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.
1478 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1479 $trail = substr( $url, $m2[0][1] ) . $trail;
1480 $url = substr( $url, 0, $m2[0][1] );
1483 # Move trailing punctuation to $trail
1485 # If there is no left bracket, then consider right brackets fair game too
1486 if ( strpos( $url, '(' ) === false ) {
1490 $urlRev = strrev( $url );
1491 $numSepChars = strspn( $urlRev, $sep );
1492 # Don't break a trailing HTML entity by moving the ; into $trail
1493 # This is in hot code, so use substr_compare to avoid having to
1494 # create a new string object for the comparison
1495 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0 ) {
1496 # more optimization: instead of running preg_match with a $
1497 # anchor, which can be slow, do the match on the reversed
1498 # string starting at the desired offset.
1499 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1500 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1504 if ( $numSepChars ) {
1505 $trail = substr( $url, -$numSepChars ) . $trail;
1506 $url = substr( $url, 0, -$numSepChars );
1509 # Verify that we still have a real URL after trail removal, and
1510 # not just lone protocol
1511 if ( strlen( $trail ) >= $numPostProto ) {
1512 return $url . $trail;
1515 $url = Sanitizer
::cleanUrl( $url );
1517 # Is this an external image?
1518 $text = $this->maybeMakeExternalImage( $url );
1519 if ( $text === false ) {
1520 # Not an image, make a link
1521 $text = Linker
::makeExternalLink( $url,
1522 $this->getConverterLanguage()->markNoConversion( $url, true ),
1524 $this->getExternalLinkAttribs( $url ) );
1525 # Register it in the output object...
1526 # Replace unnecessary URL escape codes with their equivalent characters
1527 $pasteurized = self
::normalizeLinkUrl( $url );
1528 $this->mOutput
->addExternalLink( $pasteurized );
1530 return $text . $trail;
1534 * Parse headers and return html
1538 * @param string $text
1542 public function doHeadings( $text ) {
1543 for ( $i = 6; $i >= 1; --$i ) {
1544 $h = str_repeat( '=', $i );
1545 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1551 * Replace single quotes with HTML markup
1554 * @param string $text
1556 * @return string The altered text
1558 public function doAllQuotes( $text ) {
1560 $lines = StringUtils
::explode( "\n", $text );
1561 foreach ( $lines as $line ) {
1562 $outtext .= $this->doQuotes( $line ) . "\n";
1564 $outtext = substr( $outtext, 0, -1 );
1569 * Helper function for doAllQuotes()
1571 * @param string $text
1575 public function doQuotes( $text ) {
1576 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1577 $countarr = count( $arr );
1578 if ( $countarr == 1 ) {
1582 // First, do some preliminary work. This may shift some apostrophes from
1583 // being mark-up to being text. It also counts the number of occurrences
1584 // of bold and italics mark-ups.
1587 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1588 $thislen = strlen( $arr[$i] );
1589 // If there are ever four apostrophes, assume the first is supposed to
1590 // be text, and the remaining three constitute mark-up for bold text.
1591 // (bug 13227: ''''foo'''' turns into ' ''' foo ' ''')
1592 if ( $thislen == 4 ) {
1593 $arr[$i - 1] .= "'";
1596 } elseif ( $thislen > 5 ) {
1597 // If there are more than 5 apostrophes in a row, assume they're all
1598 // text except for the last 5.
1599 // (bug 13227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1600 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1604 // Count the number of occurrences of bold and italics mark-ups.
1605 if ( $thislen == 2 ) {
1607 } elseif ( $thislen == 3 ) {
1609 } elseif ( $thislen == 5 ) {
1615 // If there is an odd number of both bold and italics, it is likely
1616 // that one of the bold ones was meant to be an apostrophe followed
1617 // by italics. Which one we cannot know for certain, but it is more
1618 // likely to be one that has a single-letter word before it.
1619 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1620 $firstsingleletterword = -1;
1621 $firstmultiletterword = -1;
1623 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1624 if ( strlen( $arr[$i] ) == 3 ) {
1625 $x1 = substr( $arr[$i - 1], -1 );
1626 $x2 = substr( $arr[$i - 1], -2, 1 );
1627 if ( $x1 === ' ' ) {
1628 if ( $firstspace == -1 ) {
1631 } elseif ( $x2 === ' ' ) {
1632 $firstsingleletterword = $i;
1633 // if $firstsingleletterword is set, we don't
1634 // look at the other options, so we can bail early.
1637 if ( $firstmultiletterword == -1 ) {
1638 $firstmultiletterword = $i;
1644 // If there is a single-letter word, use it!
1645 if ( $firstsingleletterword > -1 ) {
1646 $arr[$firstsingleletterword] = "''";
1647 $arr[$firstsingleletterword - 1] .= "'";
1648 } elseif ( $firstmultiletterword > -1 ) {
1649 // If not, but there's a multi-letter word, use that one.
1650 $arr[$firstmultiletterword] = "''";
1651 $arr[$firstmultiletterword - 1] .= "'";
1652 } elseif ( $firstspace > -1 ) {
1653 // ... otherwise use the first one that has neither.
1654 // (notice that it is possible for all three to be -1 if, for example,
1655 // there is only one pentuple-apostrophe in the line)
1656 $arr[$firstspace] = "''";
1657 $arr[$firstspace - 1] .= "'";
1661 // Now let's actually convert our apostrophic mush to HTML!
1666 foreach ( $arr as $r ) {
1667 if ( ( $i %
2 ) == 0 ) {
1668 if ( $state === 'both' ) {
1674 $thislen = strlen( $r );
1675 if ( $thislen == 2 ) {
1676 if ( $state === 'i' ) {
1679 } elseif ( $state === 'bi' ) {
1682 } elseif ( $state === 'ib' ) {
1683 $output .= '</b></i><b>';
1685 } elseif ( $state === 'both' ) {
1686 $output .= '<b><i>' . $buffer . '</i>';
1688 } else { // $state can be 'b' or ''
1692 } elseif ( $thislen == 3 ) {
1693 if ( $state === 'b' ) {
1696 } elseif ( $state === 'bi' ) {
1697 $output .= '</i></b><i>';
1699 } elseif ( $state === 'ib' ) {
1702 } elseif ( $state === 'both' ) {
1703 $output .= '<i><b>' . $buffer . '</b>';
1705 } else { // $state can be 'i' or ''
1709 } elseif ( $thislen == 5 ) {
1710 if ( $state === 'b' ) {
1711 $output .= '</b><i>';
1713 } elseif ( $state === 'i' ) {
1714 $output .= '</i><b>';
1716 } elseif ( $state === 'bi' ) {
1717 $output .= '</i></b>';
1719 } elseif ( $state === 'ib' ) {
1720 $output .= '</b></i>';
1722 } elseif ( $state === 'both' ) {
1723 $output .= '<i><b>' . $buffer . '</b></i>';
1725 } else { // ($state == '')
1733 // Now close all remaining tags. Notice that the order is important.
1734 if ( $state === 'b' ||
$state === 'ib' ) {
1737 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1740 if ( $state === 'bi' ) {
1743 // There might be lonely ''''', so make sure we have a buffer
1744 if ( $state === 'both' && $buffer ) {
1745 $output .= '<b><i>' . $buffer . '</i></b>';
1751 * Replace external links (REL)
1753 * Note: this is all very hackish and the order of execution matters a lot.
1754 * Make sure to run tests/parserTests.php if you change this code.
1758 * @param string $text
1760 * @throws MWException
1763 public function replaceExternalLinks( $text ) {
1765 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1766 if ( $bits === false ) {
1767 throw new MWException( "PCRE needs to be compiled with "
1768 . "--enable-unicode-properties in order for MediaWiki to function" );
1770 $s = array_shift( $bits );
1773 while ( $i < count( $bits ) ) {
1776 $text = $bits[$i++
];
1777 $trail = $bits[$i++
];
1779 # The characters '<' and '>' (which were escaped by
1780 # removeHTMLtags()) should not be included in
1781 # URLs, per RFC 2396.
1783 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1784 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1785 $url = substr( $url, 0, $m2[0][1] );
1788 # If the link text is an image URL, replace it with an <img> tag
1789 # This happened by accident in the original parser, but some people used it extensively
1790 $img = $this->maybeMakeExternalImage( $text );
1791 if ( $img !== false ) {
1797 # Set linktype for CSS - if URL==text, link is essentially free
1798 $linktype = ( $text === $url ) ?
'free' : 'text';
1800 # No link text, e.g. [http://domain.tld/some.link]
1801 if ( $text == '' ) {
1803 $langObj = $this->getTargetLanguage();
1804 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1805 $linktype = 'autonumber';
1807 # Have link text, e.g. [http://domain.tld/some.link text]s
1809 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1812 $text = $this->getConverterLanguage()->markNoConversion( $text );
1814 $url = Sanitizer
::cleanUrl( $url );
1816 # Use the encoded URL
1817 # This means that users can paste URLs directly into the text
1818 # Funny characters like ö aren't valid in URLs anyway
1819 # This was changed in August 2004
1820 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1821 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1823 # Register link in the output object.
1824 # Replace unnecessary URL escape codes with the referenced character
1825 # This prevents spammers from hiding links from the filters
1826 $pasteurized = self
::normalizeLinkUrl( $url );
1827 $this->mOutput
->addExternalLink( $pasteurized );
1834 * Get the rel attribute for a particular external link.
1837 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1838 * nofollow if appropriate
1839 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1840 * @return string|null Rel attribute for $url
1842 public static function getExternalLinkRel( $url = false, $title = null ) {
1843 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1844 $ns = $title ?
$title->getNamespace() : false;
1845 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1846 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1854 * Get an associative array of additional HTML attributes appropriate for a
1855 * particular external link. This currently may include rel => nofollow
1856 * (depending on configuration, namespace, and the URL's domain) and/or a
1857 * target attribute (depending on configuration).
1859 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1860 * nofollow if appropriate
1861 * @return array Associative array of HTML attributes
1863 public function getExternalLinkAttribs( $url = false ) {
1865 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1867 if ( $this->mOptions
->getExternalLinkTarget() ) {
1868 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1874 * Replace unusual escape codes in a URL with their equivalent characters
1876 * @deprecated since 1.24, use normalizeLinkUrl
1877 * @param string $url
1880 public static function replaceUnusualEscapes( $url ) {
1881 wfDeprecated( __METHOD__
, '1.24' );
1882 return self
::normalizeLinkUrl( $url );
1886 * Replace unusual escape codes in a URL with their equivalent characters
1888 * This generally follows the syntax defined in RFC 3986, with special
1889 * consideration for HTTP query strings.
1891 * @param string $url
1894 public static function normalizeLinkUrl( $url ) {
1895 # First, make sure unsafe characters are encoded
1896 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
1898 return rawurlencode( $m[0] );
1904 $end = strlen( $url );
1906 # Fragment part - 'fragment'
1907 $start = strpos( $url, '#' );
1908 if ( $start !== false && $start < $end ) {
1909 $ret = self
::normalizeUrlComponent(
1910 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
1914 # Query part - 'query' minus &=+;
1915 $start = strpos( $url, '?' );
1916 if ( $start !== false && $start < $end ) {
1917 $ret = self
::normalizeUrlComponent(
1918 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
1922 # Scheme and path part - 'pchar'
1923 # (we assume no userinfo or encoded colons in the host)
1924 $ret = self
::normalizeUrlComponent(
1925 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
1930 private static function normalizeUrlComponent( $component, $unsafe ) {
1931 $callback = function ( $matches ) use ( $unsafe ) {
1932 $char = urldecode( $matches[0] );
1933 $ord = ord( $char );
1934 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
1938 # Leave it escaped, but use uppercase for a-f
1939 return strtoupper( $matches[0] );
1942 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
1946 * make an image if it's allowed, either through the global
1947 * option, through the exception, or through the on-wiki whitelist
1949 * @param string $url
1953 private function maybeMakeExternalImage( $url ) {
1954 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1955 $imagesexception = !empty( $imagesfrom );
1957 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1958 if ( $imagesexception && is_array( $imagesfrom ) ) {
1959 $imagematch = false;
1960 foreach ( $imagesfrom as $match ) {
1961 if ( strpos( $url, $match ) === 0 ) {
1966 } elseif ( $imagesexception ) {
1967 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1969 $imagematch = false;
1972 if ( $this->mOptions
->getAllowExternalImages()
1973 ||
( $imagesexception && $imagematch )
1975 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1977 $text = Linker
::makeExternalImage( $url );
1980 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1981 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
1983 $whitelist = explode(
1985 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
1988 foreach ( $whitelist as $entry ) {
1989 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1990 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1993 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1994 # Image matches a whitelist entry
1995 $text = Linker
::makeExternalImage( $url );
2004 * Process [[ ]] wikilinks
2008 * @return string Processed text
2012 public function replaceInternalLinks( $s ) {
2013 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
2018 * Process [[ ]] wikilinks (RIL)
2020 * @throws MWException
2021 * @return LinkHolderArray
2025 public function replaceInternalLinks2( &$s ) {
2026 global $wgExtraInterlanguageLinkPrefixes;
2028 static $tc = false, $e1, $e1_img;
2029 # the % is needed to support urlencoded titles as well
2031 $tc = Title
::legalChars() . '#%';
2032 # Match a link having the form [[namespace:link|alternate]]trail
2033 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2034 # Match cases where there is no "]]", which might still be images
2035 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2038 $holders = new LinkHolderArray( $this );
2040 # split the entire text string on occurrences of [[
2041 $a = StringUtils
::explode( '[[', ' ' . $s );
2042 # get the first element (all text up to first [[), and remove the space we added
2045 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2046 $s = substr( $s, 1 );
2048 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2050 if ( $useLinkPrefixExtension ) {
2051 # Match the end of a line for a word that's not followed by whitespace,
2052 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2054 $charset = $wgContLang->linkPrefixCharset();
2055 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2058 if ( is_null( $this->mTitle
) ) {
2059 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
2061 $nottalk = !$this->mTitle
->isTalkPage();
2063 if ( $useLinkPrefixExtension ) {
2065 if ( preg_match( $e2, $s, $m ) ) {
2066 $first_prefix = $m[2];
2068 $first_prefix = false;
2074 $useSubpages = $this->areSubpagesAllowed();
2076 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
2077 # Loop for each link
2078 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2079 // @codingStandardsIgnoreStart
2081 # Check for excessive memory usage
2082 if ( $holders->isBig() ) {
2084 # Do the existence check, replace the link holders and clear the array
2085 $holders->replace( $s );
2089 if ( $useLinkPrefixExtension ) {
2090 if ( preg_match( $e2, $s, $m ) ) {
2097 if ( $first_prefix ) {
2098 $prefix = $first_prefix;
2099 $first_prefix = false;
2103 $might_be_img = false;
2105 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2107 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2108 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2109 # the real problem is with the $e1 regex
2112 # Still some problems for cases where the ] is meant to be outside punctuation,
2113 # and no image is in sight. See bug 2095.
2116 && substr( $m[3], 0, 1 ) === ']'
2117 && strpos( $text, '[' ) !== false
2119 $text .= ']'; # so that replaceExternalLinks($text) works later
2120 $m[3] = substr( $m[3], 1 );
2122 # fix up urlencoded title texts
2123 if ( strpos( $m[1], '%' ) !== false ) {
2124 # Should anchors '#' also be rejected?
2125 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) );
2128 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2129 # Invalid, but might be an image with a link in its caption
2130 $might_be_img = true;
2132 if ( strpos( $m[1], '%' ) !== false ) {
2133 $m[1] = rawurldecode( $m[1] );
2136 } else { # Invalid form; output directly
2137 $s .= $prefix . '[[' . $line;
2143 # Don't allow internal links to pages containing
2144 # PROTO: where PROTO is a valid URL protocol; these
2145 # should be external links.
2146 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2147 $s .= $prefix . '[[' . $line;
2151 # Make subpage if necessary
2152 if ( $useSubpages ) {
2153 $link = $this->maybeDoSubpageLink( $origLink, $text );
2158 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2160 # Strip off leading ':'
2161 $link = substr( $link, 1 );
2164 $unstrip = $this->mStripState
->unstripNoWiki( $link );
2165 $nt = is_string( $unstrip ) ? Title
::newFromText( $unstrip ) : null;
2166 if ( $nt === null ) {
2167 $s .= $prefix . '[[' . $line;
2171 $ns = $nt->getNamespace();
2172 $iw = $nt->getInterwiki();
2174 if ( $might_be_img ) { # if this is actually an invalid link
2175 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2178 # look at the next 'line' to see if we can close it there
2180 $next_line = $a->current();
2181 if ( $next_line === false ||
$next_line === null ) {
2184 $m = explode( ']]', $next_line, 3 );
2185 if ( count( $m ) == 3 ) {
2186 # the first ]] closes the inner link, the second the image
2188 $text .= "[[{$m[0]}]]{$m[1]}";
2191 } elseif ( count( $m ) == 2 ) {
2192 # if there's exactly one ]] that's fine, we'll keep looking
2193 $text .= "[[{$m[0]}]]{$m[1]}";
2195 # if $next_line is invalid too, we need look no further
2196 $text .= '[[' . $next_line;
2201 # we couldn't find the end of this imageLink, so output it raw
2202 # but don't ignore what might be perfectly normal links in the text we've examined
2203 $holders->merge( $this->replaceInternalLinks2( $text ) );
2204 $s .= "{$prefix}[[$link|$text";
2205 # note: no $trail, because without an end, there *is* no trail
2208 } else { # it's not an image, so output it raw
2209 $s .= "{$prefix}[[$link|$text";
2210 # note: no $trail, because without an end, there *is* no trail
2215 $wasblank = ( $text == '' );
2219 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
2220 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2221 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2222 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2223 $text = $this->doQuotes( $text );
2226 # Link not escaped by : , create the various objects
2227 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2230 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2231 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2232 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2235 # Bug 24502: filter duplicates
2236 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2237 $this->mLangLinkLanguages
[$iw] = true;
2238 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2241 $s = rtrim( $s . $prefix );
2242 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2246 if ( $ns == NS_FILE
) {
2247 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2249 # if no parameters were passed, $text
2250 # becomes something like "File:Foo.png",
2251 # which we don't want to pass on to the
2255 # recursively parse links inside the image caption
2256 # actually, this will parse them in any other parameters, too,
2257 # but it might be hard to fix that, and it doesn't matter ATM
2258 $text = $this->replaceExternalLinks( $text );
2259 $holders->merge( $this->replaceInternalLinks2( $text ) );
2261 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2262 $s .= $prefix . $this->armorLinks(
2263 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2265 $s .= $prefix . $trail;
2270 if ( $ns == NS_CATEGORY
) {
2271 $s = rtrim( $s . "\n" ); # bug 87
2274 $sortkey = $this->getDefaultSort();
2278 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2279 $sortkey = str_replace( "\n", '', $sortkey );
2280 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2281 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2284 * Strip the whitespace Category links produce, see bug 87
2286 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2292 # Self-link checking. For some languages, variants of the title are checked in
2293 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2294 # for linking to a different variant.
2295 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2296 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2300 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2301 # @todo FIXME: Should do batch file existence checks, see comment below
2302 if ( $ns == NS_MEDIA
) {
2303 # Give extensions a chance to select the file revision for us
2306 Hooks
::run( 'BeforeParserFetchFileAndTitle',
2307 array( $this, $nt, &$options, &$descQuery ) );
2308 # Fetch and register the file (file title may be different via hooks)
2309 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2310 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2311 $s .= $prefix . $this->armorLinks(
2312 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2316 # Some titles, such as valid special pages or files in foreign repos, should
2317 # be shown as bluelinks even though they're not included in the page table
2319 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2320 # batch file existence checks for NS_FILE and NS_MEDIA
2321 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2322 $this->mOutput
->addLink( $nt );
2323 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2325 # Links will be added to the output link list after checking
2326 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2333 * Render a forced-blue link inline; protect against double expansion of
2334 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2335 * Since this little disaster has to split off the trail text to avoid
2336 * breaking URLs in the following text without breaking trails on the
2337 * wiki links, it's been made into a horrible function.
2340 * @param string $text
2341 * @param array|string $query
2342 * @param string $trail
2343 * @param string $prefix
2344 * @return string HTML-wikitext mix oh yuck
2346 public function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2347 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2349 if ( is_string( $query ) ) {
2350 $query = wfCgiToArray( $query );
2352 if ( $text == '' ) {
2353 $text = htmlspecialchars( $nt->getPrefixedText() );
2356 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2358 return $this->armorLinks( $link ) . $trail;
2362 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2363 * going to go through further parsing steps before inline URL expansion.
2365 * Not needed quite as much as it used to be since free links are a bit
2366 * more sensible these days. But bracketed links are still an issue.
2368 * @param string $text More-or-less HTML
2369 * @return string Less-or-more HTML with NOPARSE bits
2371 public function armorLinks( $text ) {
2372 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2373 self
::MARKER_PREFIX
. "NOPARSE$1", $text );
2377 * Return true if subpage links should be expanded on this page.
2380 public function areSubpagesAllowed() {
2381 # Some namespaces don't allow subpages
2382 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2386 * Handle link to subpage if necessary
2388 * @param string $target The source of the link
2389 * @param string &$text The link text, modified as necessary
2390 * @return string The full name of the link
2393 public function maybeDoSubpageLink( $target, &$text ) {
2394 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2398 * Used by doBlockLevels()
2403 public function closeParagraph() {
2405 if ( $this->mLastSection
!= '' ) {
2406 $result = '</' . $this->mLastSection
. ">\n";
2408 $this->mInPre
= false;
2409 $this->mLastSection
= '';
2414 * getCommon() returns the length of the longest common substring
2415 * of both arguments, starting at the beginning of both.
2418 * @param string $st1
2419 * @param string $st2
2423 public function getCommon( $st1, $st2 ) {
2424 $fl = strlen( $st1 );
2425 $shorter = strlen( $st2 );
2426 if ( $fl < $shorter ) {
2430 for ( $i = 0; $i < $shorter; ++
$i ) {
2431 if ( $st1[$i] != $st2[$i] ) {
2439 * These next three functions open, continue, and close the list
2440 * element appropriate to the prefix character passed into them.
2443 * @param string $char
2447 public function openList( $char ) {
2448 $result = $this->closeParagraph();
2450 if ( '*' === $char ) {
2451 $result .= "<ul><li>";
2452 } elseif ( '#' === $char ) {
2453 $result .= "<ol><li>";
2454 } elseif ( ':' === $char ) {
2455 $result .= "<dl><dd>";
2456 } elseif ( ';' === $char ) {
2457 $result .= "<dl><dt>";
2458 $this->mDTopen
= true;
2460 $result = '<!-- ERR 1 -->';
2468 * @param string $char
2473 public function nextItem( $char ) {
2474 if ( '*' === $char ||
'#' === $char ) {
2475 return "</li>\n<li>";
2476 } elseif ( ':' === $char ||
';' === $char ) {
2478 if ( $this->mDTopen
) {
2481 if ( ';' === $char ) {
2482 $this->mDTopen
= true;
2483 return $close . '<dt>';
2485 $this->mDTopen
= false;
2486 return $close . '<dd>';
2489 return '<!-- ERR 2 -->';
2494 * @param string $char
2499 public function closeList( $char ) {
2500 if ( '*' === $char ) {
2501 $text = "</li></ul>";
2502 } elseif ( '#' === $char ) {
2503 $text = "</li></ol>";
2504 } elseif ( ':' === $char ) {
2505 if ( $this->mDTopen
) {
2506 $this->mDTopen
= false;
2507 $text = "</dt></dl>";
2509 $text = "</dd></dl>";
2512 return '<!-- ERR 3 -->';
2519 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2521 * @param string $text
2522 * @param bool $linestart Whether or not this is at the start of a line.
2524 * @return string The lists rendered as HTML
2526 public function doBlockLevels( $text, $linestart ) {
2528 # Parsing through the text line by line. The main thing
2529 # happening here is handling of block-level elements p, pre,
2530 # and making lists from lines starting with * # : etc.
2532 $textLines = StringUtils
::explode( "\n", $text );
2534 $lastPrefix = $output = '';
2535 $this->mDTopen
= $inBlockElem = false;
2537 $paragraphStack = false;
2538 $inBlockquote = false;
2540 foreach ( $textLines as $oLine ) {
2542 if ( !$linestart ) {
2552 $lastPrefixLength = strlen( $lastPrefix );
2553 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2554 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2555 # If not in a <pre> element, scan for and figure out what prefixes are there.
2556 if ( !$this->mInPre
) {
2557 # Multiple prefixes may abut each other for nested lists.
2558 $prefixLength = strspn( $oLine, '*#:;' );
2559 $prefix = substr( $oLine, 0, $prefixLength );
2562 # ; and : are both from definition-lists, so they're equivalent
2563 # for the purposes of determining whether or not we need to open/close
2565 $prefix2 = str_replace( ';', ':', $prefix );
2566 $t = substr( $oLine, $prefixLength );
2567 $this->mInPre
= (bool)$preOpenMatch;
2569 # Don't interpret any other prefixes in preformatted text
2571 $prefix = $prefix2 = '';
2576 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2577 # Same as the last item, so no need to deal with nesting or opening stuff
2578 $output .= $this->nextItem( substr( $prefix, -1 ) );
2579 $paragraphStack = false;
2581 if ( substr( $prefix, -1 ) === ';' ) {
2582 # The one nasty exception: definition lists work like this:
2583 # ; title : definition text
2584 # So we check for : in the remainder text to split up the
2585 # title and definition, without b0rking links.
2587 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2589 $output .= $term . $this->nextItem( ':' );
2592 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2593 # We need to open or close prefixes, or both.
2595 # Either open or close a level...
2596 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2597 $paragraphStack = false;
2599 # Close all the prefixes which aren't shared.
2600 while ( $commonPrefixLength < $lastPrefixLength ) {
2601 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2602 --$lastPrefixLength;
2605 # Continue the current prefix if appropriate.
2606 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2607 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2610 # Open prefixes where appropriate.
2611 if ( $lastPrefix && $prefixLength > $commonPrefixLength ) {
2614 while ( $prefixLength > $commonPrefixLength ) {
2615 $char = substr( $prefix, $commonPrefixLength, 1 );
2616 $output .= $this->openList( $char );
2618 if ( ';' === $char ) {
2619 # @todo FIXME: This is dupe of code above
2620 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2622 $output .= $term . $this->nextItem( ':' );
2625 ++
$commonPrefixLength;
2627 if ( !$prefixLength && $lastPrefix ) {
2630 $lastPrefix = $prefix2;
2633 # If we have no prefixes, go to paragraph mode.
2634 if ( 0 == $prefixLength ) {
2635 # No prefix (not in list)--go to paragraph mode
2636 # XXX: use a stack for nestable elements like span, table and div
2637 $openmatch = preg_match(
2638 '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|'
2639 . '<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS',
2642 $closematch = preg_match(
2643 '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'
2644 . '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|<\\/mw:|'
2645 . self
::MARKER_PREFIX
2646 . '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS',
2650 if ( $openmatch ||
$closematch ) {
2651 $paragraphStack = false;
2652 # @todo bug 5718: paragraph closed
2653 $output .= $this->closeParagraph();
2654 if ( $preOpenMatch && !$preCloseMatch ) {
2655 $this->mInPre
= true;
2658 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t, $bqMatch, PREG_OFFSET_CAPTURE
, $bqOffset ) ) {
2659 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
2660 $bqOffset = $bqMatch[0][1] +
strlen( $bqMatch[0][0] );
2662 $inBlockElem = !$closematch;
2663 } elseif ( !$inBlockElem && !$this->mInPre
) {
2664 if ( ' ' == substr( $t, 0, 1 )
2665 && ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' )
2669 if ( $this->mLastSection
!== 'pre' ) {
2670 $paragraphStack = false;
2671 $output .= $this->closeParagraph() . '<pre>';
2672 $this->mLastSection
= 'pre';
2674 $t = substr( $t, 1 );
2677 if ( trim( $t ) === '' ) {
2678 if ( $paragraphStack ) {
2679 $output .= $paragraphStack . '<br />';
2680 $paragraphStack = false;
2681 $this->mLastSection
= 'p';
2683 if ( $this->mLastSection
!== 'p' ) {
2684 $output .= $this->closeParagraph();
2685 $this->mLastSection
= '';
2686 $paragraphStack = '<p>';
2688 $paragraphStack = '</p><p>';
2692 if ( $paragraphStack ) {
2693 $output .= $paragraphStack;
2694 $paragraphStack = false;
2695 $this->mLastSection
= 'p';
2696 } elseif ( $this->mLastSection
!== 'p' ) {
2697 $output .= $this->closeParagraph() . '<p>';
2698 $this->mLastSection
= 'p';
2704 # somewhere above we forget to get out of pre block (bug 785)
2705 if ( $preCloseMatch && $this->mInPre
) {
2706 $this->mInPre
= false;
2708 if ( $paragraphStack === false ) {
2710 if ( $prefixLength === 0 ) {
2715 while ( $prefixLength ) {
2716 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2718 if ( !$prefixLength ) {
2722 if ( $this->mLastSection
!= '' ) {
2723 $output .= '</' . $this->mLastSection
. '>';
2724 $this->mLastSection
= '';
2731 * Split up a string on ':', ignoring any occurrences inside tags
2732 * to prevent illegal overlapping.
2734 * @param string $str The string to split
2735 * @param string &$before Set to everything before the ':'
2736 * @param string &$after Set to everything after the ':'
2737 * @throws MWException
2738 * @return string The position of the ':', or false if none found
2740 public function findColonNoLinks( $str, &$before, &$after ) {
2742 $pos = strpos( $str, ':' );
2743 if ( $pos === false ) {
2748 $lt = strpos( $str, '<' );
2749 if ( $lt === false ||
$lt > $pos ) {
2750 # Easy; no tag nesting to worry about
2751 $before = substr( $str, 0, $pos );
2752 $after = substr( $str, $pos +
1 );
2756 # Ugly state machine to walk through avoiding tags.
2757 $state = self
::COLON_STATE_TEXT
;
2759 $len = strlen( $str );
2760 for ( $i = 0; $i < $len; $i++
) {
2764 # (Using the number is a performance hack for common cases)
2765 case 0: # self::COLON_STATE_TEXT:
2768 # Could be either a <start> tag or an </end> tag
2769 $state = self
::COLON_STATE_TAGSTART
;
2772 if ( $stack == 0 ) {
2774 $before = substr( $str, 0, $i );
2775 $after = substr( $str, $i +
1 );
2778 # Embedded in a tag; don't break it.
2781 # Skip ahead looking for something interesting
2782 $colon = strpos( $str, ':', $i );
2783 if ( $colon === false ) {
2784 # Nothing else interesting
2787 $lt = strpos( $str, '<', $i );
2788 if ( $stack === 0 ) {
2789 if ( $lt === false ||
$colon < $lt ) {
2791 $before = substr( $str, 0, $colon );
2792 $after = substr( $str, $colon +
1 );
2796 if ( $lt === false ) {
2797 # Nothing else interesting to find; abort!
2798 # We're nested, but there's no close tags left. Abort!
2801 # Skip ahead to next tag start
2803 $state = self
::COLON_STATE_TAGSTART
;
2806 case 1: # self::COLON_STATE_TAG:
2811 $state = self
::COLON_STATE_TEXT
;
2814 # Slash may be followed by >?
2815 $state = self
::COLON_STATE_TAGSLASH
;
2821 case 2: # self::COLON_STATE_TAGSTART:
2824 $state = self
::COLON_STATE_CLOSETAG
;
2827 $state = self
::COLON_STATE_COMMENT
;
2830 # Illegal early close? This shouldn't happen D:
2831 $state = self
::COLON_STATE_TEXT
;
2834 $state = self
::COLON_STATE_TAG
;
2837 case 3: # self::COLON_STATE_CLOSETAG:
2842 wfDebug( __METHOD__
. ": Invalid input; too many close tags\n" );
2845 $state = self
::COLON_STATE_TEXT
;
2848 case self
::COLON_STATE_TAGSLASH
:
2850 # Yes, a self-closed tag <blah/>
2851 $state = self
::COLON_STATE_TEXT
;
2853 # Probably we're jumping the gun, and this is an attribute
2854 $state = self
::COLON_STATE_TAG
;
2857 case 5: # self::COLON_STATE_COMMENT:
2859 $state = self
::COLON_STATE_COMMENTDASH
;
2862 case self
::COLON_STATE_COMMENTDASH
:
2864 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2866 $state = self
::COLON_STATE_COMMENT
;
2869 case self
::COLON_STATE_COMMENTDASHDASH
:
2871 $state = self
::COLON_STATE_TEXT
;
2873 $state = self
::COLON_STATE_COMMENT
;
2877 throw new MWException( "State machine error in " . __METHOD__
);
2881 wfDebug( __METHOD__
. ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2888 * Return value of a magic variable (like PAGENAME)
2893 * @param bool|PPFrame $frame
2895 * @throws MWException
2898 public function getVariableValue( $index, $frame = false ) {
2899 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2900 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2902 if ( is_null( $this->mTitle
) ) {
2903 // If no title set, bad things are going to happen
2904 // later. Title should always be set since this
2905 // should only be called in the middle of a parse
2906 // operation (but the unit-tests do funky stuff)
2907 throw new MWException( __METHOD__
. ' Should only be '
2908 . ' called while parsing (no title set)' );
2912 * Some of these require message or data lookups and can be
2913 * expensive to check many times.
2915 if ( Hooks
::run( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2916 if ( isset( $this->mVarCache
[$index] ) ) {
2917 return $this->mVarCache
[$index];
2921 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2922 Hooks
::run( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2924 $pageLang = $this->getFunctionLang();
2930 case 'currentmonth':
2931 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ) );
2933 case 'currentmonth1':
2934 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2936 case 'currentmonthname':
2937 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2939 case 'currentmonthnamegen':
2940 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2942 case 'currentmonthabbrev':
2943 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2946 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ) );
2949 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ) );
2952 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ) );
2955 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2957 case 'localmonthname':
2958 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2960 case 'localmonthnamegen':
2961 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2963 case 'localmonthabbrev':
2964 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2967 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ) );
2970 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ) );
2973 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2976 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2978 case 'fullpagename':
2979 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2981 case 'fullpagenamee':
2982 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2985 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2987 case 'subpagenamee':
2988 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2990 case 'rootpagename':
2991 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2993 case 'rootpagenamee':
2994 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
2997 $this->mTitle
->getRootText()
3000 case 'basepagename':
3001 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
3003 case 'basepagenamee':
3004 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
3007 $this->mTitle
->getBaseText()
3010 case 'talkpagename':
3011 if ( $this->mTitle
->canTalk() ) {
3012 $talkPage = $this->mTitle
->getTalkPage();
3013 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
3018 case 'talkpagenamee':
3019 if ( $this->mTitle
->canTalk() ) {
3020 $talkPage = $this->mTitle
->getTalkPage();
3021 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
3026 case 'subjectpagename':
3027 $subjPage = $this->mTitle
->getSubjectPage();
3028 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
3030 case 'subjectpagenamee':
3031 $subjPage = $this->mTitle
->getSubjectPage();
3032 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
3034 case 'pageid': // requested in bug 23427
3035 $pageid = $this->getTitle()->getArticleID();
3036 if ( $pageid == 0 ) {
3037 # 0 means the page doesn't exist in the database,
3038 # which means the user is previewing a new page.
3039 # The vary-revision flag must be set, because the magic word
3040 # will have a different value once the page is saved.
3041 $this->mOutput
->setFlag( 'vary-revision' );
3042 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
3044 $value = $pageid ?
$pageid : null;
3047 # Let the edit saving system know we should parse the page
3048 # *after* a revision ID has been assigned.
3049 $this->mOutput
->setFlag( 'vary-revision' );
3050 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
3051 $value = $this->mRevisionId
;
3054 # Let the edit saving system know we should parse the page
3055 # *after* a revision ID has been assigned. This is for null edits.
3056 $this->mOutput
->setFlag( 'vary-revision' );
3057 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
3058 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
3060 case 'revisionday2':
3061 # Let the edit saving system know we should parse the page
3062 # *after* a revision ID has been assigned. This is for null edits.
3063 $this->mOutput
->setFlag( 'vary-revision' );
3064 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
3065 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
3067 case 'revisionmonth':
3068 # Let the edit saving system know we should parse the page
3069 # *after* a revision ID has been assigned. This is for null edits.
3070 $this->mOutput
->setFlag( 'vary-revision' );
3071 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
3072 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
3074 case 'revisionmonth1':
3075 # Let the edit saving system know we should parse the page
3076 # *after* a revision ID has been assigned. This is for null edits.
3077 $this->mOutput
->setFlag( 'vary-revision' );
3078 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
3079 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
3081 case 'revisionyear':
3082 # Let the edit saving system know we should parse the page
3083 # *after* a revision ID has been assigned. This is for null edits.
3084 $this->mOutput
->setFlag( 'vary-revision' );
3085 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
3086 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
3088 case 'revisiontimestamp':
3089 # Let the edit saving system know we should parse the page
3090 # *after* a revision ID has been assigned. This is for null edits.
3091 $this->mOutput
->setFlag( 'vary-revision' );
3092 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
3093 $value = $this->getRevisionTimestamp();
3095 case 'revisionuser':
3096 # Let the edit saving system know we should parse the page
3097 # *after* a revision ID has been assigned. This is for null edits.
3098 $this->mOutput
->setFlag( 'vary-revision' );
3099 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
3100 $value = $this->getRevisionUser();
3102 case 'revisionsize':
3103 # Let the edit saving system know we should parse the page
3104 # *after* a revision ID has been assigned. This is for null edits.
3105 $this->mOutput
->setFlag( 'vary-revision' );
3106 wfDebug( __METHOD__
. ": {{REVISIONSIZE}} used, setting vary-revision...\n" );
3107 $value = $this->getRevisionSize();
3110 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3113 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3115 case 'namespacenumber':
3116 $value = $this->mTitle
->getNamespace();
3119 $value = $this->mTitle
->canTalk()
3120 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
3124 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
3126 case 'subjectspace':
3127 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
3129 case 'subjectspacee':
3130 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
3132 case 'currentdayname':
3133 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
3136 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
3139 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
3142 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
3145 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3146 # int to remove the padding
3147 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
3150 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
3152 case 'localdayname':
3153 $value = $pageLang->getWeekdayName(
3154 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
3158 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
3161 $value = $pageLang->time(
3162 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
3168 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
3171 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3172 # int to remove the padding
3173 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
3176 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
3178 case 'numberofarticles':
3179 $value = $pageLang->formatNum( SiteStats
::articles() );
3181 case 'numberoffiles':
3182 $value = $pageLang->formatNum( SiteStats
::images() );
3184 case 'numberofusers':
3185 $value = $pageLang->formatNum( SiteStats
::users() );
3187 case 'numberofactiveusers':
3188 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
3190 case 'numberofpages':
3191 $value = $pageLang->formatNum( SiteStats
::pages() );
3193 case 'numberofadmins':
3194 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
3196 case 'numberofedits':
3197 $value = $pageLang->formatNum( SiteStats
::edits() );
3199 case 'currenttimestamp':
3200 $value = wfTimestamp( TS_MW
, $ts );
3202 case 'localtimestamp':
3203 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
3205 case 'currentversion':
3206 $value = SpecialVersion
::getVersion();
3209 return $wgArticlePath;
3215 return $wgServerName;
3217 return $wgScriptPath;
3219 return $wgStylePath;
3220 case 'directionmark':
3221 return $pageLang->getDirMark();
3222 case 'contentlanguage':
3223 global $wgLanguageCode;
3224 return $wgLanguageCode;
3225 case 'cascadingsources':
3226 $value = CoreParserFunctions
::cascadingsources( $this );
3231 'ParserGetVariableValueSwitch',
3232 array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame )
3239 $this->mVarCache
[$index] = $value;
3246 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3250 public function initialiseVariables() {
3251 $variableIDs = MagicWord
::getVariableIDs();
3252 $substIDs = MagicWord
::getSubstIDs();
3254 $this->mVariables
= new MagicWordArray( $variableIDs );
3255 $this->mSubstWords
= new MagicWordArray( $substIDs );
3259 * Preprocess some wikitext and return the document tree.
3260 * This is the ghost of replace_variables().
3262 * @param string $text The text to parse
3263 * @param int $flags Bitwise combination of:
3264 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
3265 * included. Default is to assume a direct page view.
3267 * The generated DOM tree must depend only on the input text and the flags.
3268 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3270 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3271 * change in the DOM tree for a given text, must be passed through the section identifier
3272 * in the section edit link and thus back to extractSections().
3274 * The output of this function is currently only cached in process memory, but a persistent
3275 * cache may be implemented at a later date which takes further advantage of these strict
3276 * dependency requirements.
3280 public function preprocessToDom( $text, $flags = 0 ) {
3281 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3286 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3292 public static function splitWhitespace( $s ) {
3293 $ltrimmed = ltrim( $s );
3294 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3295 $trimmed = rtrim( $ltrimmed );
3296 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3298 $w2 = substr( $ltrimmed, -$diff );
3302 return array( $w1, $trimmed, $w2 );
3306 * Replace magic variables, templates, and template arguments
3307 * with the appropriate text. Templates are substituted recursively,
3308 * taking care to avoid infinite loops.
3310 * Note that the substitution depends on value of $mOutputType:
3311 * self::OT_WIKI: only {{subst:}} templates
3312 * self::OT_PREPROCESS: templates but not extension tags
3313 * self::OT_HTML: all templates and extension tags
3315 * @param string $text The text to transform
3316 * @param bool|PPFrame $frame Object describing the arguments passed to the
3317 * template. Arguments may also be provided as an associative array, as
3318 * was the usual case before MW1.12. Providing arguments this way may be
3319 * useful for extensions wishing to perform variable replacement
3321 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3322 * double-brace expansion.
3325 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3326 # Is there any text? Also, Prevent too big inclusions!
3327 $textSize = strlen( $text );
3328 if ( $textSize < 1 ||
$textSize > $this->mOptions
->getMaxIncludeSize() ) {
3332 if ( $frame === false ) {
3333 $frame = $this->getPreprocessor()->newFrame();
3334 } elseif ( !( $frame instanceof PPFrame
) ) {
3335 wfDebug( __METHOD__
. " called using plain parameters instead of "
3336 . "a PPFrame instance. Creating custom frame.\n" );
3337 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3340 $dom = $this->preprocessToDom( $text );
3341 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3342 $text = $frame->expand( $dom, $flags );
3348 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3350 * @param array $args
3354 public static function createAssocArgs( $args ) {
3355 $assocArgs = array();
3357 foreach ( $args as $arg ) {
3358 $eqpos = strpos( $arg, '=' );
3359 if ( $eqpos === false ) {
3360 $assocArgs[$index++
] = $arg;
3362 $name = trim( substr( $arg, 0, $eqpos ) );
3363 $value = trim( substr( $arg, $eqpos +
1 ) );
3364 if ( $value === false ) {
3367 if ( $name !== false ) {
3368 $assocArgs[$name] = $value;
3377 * Warn the user when a parser limitation is reached
3378 * Will warn at most once the user per limitation type
3380 * @param string $limitationType Should be one of:
3381 * 'expensive-parserfunction' (corresponding messages:
3382 * 'expensive-parserfunction-warning',
3383 * 'expensive-parserfunction-category')
3384 * 'post-expand-template-argument' (corresponding messages:
3385 * 'post-expand-template-argument-warning',
3386 * 'post-expand-template-argument-category')
3387 * 'post-expand-template-inclusion' (corresponding messages:
3388 * 'post-expand-template-inclusion-warning',
3389 * 'post-expand-template-inclusion-category')
3390 * 'node-count-exceeded' (corresponding messages:
3391 * 'node-count-exceeded-warning',
3392 * 'node-count-exceeded-category')
3393 * 'expansion-depth-exceeded' (corresponding messages:
3394 * 'expansion-depth-exceeded-warning',
3395 * 'expansion-depth-exceeded-category')
3396 * @param string|int|null $current Current value
3397 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3398 * exceeded, provide the values (optional)
3400 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3401 # does no harm if $current and $max are present but are unnecessary for the message
3402 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3403 ->inLanguage( $this->mOptions
->getUserLangObj() )->text();
3404 $this->mOutput
->addWarning( $warning );
3405 $this->addTrackingCategory( "$limitationType-category" );
3409 * Return the text of a template, after recursively
3410 * replacing any variables or templates within the template.
3412 * @param array $piece The parts of the template
3413 * $piece['title']: the title, i.e. the part before the |
3414 * $piece['parts']: the parameter array
3415 * $piece['lineStart']: whether the brace was at the start of a line
3416 * @param PPFrame $frame The current frame, contains template arguments
3418 * @return string The text of the template
3420 public function braceSubstitution( $piece, $frame ) {
3424 // $text has been filled
3426 // wiki markup in $text should be escaped
3428 // $text is HTML, armour it against wikitext transformation
3430 // Force interwiki transclusion to be done in raw mode not rendered
3431 $forceRawInterwiki = false;
3432 // $text is a DOM node needing expansion in a child frame
3433 $isChildObj = false;
3434 // $text is a DOM node needing expansion in the current frame
3435 $isLocalObj = false;
3437 # Title object, where $text came from
3440 # $part1 is the bit before the first |, and must contain only title characters.
3441 # Various prefixes will be stripped from it later.
3442 $titleWithSpaces = $frame->expand( $piece['title'] );
3443 $part1 = trim( $titleWithSpaces );
3446 # Original title text preserved for various purposes
3447 $originalTitle = $part1;
3449 # $args is a list of argument nodes, starting from index 0, not including $part1
3450 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3451 # below won't work b/c this $args isn't an object
3452 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3454 $profileSection = null; // profile templates
3458 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3460 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3461 # Decide whether to expand template or keep wikitext as-is.
3462 if ( $this->ot
['wiki'] ) {
3463 if ( $substMatch === false ) {
3464 $literal = true; # literal when in PST with no prefix
3466 $literal = false; # expand when in PST with subst: or safesubst:
3469 if ( $substMatch == 'subst' ) {
3470 $literal = true; # literal when not in PST with plain subst:
3472 $literal = false; # expand when not in PST with safesubst: or no prefix
3476 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3483 if ( !$found && $args->getLength() == 0 ) {
3484 $id = $this->mVariables
->matchStartToEnd( $part1 );
3485 if ( $id !== false ) {
3486 $text = $this->getVariableValue( $id, $frame );
3487 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3488 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3494 # MSG, MSGNW and RAW
3497 $mwMsgnw = MagicWord
::get( 'msgnw' );
3498 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3501 # Remove obsolete MSG:
3502 $mwMsg = MagicWord
::get( 'msg' );
3503 $mwMsg->matchStartAndRemove( $part1 );
3507 $mwRaw = MagicWord
::get( 'raw' );
3508 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3509 $forceRawInterwiki = true;
3515 $colonPos = strpos( $part1, ':' );
3516 if ( $colonPos !== false ) {
3517 $func = substr( $part1, 0, $colonPos );
3518 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3519 for ( $i = 0; $i < $args->getLength(); $i++
) {
3520 $funcArgs[] = $args->item( $i );
3523 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3524 } catch ( Exception
$ex ) {
3528 # The interface for parser functions allows for extracting
3529 # flags into the local scope. Extract any forwarded flags
3535 # Finish mangling title and then check for loops.
3536 # Set $title to a Title object and $titleText to the PDBK
3539 # Split the title into page and subpage
3541 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3542 if ( $part1 !== $relative ) {
3544 $ns = $this->mTitle
->getNamespace();
3546 $title = Title
::newFromText( $part1, $ns );
3548 $titleText = $title->getPrefixedText();
3549 # Check for language variants if the template is not found
3550 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3551 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3553 # Do recursion depth check
3554 $limit = $this->mOptions
->getMaxTemplateDepth();
3555 if ( $frame->depth
>= $limit ) {
3557 $text = '<span class="error">'
3558 . wfMessage( 'parser-template-recursion-depth-warning' )
3559 ->numParams( $limit )->inContentLanguage()->text()
3565 # Load from database
3566 if ( !$found && $title ) {
3567 $profileSection = $this->mProfiler
->scopedProfileIn( $title->getPrefixedDBkey() );
3568 if ( !$title->isExternal() ) {
3569 if ( $title->isSpecialPage()
3570 && $this->mOptions
->getAllowSpecialInclusion()
3571 && $this->ot
['html']
3573 // Pass the template arguments as URL parameters.
3574 // "uselang" will have no effect since the Language object
3575 // is forced to the one defined in ParserOptions.
3576 $pageArgs = array();
3577 $argsLength = $args->getLength();
3578 for ( $i = 0; $i < $argsLength; $i++
) {
3579 $bits = $args->item( $i )->splitArg();
3580 if ( strval( $bits['index'] ) === '' ) {
3581 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3582 $value = trim( $frame->expand( $bits['value'] ) );
3583 $pageArgs[$name] = $value;
3587 // Create a new context to execute the special page
3588 $context = new RequestContext
;
3589 $context->setTitle( $title );
3590 $context->setRequest( new FauxRequest( $pageArgs ) );
3591 $context->setUser( $this->getUser() );
3592 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3593 $ret = SpecialPageFactory
::capturePath( $title, $context );
3595 $text = $context->getOutput()->getHTML();
3596 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3599 $this->disableCache();
3601 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3602 $found = false; # access denied
3603 wfDebug( __METHOD__
. ": template inclusion denied for " .
3604 $title->getPrefixedDBkey() . "\n" );
3606 list( $text, $title ) = $this->getTemplateDom( $title );
3607 if ( $text !== false ) {
3613 # If the title is valid but undisplayable, make a link to it
3614 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3615 $text = "[[:$titleText]]";
3618 } elseif ( $title->isTrans() ) {
3619 # Interwiki transclusion
3620 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3621 $text = $this->interwikiTransclude( $title, 'render' );
3624 $text = $this->interwikiTransclude( $title, 'raw' );
3625 # Preprocess it like a template
3626 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3632 # Do infinite loop check
3633 # This has to be done after redirect resolution to avoid infinite loops via redirects
3634 if ( !$frame->loopCheck( $title ) ) {
3636 $text = '<span class="error">'
3637 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3639 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3643 # If we haven't found text to substitute by now, we're done
3644 # Recover the source wikitext and return it
3646 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3647 if ( $profileSection ) {
3648 $this->mProfiler
->scopedProfileOut( $profileSection );
3650 return array( 'object' => $text );
3653 # Expand DOM-style return values in a child frame
3654 if ( $isChildObj ) {
3655 # Clean up argument array
3656 $newFrame = $frame->newChild( $args, $title );
3659 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3660 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3661 # Expansion is eligible for the empty-frame cache
3662 $text = $newFrame->cachedExpand( $titleText, $text );
3664 # Uncached expansion
3665 $text = $newFrame->expand( $text );
3668 if ( $isLocalObj && $nowiki ) {
3669 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3670 $isLocalObj = false;
3673 if ( $profileSection ) {
3674 $this->mProfiler
->scopedProfileOut( $profileSection );
3677 # Replace raw HTML by a placeholder
3679 $text = $this->insertStripItem( $text );
3680 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3681 # Escape nowiki-style return values
3682 $text = wfEscapeWikiText( $text );
3683 } elseif ( is_string( $text )
3684 && !$piece['lineStart']
3685 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3687 # Bug 529: if the template begins with a table or block-level
3688 # element, it should be treated as beginning a new line.
3689 # This behavior is somewhat controversial.
3690 $text = "\n" . $text;
3693 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3694 # Error, oversize inclusion
3695 if ( $titleText !== false ) {
3696 # Make a working, properly escaped link if possible (bug 23588)
3697 $text = "[[:$titleText]]";
3699 # This will probably not be a working link, but at least it may
3700 # provide some hint of where the problem is
3701 preg_replace( '/^:/', '', $originalTitle );
3702 $text = "[[:$originalTitle]]";
3704 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3705 . 'post-expand include size too large -->' );
3706 $this->limitationWarn( 'post-expand-template-inclusion' );
3709 if ( $isLocalObj ) {
3710 $ret = array( 'object' => $text );
3712 $ret = array( 'text' => $text );
3719 * Call a parser function and return an array with text and flags.
3721 * The returned array will always contain a boolean 'found', indicating
3722 * whether the parser function was found or not. It may also contain the
3724 * text: string|object, resulting wikitext or PP DOM object
3725 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3726 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3727 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3728 * nowiki: bool, wiki markup in $text should be escaped
3731 * @param PPFrame $frame The current frame, contains template arguments
3732 * @param string $function Function name
3733 * @param array $args Arguments to the function
3734 * @throws MWException
3737 public function callParserFunction( $frame, $function, array $args = array() ) {
3741 # Case sensitive functions
3742 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3743 $function = $this->mFunctionSynonyms
[1][$function];
3745 # Case insensitive functions
3746 $function = $wgContLang->lc( $function );
3747 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3748 $function = $this->mFunctionSynonyms
[0][$function];
3750 return array( 'found' => false );
3754 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3756 # Workaround for PHP bug 35229 and similar
3757 if ( !is_callable( $callback ) ) {
3758 throw new MWException( "Tag hook for $function is not callable\n" );
3761 $allArgs = array( &$this );
3762 if ( $flags & self
::SFH_OBJECT_ARGS
) {
3763 # Convert arguments to PPNodes and collect for appending to $allArgs
3764 $funcArgs = array();
3765 foreach ( $args as $k => $v ) {
3766 if ( $v instanceof PPNode ||
$k === 0 ) {
3769 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( array( $k => $v ) )->item( 0 );
3773 # Add a frame parameter, and pass the arguments as an array
3774 $allArgs[] = $frame;
3775 $allArgs[] = $funcArgs;
3777 # Convert arguments to plain text and append to $allArgs
3778 foreach ( $args as $k => $v ) {
3779 if ( $v instanceof PPNode
) {
3780 $allArgs[] = trim( $frame->expand( $v ) );
3781 } elseif ( is_int( $k ) && $k >= 0 ) {
3782 $allArgs[] = trim( $v );
3784 $allArgs[] = trim( "$k=$v" );
3789 $result = call_user_func_array( $callback, $allArgs );
3791 # The interface for function hooks allows them to return a wikitext
3792 # string or an array containing the string and any flags. This mungs
3793 # things around to match what this method should return.
3794 if ( !is_array( $result ) ) {
3800 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3801 $result['text'] = $result[0];
3803 unset( $result[0] );
3810 $preprocessFlags = 0;
3811 if ( isset( $result['noparse'] ) ) {
3812 $noparse = $result['noparse'];
3814 if ( isset( $result['preprocessFlags'] ) ) {
3815 $preprocessFlags = $result['preprocessFlags'];
3819 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3820 $result['isChildObj'] = true;
3827 * Get the semi-parsed DOM representation of a template with a given title,
3828 * and its redirect destination title. Cached.
3830 * @param Title $title
3834 public function getTemplateDom( $title ) {
3835 $cacheTitle = $title;
3836 $titleText = $title->getPrefixedDBkey();
3838 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3839 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3840 $title = Title
::makeTitle( $ns, $dbk );
3841 $titleText = $title->getPrefixedDBkey();
3843 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3844 return array( $this->mTplDomCache
[$titleText], $title );
3847 # Cache miss, go to the database
3848 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3850 if ( $text === false ) {
3851 $this->mTplDomCache
[$titleText] = false;
3852 return array( false, $title );
3855 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3856 $this->mTplDomCache
[$titleText] = $dom;
3858 if ( !$title->equals( $cacheTitle ) ) {
3859 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3860 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3863 return array( $dom, $title );
3867 * Fetch the current revision of a given title. Note that the revision
3868 * (and even the title) may not exist in the database, so everything
3869 * contributing to the output of the parser should use this method
3870 * where possible, rather than getting the revisions themselves. This
3871 * method also caches its results, so using it benefits performance.
3874 * @param Title $title
3877 public function fetchCurrentRevisionOfTitle( $title ) {
3878 $cacheKey = $title->getPrefixedDBkey();
3879 if ( !$this->currentRevisionCache
) {
3880 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3882 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3883 $this->currentRevisionCache
->set( $cacheKey,
3884 // Defaults to Parser::statelessFetchRevision()
3885 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3888 return $this->currentRevisionCache
->get( $cacheKey );
3892 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3893 * without passing them on to it.
3896 * @param Title $title
3897 * @param Parser|bool $parser
3900 public static function statelessFetchRevision( $title, $parser = false ) {
3901 return Revision
::newFromTitle( $title );
3905 * Fetch the unparsed text of a template and register a reference to it.
3906 * @param Title $title
3907 * @return array ( string or false, Title )
3909 public function fetchTemplateAndTitle( $title ) {
3910 // Defaults to Parser::statelessFetchTemplate()
3911 $templateCb = $this->mOptions
->getTemplateCallback();
3912 $stuff = call_user_func( $templateCb, $title, $this );
3913 // We use U+007F DELETE to distinguish strip markers from regular text.
3914 $text = $stuff['text'];
3915 if ( is_string( $stuff['text'] ) ) {
3916 $text = strtr( $text, "\x7f", "?" );
3918 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3919 if ( isset( $stuff['deps'] ) ) {
3920 foreach ( $stuff['deps'] as $dep ) {
3921 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3922 if ( $dep['title']->equals( $this->getTitle() ) ) {
3923 // If we transclude ourselves, the final result
3924 // will change based on the new version of the page
3925 $this->mOutput
->setFlag( 'vary-revision' );
3929 return array( $text, $finalTitle );
3933 * Fetch the unparsed text of a template and register a reference to it.
3934 * @param Title $title
3935 * @return string|bool
3937 public function fetchTemplate( $title ) {
3938 $rv = $this->fetchTemplateAndTitle( $title );
3943 * Static function to get a template
3944 * Can be overridden via ParserOptions::setTemplateCallback().
3946 * @param Title $title
3947 * @param bool|Parser $parser
3951 public static function statelessFetchTemplate( $title, $parser = false ) {
3952 $text = $skip = false;
3953 $finalTitle = $title;
3956 # Loop to fetch the article, with up to 1 redirect
3957 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3958 # Give extensions a chance to select the revision instead
3959 $id = false; # Assume current
3960 Hooks
::run( 'BeforeParserFetchTemplateAndtitle',
3961 array( $parser, $title, &$skip, &$id ) );
3967 'page_id' => $title->getArticleID(),
3974 $rev = Revision
::newFromId( $id );
3975 } elseif ( $parser ) {
3976 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3978 $rev = Revision
::newFromTitle( $title );
3980 $rev_id = $rev ?
$rev->getId() : 0;
3981 # If there is no current revision, there is no page
3982 if ( $id === false && !$rev ) {
3983 $linkCache = LinkCache
::singleton();
3984 $linkCache->addBadLinkObj( $title );
3989 'page_id' => $title->getArticleID(),
3990 'rev_id' => $rev_id );
3991 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3992 # We fetched a rev from a different title; register it too...
3994 'title' => $rev->getTitle(),
3995 'page_id' => $rev->getPage(),
3996 'rev_id' => $rev_id );
4000 $content = $rev->getContent();
4001 $text = $content ?
$content->getWikitextForTransclusion() : null;
4003 if ( $text === false ||
$text === null ) {
4007 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
4009 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
4010 if ( !$message->exists() ) {
4014 $content = $message->content();
4015 $text = $message->plain();
4023 $finalTitle = $title;
4024 $title = $content->getRedirectTarget();
4028 'finalTitle' => $finalTitle,
4033 * Fetch a file and its title and register a reference to it.
4034 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4035 * @param Title $title
4036 * @param array $options Array of options to RepoGroup::findFile
4039 public function fetchFile( $title, $options = array() ) {
4040 $res = $this->fetchFileAndTitle( $title, $options );
4045 * Fetch a file and its title and register a reference to it.
4046 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4047 * @param Title $title
4048 * @param array $options Array of options to RepoGroup::findFile
4049 * @return array ( File or false, Title of file )
4051 public function fetchFileAndTitle( $title, $options = array() ) {
4052 $file = $this->fetchFileNoRegister( $title, $options );
4054 $time = $file ?
$file->getTimestamp() : false;
4055 $sha1 = $file ?
$file->getSha1() : false;
4056 # Register the file as a dependency...
4057 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4058 if ( $file && !$title->equals( $file->getTitle() ) ) {
4059 # Update fetched file title
4060 $title = $file->getTitle();
4061 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4063 return array( $file, $title );
4067 * Helper function for fetchFileAndTitle.
4069 * Also useful if you need to fetch a file but not use it yet,
4070 * for example to get the file's handler.
4072 * @param Title $title
4073 * @param array $options Array of options to RepoGroup::findFile
4076 protected function fetchFileNoRegister( $title, $options = array() ) {
4077 if ( isset( $options['broken'] ) ) {
4078 $file = false; // broken thumbnail forced by hook
4079 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
4080 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
4081 } else { // get by (name,timestamp)
4082 $file = wfFindFile( $title, $options );
4088 * Transclude an interwiki link.
4090 * @param Title $title
4091 * @param string $action
4095 public function interwikiTransclude( $title, $action ) {
4096 global $wgEnableScaryTranscluding;
4098 if ( !$wgEnableScaryTranscluding ) {
4099 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
4102 $url = $title->getFullURL( array( 'action' => $action ) );
4104 if ( strlen( $url ) > 255 ) {
4105 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
4107 return $this->fetchScaryTemplateMaybeFromCache( $url );
4111 * @param string $url
4112 * @return mixed|string
4114 public function fetchScaryTemplateMaybeFromCache( $url ) {
4115 global $wgTranscludeCacheExpiry;
4116 $dbr = wfGetDB( DB_SLAVE
);
4117 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
4118 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
4119 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
4121 return $obj->tc_contents
;
4124 $req = MWHttpRequest
::factory( $url, array(), __METHOD__
);
4125 $status = $req->execute(); // Status object
4126 if ( $status->isOK() ) {
4127 $text = $req->getContent();
4128 } elseif ( $req->getStatus() != 200 ) {
4129 // Though we failed to fetch the content, this status is useless.
4130 return wfMessage( 'scarytranscludefailed-httpstatus' )
4131 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
4133 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
4136 $dbw = wfGetDB( DB_MASTER
);
4137 $dbw->replace( 'transcache', array( 'tc_url' ), array(
4139 'tc_time' => $dbw->timestamp( time() ),
4140 'tc_contents' => $text
4146 * Triple brace replacement -- used for template arguments
4149 * @param array $piece
4150 * @param PPFrame $frame
4154 public function argSubstitution( $piece, $frame ) {
4157 $parts = $piece['parts'];
4158 $nameWithSpaces = $frame->expand( $piece['title'] );
4159 $argName = trim( $nameWithSpaces );
4161 $text = $frame->getArgument( $argName );
4162 if ( $text === false && $parts->getLength() > 0
4163 && ( $this->ot
['html']
4165 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
4168 # No match in frame, use the supplied default
4169 $object = $parts->item( 0 )->getChildren();
4171 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
4172 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
4173 $this->limitationWarn( 'post-expand-template-argument' );
4176 if ( $text === false && $object === false ) {
4178 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
4180 if ( $error !== false ) {
4183 if ( $object !== false ) {
4184 $ret = array( 'object' => $object );
4186 $ret = array( 'text' => $text );
4193 * Return the text to be used for a given extension tag.
4194 * This is the ghost of strip().
4196 * @param array $params Associative array of parameters:
4197 * name PPNode for the tag name
4198 * attr PPNode for unparsed text where tag attributes are thought to be
4199 * attributes Optional associative array of parsed attributes
4200 * inner Contents of extension element
4201 * noClose Original text did not have a close tag
4202 * @param PPFrame $frame
4204 * @throws MWException
4207 public function extensionSubstitution( $params, $frame ) {
4208 $name = $frame->expand( $params['name'] );
4209 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
4210 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
4211 $marker = self
::MARKER_PREFIX
. "-$name-"
4212 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
4214 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
4215 ( $this->ot
['html'] ||
$this->ot
['pre'] );
4216 if ( $isFunctionTag ) {
4217 $markerType = 'none';
4219 $markerType = 'general';
4221 if ( $this->ot
['html'] ||
$isFunctionTag ) {
4222 $name = strtolower( $name );
4223 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
4224 if ( isset( $params['attributes'] ) ) {
4225 $attributes = $attributes +
$params['attributes'];
4228 if ( isset( $this->mTagHooks
[$name] ) ) {
4229 # Workaround for PHP bug 35229 and similar
4230 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
4231 throw new MWException( "Tag hook for $name is not callable\n" );
4233 $output = call_user_func_array( $this->mTagHooks
[$name],
4234 array( $content, $attributes, $this, $frame ) );
4235 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
4236 list( $callback, ) = $this->mFunctionTagHooks
[$name];
4237 if ( !is_callable( $callback ) ) {
4238 throw new MWException( "Tag hook for $name is not callable\n" );
4241 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
4243 $output = '<span class="error">Invalid tag extension name: ' .
4244 htmlspecialchars( $name ) . '</span>';
4247 if ( is_array( $output ) ) {
4248 # Extract flags to local scope (to override $markerType)
4250 $output = $flags[0];
4255 if ( is_null( $attrText ) ) {
4258 if ( isset( $params['attributes'] ) ) {
4259 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4260 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4261 htmlspecialchars( $attrValue ) . '"';
4264 if ( $content === null ) {
4265 $output = "<$name$attrText/>";
4267 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4268 $output = "<$name$attrText>$content$close";
4272 if ( $markerType === 'none' ) {
4274 } elseif ( $markerType === 'nowiki' ) {
4275 $this->mStripState
->addNoWiki( $marker, $output );
4276 } elseif ( $markerType === 'general' ) {
4277 $this->mStripState
->addGeneral( $marker, $output );
4279 throw new MWException( __METHOD__
. ': invalid marker type' );
4285 * Increment an include size counter
4287 * @param string $type The type of expansion
4288 * @param int $size The size of the text
4289 * @return bool False if this inclusion would take it over the maximum, true otherwise
4291 public function incrementIncludeSize( $type, $size ) {
4292 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4295 $this->mIncludeSizes
[$type] +
= $size;
4301 * Increment the expensive function count
4303 * @return bool False if the limit has been exceeded
4305 public function incrementExpensiveFunctionCount() {
4306 $this->mExpensiveFunctionCount++
;
4307 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4311 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4312 * Fills $this->mDoubleUnderscores, returns the modified text
4314 * @param string $text
4318 public function doDoubleUnderscore( $text ) {
4320 # The position of __TOC__ needs to be recorded
4321 $mw = MagicWord
::get( 'toc' );
4322 if ( $mw->match( $text ) ) {
4323 $this->mShowToc
= true;
4324 $this->mForceTocPosition
= true;
4326 # Set a placeholder. At the end we'll fill it in with the TOC.
4327 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4329 # Only keep the first one.
4330 $text = $mw->replace( '', $text );
4333 # Now match and remove the rest of them
4334 $mwa = MagicWord
::getDoubleUnderscoreArray();
4335 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4337 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4338 $this->mOutput
->mNoGallery
= true;
4340 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4341 $this->mShowToc
= false;
4343 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4344 && $this->mTitle
->getNamespace() == NS_CATEGORY
4346 $this->addTrackingCategory( 'hidden-category-category' );
4348 # (bug 8068) Allow control over whether robots index a page.
4350 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4351 # is not desirable, the last one on the page should win.
4352 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4353 $this->mOutput
->setIndexPolicy( 'noindex' );
4354 $this->addTrackingCategory( 'noindex-category' );
4356 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4357 $this->mOutput
->setIndexPolicy( 'index' );
4358 $this->addTrackingCategory( 'index-category' );
4361 # Cache all double underscores in the database
4362 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4363 $this->mOutput
->setProperty( $key, '' );
4370 * @see ParserOutput::addTrackingCategory()
4371 * @param string $msg Message key
4372 * @return bool Whether the addition was successful
4374 public function addTrackingCategory( $msg ) {
4375 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4379 * This function accomplishes several tasks:
4380 * 1) Auto-number headings if that option is enabled
4381 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4382 * 3) Add a Table of contents on the top for users who have enabled the option
4383 * 4) Auto-anchor headings
4385 * It loops through all headlines, collects the necessary data, then splits up the
4386 * string and re-inserts the newly formatted headlines.
4388 * @param string $text
4389 * @param string $origText Original, untouched wikitext
4390 * @param bool $isMain
4391 * @return mixed|string
4394 public function formatHeadings( $text, $origText, $isMain = true ) {
4395 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4397 # Inhibit editsection links if requested in the page
4398 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4399 $maybeShowEditLink = $showEditLink = false;
4401 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4402 $showEditLink = $this->mOptions
->getEditSection();
4404 if ( $showEditLink ) {
4405 $this->mOutput
->setEditSectionTokens( true );
4408 # Get all headlines for numbering them and adding funky stuff like [edit]
4409 # links - this is for later, but we need the number of headlines right now
4411 $numMatches = preg_match_all(
4412 '/<H(?P<level>[1-6])(?P<attrib>.*?>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i',
4417 # if there are fewer than 4 headlines in the article, do not show TOC
4418 # unless it's been explicitly enabled.
4419 $enoughToc = $this->mShowToc
&&
4420 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4422 # Allow user to stipulate that a page should have a "new section"
4423 # link added via __NEWSECTIONLINK__
4424 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4425 $this->mOutput
->setNewSection( true );
4428 # Allow user to remove the "new section"
4429 # link via __NONEWSECTIONLINK__
4430 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4431 $this->mOutput
->hideNewSection( true );
4434 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4435 # override above conditions and always show TOC above first header
4436 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4437 $this->mShowToc
= true;
4445 # Ugh .. the TOC should have neat indentation levels which can be
4446 # passed to the skin functions. These are determined here
4450 $sublevelCount = array();
4451 $levelCount = array();
4456 $markerRegex = self
::MARKER_PREFIX
. "-h-(\d+)-" . self
::MARKER_SUFFIX
;
4457 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4458 $oldType = $this->mOutputType
;
4459 $this->setOutputType( self
::OT_WIKI
);
4460 $frame = $this->getPreprocessor()->newFrame();
4461 $root = $this->preprocessToDom( $origText );
4462 $node = $root->getFirstChild();
4467 $headlines = $numMatches !== false ?
$matches[3] : array();
4469 foreach ( $headlines as $headline ) {
4470 $isTemplate = false;
4472 $sectionIndex = false;
4474 $markerMatches = array();
4475 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4476 $serial = $markerMatches[1];
4477 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4478 $isTemplate = ( $titleText != $baseTitleText );
4479 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4483 $prevlevel = $level;
4485 $level = $matches[1][$headlineCount];
4487 if ( $level > $prevlevel ) {
4488 # Increase TOC level
4490 $sublevelCount[$toclevel] = 0;
4491 if ( $toclevel < $wgMaxTocLevel ) {
4492 $prevtoclevel = $toclevel;
4493 $toc .= Linker
::tocIndent();
4496 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4497 # Decrease TOC level, find level to jump to
4499 for ( $i = $toclevel; $i > 0; $i-- ) {
4500 if ( $levelCount[$i] == $level ) {
4501 # Found last matching level
4504 } elseif ( $levelCount[$i] < $level ) {
4505 # Found first matching level below current level
4513 if ( $toclevel < $wgMaxTocLevel ) {
4514 if ( $prevtoclevel < $wgMaxTocLevel ) {
4515 # Unindent only if the previous toc level was shown :p
4516 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4517 $prevtoclevel = $toclevel;
4519 $toc .= Linker
::tocLineEnd();
4523 # No change in level, end TOC line
4524 if ( $toclevel < $wgMaxTocLevel ) {
4525 $toc .= Linker
::tocLineEnd();
4529 $levelCount[$toclevel] = $level;
4531 # count number of headlines for each level
4532 $sublevelCount[$toclevel]++
;
4534 for ( $i = 1; $i <= $toclevel; $i++
) {
4535 if ( !empty( $sublevelCount[$i] ) ) {
4539 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4544 # The safe header is a version of the header text safe to use for links
4546 # Remove link placeholders by the link text.
4547 # <!--LINK number-->
4549 # link text with suffix
4550 # Do this before unstrip since link text can contain strip markers
4551 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4553 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4554 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4556 # Strip out HTML (first regex removes any tag not allowed)
4558 # * <sup> and <sub> (bug 8393)
4561 # * <bdi> (bug 72884)
4562 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4564 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4565 # to allow setting directionality in toc items.
4566 $tocline = preg_replace(
4568 '#<(?!/?(span|sup|sub|bdi|i|b)(?: [^>]*)?>).*?>#',
4569 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b))(?: .*?)?>#'
4571 array( '', '<$1>' ),
4575 # Strip '<span></span>', which is the result from the above if
4576 # <span id="foo"></span> is used to produce an additional anchor
4578 $tocline = str_replace( '<span></span>', '', $tocline );
4580 $tocline = trim( $tocline );
4582 # For the anchor, strip out HTML-y stuff period
4583 $safeHeadline = preg_replace( '/<.*?>/', '', $safeHeadline );
4584 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4586 # Save headline for section edit hint before it's escaped
4587 $headlineHint = $safeHeadline;
4589 if ( $wgExperimentalHtmlIds ) {
4590 # For reverse compatibility, provide an id that's
4591 # HTML4-compatible, like we used to.
4593 # It may be worth noting, academically, that it's possible for
4594 # the legacy anchor to conflict with a non-legacy headline
4595 # anchor on the page. In this case likely the "correct" thing
4596 # would be to either drop the legacy anchors or make sure
4597 # they're numbered first. However, this would require people
4598 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4599 # manually, so let's not bother worrying about it.
4600 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4601 array( 'noninitial', 'legacy' ) );
4602 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4604 if ( $legacyHeadline == $safeHeadline ) {
4605 # No reason to have both (in fact, we can't)
4606 $legacyHeadline = false;
4609 $legacyHeadline = false;
4610 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4614 # HTML names must be case-insensitively unique (bug 10721).
4615 # This does not apply to Unicode characters per
4616 # http://www.w3.org/TR/html5/infrastructure.html#case-sensitivity-and-string-comparison
4617 # @todo FIXME: We may be changing them depending on the current locale.
4618 $arrayKey = strtolower( $safeHeadline );
4619 if ( $legacyHeadline === false ) {
4620 $legacyArrayKey = false;
4622 $legacyArrayKey = strtolower( $legacyHeadline );
4625 # Create the anchor for linking from the TOC to the section
4626 $anchor = $safeHeadline;
4627 $legacyAnchor = $legacyHeadline;
4628 if ( isset( $refers[$arrayKey] ) ) {
4629 for ( $i = 2; isset( $refers["${arrayKey}_$i"] ); ++
$i );
4631 $refers["${arrayKey}_$i"] = true;
4633 $refers[$arrayKey] = true;
4635 if ( $legacyHeadline !== false && isset( $refers[$legacyArrayKey] ) ) {
4636 for ( $i = 2; isset( $refers["${legacyArrayKey}_$i"] ); ++
$i );
4637 $legacyAnchor .= "_$i";
4638 $refers["${legacyArrayKey}_$i"] = true;
4640 $refers[$legacyArrayKey] = true;
4643 # Don't number the heading if it is the only one (looks silly)
4644 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4645 # the two are different if the line contains a link
4646 $headline = Html
::element(
4648 array( 'class' => 'mw-headline-number' ),
4650 ) . ' ' . $headline;
4653 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4654 $toc .= Linker
::tocLine( $anchor, $tocline,
4655 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4658 # Add the section to the section tree
4659 # Find the DOM node for this header
4660 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4661 while ( $node && !$noOffset ) {
4662 if ( $node->getName() === 'h' ) {
4663 $bits = $node->splitHeading();
4664 if ( $bits['i'] == $sectionIndex ) {
4668 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4669 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4670 $node = $node->getNextSibling();
4673 'toclevel' => $toclevel,
4676 'number' => $numbering,
4677 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4678 'fromtitle' => $titleText,
4679 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4680 'anchor' => $anchor,
4683 # give headline the correct <h#> tag
4684 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4685 // Output edit section links as markers with styles that can be customized by skins
4686 if ( $isTemplate ) {
4687 # Put a T flag in the section identifier, to indicate to extractSections()
4688 # that sections inside <includeonly> should be counted.
4689 $editsectionPage = $titleText;
4690 $editsectionSection = "T-$sectionIndex";
4691 $editsectionContent = null;
4693 $editsectionPage = $this->mTitle
->getPrefixedText();
4694 $editsectionSection = $sectionIndex;
4695 $editsectionContent = $headlineHint;
4697 // We use a bit of pesudo-xml for editsection markers. The
4698 // language converter is run later on. Using a UNIQ style marker
4699 // leads to the converter screwing up the tokens when it
4700 // converts stuff. And trying to insert strip tags fails too. At
4701 // this point all real inputted tags have already been escaped,
4702 // so we don't have to worry about a user trying to input one of
4703 // these markers directly. We use a page and section attribute
4704 // to stop the language converter from converting these
4705 // important bits of data, but put the headline hint inside a
4706 // content block because the language converter is supposed to
4707 // be able to convert that piece of data.
4708 // Gets replaced with html in ParserOutput::getText
4709 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4710 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4711 if ( $editsectionContent !== null ) {
4712 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4719 $head[$headlineCount] = Linker
::makeHeadline( $level,
4720 $matches['attrib'][$headlineCount], $anchor, $headline,
4721 $editlink, $legacyAnchor );
4726 $this->setOutputType( $oldType );
4728 # Never ever show TOC if no headers
4729 if ( $numVisible < 1 ) {
4734 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4735 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4737 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4738 $this->mOutput
->setTOCHTML( $toc );
4739 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4740 $this->mOutput
->addModules( 'mediawiki.toc' );
4744 $this->mOutput
->setSections( $tocraw );
4747 # split up and insert constructed headlines
4748 $blocks = preg_split( '/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4751 // build an array of document sections
4752 $sections = array();
4753 foreach ( $blocks as $block ) {
4754 // $head is zero-based, sections aren't.
4755 if ( empty( $head[$i - 1] ) ) {
4756 $sections[$i] = $block;
4758 $sections[$i] = $head[$i - 1] . $block;
4762 * Send a hook, one per section.
4763 * The idea here is to be able to make section-level DIVs, but to do so in a
4764 * lower-impact, more correct way than r50769
4767 * $section : the section number
4768 * &$sectionContent : ref to the content of the section
4769 * $showEditLinks : boolean describing whether this section has an edit link
4771 Hooks
::run( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4776 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4777 // append the TOC at the beginning
4778 // Top anchor now in skin
4779 $sections[0] = $sections[0] . $toc . "\n";
4782 $full .= join( '', $sections );
4784 if ( $this->mForceTocPosition
) {
4785 return str_replace( '<!--MWTOC-->', $toc, $full );
4792 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4793 * conversion, substituting signatures, {{subst:}} templates, etc.
4795 * @param string $text The text to transform
4796 * @param Title $title The Title object for the current article
4797 * @param User $user The User object describing the current user
4798 * @param ParserOptions $options Parsing options
4799 * @param bool $clearState Whether to clear the parser state first
4800 * @return string The altered wiki markup
4802 public function preSaveTransform( $text, Title
$title, User
$user,
4803 ParserOptions
$options, $clearState = true
4805 if ( $clearState ) {
4806 $magicScopeVariable = $this->lock();
4808 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4809 $this->setUser( $user );
4815 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4816 if ( $options->getPreSaveTransform() ) {
4817 $text = $this->pstPass2( $text, $user );
4819 $text = $this->mStripState
->unstripBoth( $text );
4821 $this->setUser( null ); #Reset
4827 * Pre-save transform helper function
4829 * @param string $text
4834 private function pstPass2( $text, $user ) {
4837 # Note: This is the timestamp saved as hardcoded wikitext to
4838 # the database, we use $wgContLang here in order to give
4839 # everyone the same signature and use the default one rather
4840 # than the one selected in each user's preferences.
4841 # (see also bug 12815)
4842 $ts = $this->mOptions
->getTimestamp();
4843 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4844 $ts = $timestamp->format( 'YmdHis' );
4845 $tzMsg = $timestamp->format( 'T' ); # might vary on DST changeover!
4847 # Allow translation of timezones through wiki. format() can return
4848 # whatever crap the system uses, localised or not, so we cannot
4849 # ship premade translations.
4850 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4851 $msg = wfMessage( $key )->inContentLanguage();
4852 if ( $msg->exists() ) {
4853 $tzMsg = $msg->text();
4856 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4858 # Variable replacement
4859 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4860 $text = $this->replaceVariables( $text );
4862 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4863 # which may corrupt this parser instance via its wfMessage()->text() call-
4866 $sigText = $this->getUserSig( $user );
4867 $text = strtr( $text, array(
4869 '~~~~' => "$sigText $d",
4873 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4874 $tc = '[' . Title
::legalChars() . ']';
4875 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4877 // [[ns:page (context)|]]
4878 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4879 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4880 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4881 // [[ns:page (context), context|]] (using either single or double-width comma)
4882 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4883 // [[|page]] (reverse pipe trick: add context from page title)
4884 $p2 = "/\[\[\\|($tc+)]]/";
4886 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4887 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4888 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4889 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4891 $t = $this->mTitle
->getText();
4893 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4894 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4895 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4896 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4898 # if there's no context, don't bother duplicating the title
4899 $text = preg_replace( $p2, '[[\\1]]', $text );
4902 # Trim trailing whitespace
4903 $text = rtrim( $text );
4909 * Fetch the user's signature text, if any, and normalize to
4910 * validated, ready-to-insert wikitext.
4911 * If you have pre-fetched the nickname or the fancySig option, you can
4912 * specify them here to save a database query.
4913 * Do not reuse this parser instance after calling getUserSig(),
4914 * as it may have changed if it's the $wgParser.
4917 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4918 * @param bool|null $fancySig whether the nicknname is the complete signature
4919 * or null to use default value
4922 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4923 global $wgMaxSigChars;
4925 $username = $user->getName();
4927 # If not given, retrieve from the user object.
4928 if ( $nickname === false ) {
4929 $nickname = $user->getOption( 'nickname' );
4932 if ( is_null( $fancySig ) ) {
4933 $fancySig = $user->getBoolOption( 'fancysig' );
4936 $nickname = $nickname == null ?
$username : $nickname;
4938 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4939 $nickname = $username;
4940 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4941 } elseif ( $fancySig !== false ) {
4942 # Sig. might contain markup; validate this
4943 if ( $this->validateSig( $nickname ) !== false ) {
4944 # Validated; clean up (if needed) and return it
4945 return $this->cleanSig( $nickname, true );
4947 # Failed to validate; fall back to the default
4948 $nickname = $username;
4949 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4953 # Make sure nickname doesnt get a sig in a sig
4954 $nickname = self
::cleanSigInSig( $nickname );
4956 # If we're still here, make it a link to the user page
4957 $userText = wfEscapeWikiText( $username );
4958 $nickText = wfEscapeWikiText( $nickname );
4959 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4961 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4962 ->title( $this->getTitle() )->text();
4966 * Check that the user's signature contains no bad XML
4968 * @param string $text
4969 * @return string|bool An expanded string, or false if invalid.
4971 public function validateSig( $text ) {
4972 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4976 * Clean up signature text
4978 * 1) Strip 3, 4 or 5 tildes out of signatures @see cleanSigInSig
4979 * 2) Substitute all transclusions
4981 * @param string $text
4982 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4983 * @return string Signature text
4985 public function cleanSig( $text, $parsing = false ) {
4988 $magicScopeVariable = $this->lock();
4989 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4992 # Option to disable this feature
4993 if ( !$this->mOptions
->getCleanSignatures() ) {
4997 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4998 # => Move this logic to braceSubstitution()
4999 $substWord = MagicWord
::get( 'subst' );
5000 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
5001 $substText = '{{' . $substWord->getSynonym( 0 );
5003 $text = preg_replace( $substRegex, $substText, $text );
5004 $text = self
::cleanSigInSig( $text );
5005 $dom = $this->preprocessToDom( $text );
5006 $frame = $this->getPreprocessor()->newFrame();
5007 $text = $frame->expand( $dom );
5010 $text = $this->mStripState
->unstripBoth( $text );
5017 * Strip 3, 4 or 5 tildes out of signatures.
5019 * @param string $text
5020 * @return string Signature text with /~{3,5}/ removed
5022 public static function cleanSigInSig( $text ) {
5023 $text = preg_replace( '/~{3,5}/', '', $text );
5028 * Set up some variables which are usually set up in parse()
5029 * so that an external function can call some class members with confidence
5031 * @param Title|null $title
5032 * @param ParserOptions $options
5033 * @param int $outputType
5034 * @param bool $clearState
5036 public function startExternalParse( Title
$title = null, ParserOptions
$options,
5037 $outputType, $clearState = true
5039 $this->startParse( $title, $options, $outputType, $clearState );
5043 * @param Title|null $title
5044 * @param ParserOptions $options
5045 * @param int $outputType
5046 * @param bool $clearState
5048 private function startParse( Title
$title = null, ParserOptions
$options,
5049 $outputType, $clearState = true
5051 $this->setTitle( $title );
5052 $this->mOptions
= $options;
5053 $this->setOutputType( $outputType );
5054 if ( $clearState ) {
5055 $this->clearState();
5060 * Wrapper for preprocess()
5062 * @param string $text The text to preprocess
5063 * @param ParserOptions $options Options
5064 * @param Title|null $title Title object or null to use $wgTitle
5067 public function transformMsg( $text, $options, $title = null ) {
5068 static $executing = false;
5070 # Guard against infinite recursion
5081 $text = $this->preprocess( $text, $title, $options );
5088 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
5089 * The callback should have the following form:
5090 * function myParserHook( $text, $params, $parser, $frame ) { ... }
5092 * Transform and return $text. Use $parser for any required context, e.g. use
5093 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
5095 * Hooks may return extended information by returning an array, of which the
5096 * first numbered element (index 0) must be the return string, and all other
5097 * entries are extracted into local variables within an internal function
5098 * in the Parser class.
5100 * This interface (introduced r61913) appears to be undocumented, but
5101 * 'markerType' is used by some core tag hooks to override which strip
5102 * array their results are placed in. **Use great caution if attempting
5103 * this interface, as it is not documented and injudicious use could smash
5104 * private variables.**
5106 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5107 * @param callable $callback The callback function (and object) to use for the tag
5108 * @throws MWException
5109 * @return callable|null The old value of the mTagHooks array associated with the hook
5111 public function setHook( $tag, $callback ) {
5112 $tag = strtolower( $tag );
5113 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5114 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
5116 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
5117 $this->mTagHooks
[$tag] = $callback;
5118 if ( !in_array( $tag, $this->mStripList
) ) {
5119 $this->mStripList
[] = $tag;
5126 * As setHook(), but letting the contents be parsed.
5128 * Transparent tag hooks are like regular XML-style tag hooks, except they
5129 * operate late in the transformation sequence, on HTML instead of wikitext.
5131 * This is probably obsoleted by things dealing with parser frames?
5132 * The only extension currently using it is geoserver.
5135 * @todo better document or deprecate this
5137 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5138 * @param callable $callback The callback function (and object) to use for the tag
5139 * @throws MWException
5140 * @return callable|null The old value of the mTagHooks array associated with the hook
5142 public function setTransparentTagHook( $tag, $callback ) {
5143 $tag = strtolower( $tag );
5144 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5145 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
5147 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
5148 $this->mTransparentTagHooks
[$tag] = $callback;
5154 * Remove all tag hooks
5156 public function clearTagHooks() {
5157 $this->mTagHooks
= array();
5158 $this->mFunctionTagHooks
= array();
5159 $this->mStripList
= $this->mDefaultStripList
;
5163 * Create a function, e.g. {{sum:1|2|3}}
5164 * The callback function should have the form:
5165 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
5167 * Or with Parser::SFH_OBJECT_ARGS:
5168 * function myParserFunction( $parser, $frame, $args ) { ... }
5170 * The callback may either return the text result of the function, or an array with the text
5171 * in element 0, and a number of flags in the other elements. The names of the flags are
5172 * specified in the keys. Valid flags are:
5173 * found The text returned is valid, stop processing the template. This
5175 * nowiki Wiki markup in the return value should be escaped
5176 * isHTML The returned text is HTML, armour it against wikitext transformation
5178 * @param string $id The magic word ID
5179 * @param callable $callback The callback function (and object) to use
5180 * @param int $flags A combination of the following flags:
5181 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
5183 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
5184 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
5185 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
5186 * the arguments, and to control the way they are expanded.
5188 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
5189 * arguments, for instance:
5190 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
5192 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
5193 * future versions. Please call $frame->expand() on it anyway so that your code keeps
5194 * working if/when this is changed.
5196 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
5199 * Please read the documentation in includes/parser/Preprocessor.php for more information
5200 * about the methods available in PPFrame and PPNode.
5202 * @throws MWException
5203 * @return string|callable The old callback function for this name, if any
5205 public function setFunctionHook( $id, $callback, $flags = 0 ) {
5208 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
5209 $this->mFunctionHooks
[$id] = array( $callback, $flags );
5211 # Add to function cache
5212 $mw = MagicWord
::get( $id );
5214 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
5217 $synonyms = $mw->getSynonyms();
5218 $sensitive = intval( $mw->isCaseSensitive() );
5220 foreach ( $synonyms as $syn ) {
5222 if ( !$sensitive ) {
5223 $syn = $wgContLang->lc( $syn );
5226 if ( !( $flags & self
::SFH_NO_HASH
) ) {
5229 # Remove trailing colon
5230 if ( substr( $syn, -1, 1 ) === ':' ) {
5231 $syn = substr( $syn, 0, -1 );
5233 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
5239 * Get all registered function hook identifiers
5243 public function getFunctionHooks() {
5244 return array_keys( $this->mFunctionHooks
);
5248 * Create a tag function, e.g. "<test>some stuff</test>".
5249 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5250 * Unlike parser functions, their content is not preprocessed.
5251 * @param string $tag
5252 * @param callable $callback
5254 * @throws MWException
5257 public function setFunctionTagHook( $tag, $callback, $flags ) {
5258 $tag = strtolower( $tag );
5259 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5260 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5262 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
5263 $this->mFunctionTagHooks
[$tag] : null;
5264 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
5266 if ( !in_array( $tag, $this->mStripList
) ) {
5267 $this->mStripList
[] = $tag;
5274 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
5275 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5276 * Placeholders created in Skin::makeLinkObj()
5278 * @param string $text
5279 * @param int $options
5281 public function replaceLinkHolders( &$text, $options = 0 ) {
5282 $this->mLinkHolders
->replace( $text );
5286 * Replace "<!--LINK-->" link placeholders with plain text of links
5287 * (not HTML-formatted).
5289 * @param string $text
5292 public function replaceLinkHoldersText( $text ) {
5293 return $this->mLinkHolders
->replaceText( $text );
5297 * Renders an image gallery from a text with one line per image.
5298 * text labels may be given by using |-style alternative text. E.g.
5299 * Image:one.jpg|The number "1"
5300 * Image:tree.jpg|A tree
5301 * given as text will return the HTML of a gallery with two images,
5302 * labeled 'The number "1"' and
5305 * @param string $text
5306 * @param array $params
5307 * @return string HTML
5309 public function renderImageGallery( $text, $params ) {
5312 if ( isset( $params['mode'] ) ) {
5313 $mode = $params['mode'];
5317 $ig = ImageGalleryBase
::factory( $mode );
5318 } catch ( Exception
$e ) {
5319 // If invalid type set, fallback to default.
5320 $ig = ImageGalleryBase
::factory( false );
5323 $ig->setContextTitle( $this->mTitle
);
5324 $ig->setShowBytes( false );
5325 $ig->setShowFilename( false );
5326 $ig->setParser( $this );
5327 $ig->setHideBadImages();
5328 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
5330 if ( isset( $params['showfilename'] ) ) {
5331 $ig->setShowFilename( true );
5333 $ig->setShowFilename( false );
5335 if ( isset( $params['caption'] ) ) {
5336 $caption = $params['caption'];
5337 $caption = htmlspecialchars( $caption );
5338 $caption = $this->replaceInternalLinks( $caption );
5339 $ig->setCaptionHtml( $caption );
5341 if ( isset( $params['perrow'] ) ) {
5342 $ig->setPerRow( $params['perrow'] );
5344 if ( isset( $params['widths'] ) ) {
5345 $ig->setWidths( $params['widths'] );
5347 if ( isset( $params['heights'] ) ) {
5348 $ig->setHeights( $params['heights'] );
5350 $ig->setAdditionalOptions( $params );
5352 Hooks
::run( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5354 $lines = StringUtils
::explode( "\n", $text );
5355 foreach ( $lines as $line ) {
5356 # match lines like these:
5357 # Image:someimage.jpg|This is some image
5359 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5361 if ( count( $matches ) == 0 ) {
5365 if ( strpos( $matches[0], '%' ) !== false ) {
5366 $matches[1] = rawurldecode( $matches[1] );
5368 $title = Title
::newFromText( $matches[1], NS_FILE
);
5369 if ( is_null( $title ) ) {
5370 # Bogus title. Ignore these so we don't bomb out later.
5374 # We need to get what handler the file uses, to figure out parameters.
5375 # Note, a hook can overide the file name, and chose an entirely different
5376 # file (which potentially could be of a different type and have different handler).
5379 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5380 array( $this, $title, &$options, &$descQuery ) );
5381 # Don't register it now, as ImageGallery does that later.
5382 $file = $this->fetchFileNoRegister( $title, $options );
5383 $handler = $file ?
$file->getHandler() : false;
5386 'img_alt' => 'gallery-internal-alt',
5387 'img_link' => 'gallery-internal-link',
5390 $paramMap = $paramMap +
$handler->getParamMap();
5391 // We don't want people to specify per-image widths.
5392 // Additionally the width parameter would need special casing anyhow.
5393 unset( $paramMap['img_width'] );
5396 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5401 $handlerOptions = array();
5402 if ( isset( $matches[3] ) ) {
5403 // look for an |alt= definition while trying not to break existing
5404 // captions with multiple pipes (|) in it, until a more sensible grammar
5405 // is defined for images in galleries
5407 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5408 // splitting on '|' is a bit odd, and different from makeImage.
5409 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5410 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
5412 foreach ( $parameterMatches as $parameterMatch ) {
5413 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5415 $paramName = $paramMap[$magicName];
5417 switch ( $paramName ) {
5418 case 'gallery-internal-alt':
5419 $alt = $this->stripAltText( $match, false );
5421 case 'gallery-internal-link':
5422 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5423 $chars = self
::EXT_LINK_URL_CLASS
;
5424 $addr = self
::EXT_LINK_ADDR
;
5425 $prots = $this->mUrlProtocols
;
5426 //check to see if link matches an absolute url, if not then it must be a wiki link.
5427 if ( preg_match( "/^($prots)$addr$chars*$/u", $linkValue ) ) {
5430 $localLinkTitle = Title
::newFromText( $linkValue );
5431 if ( $localLinkTitle !== null ) {
5432 $link = $localLinkTitle->getLinkURL();
5437 // Must be a handler specific parameter.
5438 if ( $handler->validateParam( $paramName, $match ) ) {
5439 $handlerOptions[$paramName] = $match;
5441 // Guess not. Append it to the caption.
5442 wfDebug( "$parameterMatch failed parameter validation\n" );
5443 $label .= '|' . $parameterMatch;
5448 // concatenate all other pipes
5449 $label .= '|' . $parameterMatch;
5452 // remove the first pipe
5453 $label = substr( $label, 1 );
5456 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5458 $html = $ig->toHTML();
5459 Hooks
::run( 'AfterParserFetchFileAndTitle', array( $this, $ig, &$html ) );
5464 * @param MediaHandler $handler
5467 public function getImageParams( $handler ) {
5469 $handlerClass = get_class( $handler );
5473 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5474 # Initialise static lists
5475 static $internalParamNames = array(
5476 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5477 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5478 'bottom', 'text-bottom' ),
5479 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5480 'upright', 'border', 'link', 'alt', 'class' ),
5482 static $internalParamMap;
5483 if ( !$internalParamMap ) {
5484 $internalParamMap = array();
5485 foreach ( $internalParamNames as $type => $names ) {
5486 foreach ( $names as $name ) {
5487 $magicName = str_replace( '-', '_', "img_$name" );
5488 $internalParamMap[$magicName] = array( $type, $name );
5493 # Add handler params
5494 $paramMap = $internalParamMap;
5496 $handlerParamMap = $handler->getParamMap();
5497 foreach ( $handlerParamMap as $magic => $paramName ) {
5498 $paramMap[$magic] = array( 'handler', $paramName );
5501 $this->mImageParams
[$handlerClass] = $paramMap;
5502 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5504 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5508 * Parse image options text and use it to make an image
5510 * @param Title $title
5511 * @param string $options
5512 * @param LinkHolderArray|bool $holders
5513 * @return string HTML
5515 public function makeImage( $title, $options, $holders = false ) {
5516 # Check if the options text is of the form "options|alt text"
5518 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5519 # * left no resizing, just left align. label is used for alt= only
5520 # * right same, but right aligned
5521 # * none same, but not aligned
5522 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5523 # * center center the image
5524 # * frame Keep original image size, no magnify-button.
5525 # * framed Same as "frame"
5526 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5527 # * upright reduce width for upright images, rounded to full __0 px
5528 # * border draw a 1px border around the image
5529 # * alt Text for HTML alt attribute (defaults to empty)
5530 # * class Set a class for img node
5531 # * link Set the target of the image link. Can be external, interwiki, or local
5532 # vertical-align values (no % or length right now):
5542 $parts = StringUtils
::explode( "|", $options );
5544 # Give extensions a chance to select the file revision for us
5547 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5548 array( $this, $title, &$options, &$descQuery ) );
5549 # Fetch and register the file (file title may be different via hooks)
5550 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5553 $handler = $file ?
$file->getHandler() : false;
5555 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5558 $this->addTrackingCategory( 'broken-file-category' );
5561 # Process the input parameters
5563 $params = array( 'frame' => array(), 'handler' => array(),
5564 'horizAlign' => array(), 'vertAlign' => array() );
5565 $seenformat = false;
5566 foreach ( $parts as $part ) {
5567 $part = trim( $part );
5568 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5570 if ( isset( $paramMap[$magicName] ) ) {
5571 list( $type, $paramName ) = $paramMap[$magicName];
5573 # Special case; width and height come in one variable together
5574 if ( $type === 'handler' && $paramName === 'width' ) {
5575 $parsedWidthParam = $this->parseWidthParam( $value );
5576 if ( isset( $parsedWidthParam['width'] ) ) {
5577 $width = $parsedWidthParam['width'];
5578 if ( $handler->validateParam( 'width', $width ) ) {
5579 $params[$type]['width'] = $width;
5583 if ( isset( $parsedWidthParam['height'] ) ) {
5584 $height = $parsedWidthParam['height'];
5585 if ( $handler->validateParam( 'height', $height ) ) {
5586 $params[$type]['height'] = $height;
5590 # else no validation -- bug 13436
5592 if ( $type === 'handler' ) {
5593 # Validate handler parameter
5594 $validated = $handler->validateParam( $paramName, $value );
5596 # Validate internal parameters
5597 switch ( $paramName ) {
5601 # @todo FIXME: Possibly check validity here for
5602 # manualthumb? downstream behavior seems odd with
5603 # missing manual thumbs.
5605 $value = $this->stripAltText( $value, $holders );
5608 $chars = self
::EXT_LINK_URL_CLASS
;
5609 $addr = self
::EXT_LINK_ADDR
;
5610 $prots = $this->mUrlProtocols
;
5611 if ( $value === '' ) {
5612 $paramName = 'no-link';
5615 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5616 if ( preg_match( "/^((?i)$prots)$addr$chars*$/u", $value, $m ) ) {
5617 $paramName = 'link-url';
5618 $this->mOutput
->addExternalLink( $value );
5619 if ( $this->mOptions
->getExternalLinkTarget() ) {
5620 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5625 $linkTitle = Title
::newFromText( $value );
5627 $paramName = 'link-title';
5628 $value = $linkTitle;
5629 $this->mOutput
->addLink( $linkTitle );
5637 // use first appearing option, discard others.
5638 $validated = ! $seenformat;
5642 # Most other things appear to be empty or numeric...
5643 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5648 $params[$type][$paramName] = $value;
5652 if ( !$validated ) {
5657 # Process alignment parameters
5658 if ( $params['horizAlign'] ) {
5659 $params['frame']['align'] = key( $params['horizAlign'] );
5661 if ( $params['vertAlign'] ) {
5662 $params['frame']['valign'] = key( $params['vertAlign'] );
5665 $params['frame']['caption'] = $caption;
5667 # Will the image be presented in a frame, with the caption below?
5668 $imageIsFramed = isset( $params['frame']['frame'] )
5669 ||
isset( $params['frame']['framed'] )
5670 ||
isset( $params['frame']['thumbnail'] )
5671 ||
isset( $params['frame']['manualthumb'] );
5673 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5674 # came to also set the caption, ordinary text after the image -- which
5675 # makes no sense, because that just repeats the text multiple times in
5676 # screen readers. It *also* came to set the title attribute.
5678 # Now that we have an alt attribute, we should not set the alt text to
5679 # equal the caption: that's worse than useless, it just repeats the
5680 # text. This is the framed/thumbnail case. If there's no caption, we
5681 # use the unnamed parameter for alt text as well, just for the time be-
5682 # ing, if the unnamed param is set and the alt param is not.
5684 # For the future, we need to figure out if we want to tweak this more,
5685 # e.g., introducing a title= parameter for the title; ignoring the un-
5686 # named parameter entirely for images without a caption; adding an ex-
5687 # plicit caption= parameter and preserving the old magic unnamed para-
5689 if ( $imageIsFramed ) { # Framed image
5690 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5691 # No caption or alt text, add the filename as the alt text so
5692 # that screen readers at least get some description of the image
5693 $params['frame']['alt'] = $title->getText();
5695 # Do not set $params['frame']['title'] because tooltips don't make sense
5697 } else { # Inline image
5698 if ( !isset( $params['frame']['alt'] ) ) {
5699 # No alt text, use the "caption" for the alt text
5700 if ( $caption !== '' ) {
5701 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5703 # No caption, fall back to using the filename for the
5705 $params['frame']['alt'] = $title->getText();
5708 # Use the "caption" for the tooltip text
5709 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5712 Hooks
::run( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5714 # Linker does the rest
5715 $time = isset( $options['time'] ) ?
$options['time'] : false;
5716 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5717 $time, $descQuery, $this->mOptions
->getThumbSize() );
5719 # Give the handler a chance to modify the parser object
5721 $handler->parserTransformHook( $this, $file );
5728 * @param string $caption
5729 * @param LinkHolderArray|bool $holders
5730 * @return mixed|string
5732 protected function stripAltText( $caption, $holders ) {
5733 # Strip bad stuff out of the title (tooltip). We can't just use
5734 # replaceLinkHoldersText() here, because if this function is called
5735 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5737 $tooltip = $holders->replaceText( $caption );
5739 $tooltip = $this->replaceLinkHoldersText( $caption );
5742 # make sure there are no placeholders in thumbnail attributes
5743 # that are later expanded to html- so expand them now and
5745 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5746 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5752 * Set a flag in the output object indicating that the content is dynamic and
5753 * shouldn't be cached.
5755 public function disableCache() {
5756 wfDebug( "Parser output marked as uncacheable.\n" );
5757 if ( !$this->mOutput
) {
5758 throw new MWException( __METHOD__
.
5759 " can only be called when actually parsing something" );
5761 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5762 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5766 * Callback from the Sanitizer for expanding items found in HTML attribute
5767 * values, so they can be safely tested and escaped.
5769 * @param string $text
5770 * @param bool|PPFrame $frame
5773 public function attributeStripCallback( &$text, $frame = false ) {
5774 $text = $this->replaceVariables( $text, $frame );
5775 $text = $this->mStripState
->unstripBoth( $text );
5784 public function getTags() {
5786 array_keys( $this->mTransparentTagHooks
),
5787 array_keys( $this->mTagHooks
),
5788 array_keys( $this->mFunctionTagHooks
)
5793 * Replace transparent tags in $text with the values given by the callbacks.
5795 * Transparent tag hooks are like regular XML-style tag hooks, except they
5796 * operate late in the transformation sequence, on HTML instead of wikitext.
5798 * @param string $text
5802 public function replaceTransparentTags( $text ) {
5804 $elements = array_keys( $this->mTransparentTagHooks
);
5805 $text = self
::extractTagsAndParams( $elements, $text, $matches );
5806 $replacements = array();
5808 foreach ( $matches as $marker => $data ) {
5809 list( $element, $content, $params, $tag ) = $data;
5810 $tagName = strtolower( $element );
5811 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5812 $output = call_user_func_array(
5813 $this->mTransparentTagHooks
[$tagName],
5814 array( $content, $params, $this )
5819 $replacements[$marker] = $output;
5821 return strtr( $text, $replacements );
5825 * Break wikitext input into sections, and either pull or replace
5826 * some particular section's text.
5828 * External callers should use the getSection and replaceSection methods.
5830 * @param string $text Page wikitext
5831 * @param string|number $sectionId A section identifier string of the form:
5832 * "<flag1> - <flag2> - ... - <section number>"
5834 * Currently the only recognised flag is "T", which means the target section number
5835 * was derived during a template inclusion parse, in other words this is a template
5836 * section edit link. If no flags are given, it was an ordinary section edit link.
5837 * This flag is required to avoid a section numbering mismatch when a section is
5838 * enclosed by "<includeonly>" (bug 6563).
5840 * The section number 0 pulls the text before the first heading; other numbers will
5841 * pull the given section along with its lower-level subsections. If the section is
5842 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5844 * Section 0 is always considered to exist, even if it only contains the empty
5845 * string. If $text is the empty string and section 0 is replaced, $newText is
5848 * @param string $mode One of "get" or "replace"
5849 * @param string $newText Replacement text for section data.
5850 * @return string For "get", the extracted section text.
5851 * for "replace", the whole page with the section replaced.
5853 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5854 global $wgTitle; # not generally used but removes an ugly failure mode
5856 $magicScopeVariable = $this->lock();
5857 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5859 $frame = $this->getPreprocessor()->newFrame();
5861 # Process section extraction flags
5863 $sectionParts = explode( '-', $sectionId );
5864 $sectionIndex = array_pop( $sectionParts );
5865 foreach ( $sectionParts as $part ) {
5866 if ( $part === 'T' ) {
5867 $flags |
= self
::PTD_FOR_INCLUSION
;
5871 # Check for empty input
5872 if ( strval( $text ) === '' ) {
5873 # Only sections 0 and T-0 exist in an empty document
5874 if ( $sectionIndex == 0 ) {
5875 if ( $mode === 'get' ) {
5881 if ( $mode === 'get' ) {
5889 # Preprocess the text
5890 $root = $this->preprocessToDom( $text, $flags );
5892 # <h> nodes indicate section breaks
5893 # They can only occur at the top level, so we can find them by iterating the root's children
5894 $node = $root->getFirstChild();
5896 # Find the target section
5897 if ( $sectionIndex == 0 ) {
5898 # Section zero doesn't nest, level=big
5899 $targetLevel = 1000;
5902 if ( $node->getName() === 'h' ) {
5903 $bits = $node->splitHeading();
5904 if ( $bits['i'] == $sectionIndex ) {
5905 $targetLevel = $bits['level'];
5909 if ( $mode === 'replace' ) {
5910 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5912 $node = $node->getNextSibling();
5918 if ( $mode === 'get' ) {
5925 # Find the end of the section, including nested sections
5927 if ( $node->getName() === 'h' ) {
5928 $bits = $node->splitHeading();
5929 $curLevel = $bits['level'];
5930 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5934 if ( $mode === 'get' ) {
5935 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5937 $node = $node->getNextSibling();
5940 # Write out the remainder (in replace mode only)
5941 if ( $mode === 'replace' ) {
5942 # Output the replacement text
5943 # Add two newlines on -- trailing whitespace in $newText is conventionally
5944 # stripped by the editor, so we need both newlines to restore the paragraph gap
5945 # Only add trailing whitespace if there is newText
5946 if ( $newText != "" ) {
5947 $outText .= $newText . "\n\n";
5951 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5952 $node = $node->getNextSibling();
5956 if ( is_string( $outText ) ) {
5957 # Re-insert stripped tags
5958 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5965 * This function returns the text of a section, specified by a number ($section).
5966 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5967 * the first section before any such heading (section 0).
5969 * If a section contains subsections, these are also returned.
5971 * @param string $text Text to look in
5972 * @param string|number $sectionId Section identifier as a number or string
5973 * (e.g. 0, 1 or 'T-1').
5974 * @param string $defaultText Default to return if section is not found
5976 * @return string Text of the requested section
5978 public function getSection( $text, $sectionId, $defaultText = '' ) {
5979 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5983 * This function returns $oldtext after the content of the section
5984 * specified by $section has been replaced with $text. If the target
5985 * section does not exist, $oldtext is returned unchanged.
5987 * @param string $oldText Former text of the article
5988 * @param string|number $sectionId Section identifier as a number or string
5989 * (e.g. 0, 1 or 'T-1').
5990 * @param string $newText Replacing text
5992 * @return string Modified text
5994 public function replaceSection( $oldText, $sectionId, $newText ) {
5995 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5999 * Get the ID of the revision we are parsing
6003 public function getRevisionId() {
6004 return $this->mRevisionId
;
6008 * Get the revision object for $this->mRevisionId
6010 * @return Revision|null Either a Revision object or null
6011 * @since 1.23 (public since 1.23)
6013 public function getRevisionObject() {
6014 if ( !is_null( $this->mRevisionObject
) ) {
6015 return $this->mRevisionObject
;
6017 if ( is_null( $this->mRevisionId
) ) {
6021 $rev = call_user_func(
6022 $this->mOptions
->getCurrentRevisionCallback(), $this->getTitle(), $this
6025 # If the parse is for a new revision, then the callback should have
6026 # already been set to force the object and should match mRevisionId.
6027 # If not, try to fetch by mRevisionId for sanity.
6028 if ( $rev && $rev->getId() != $this->mRevisionId
) {
6029 $rev = Revision
::newFromId( $this->mRevisionId
);
6032 $this->mRevisionObject
= $rev;
6034 return $this->mRevisionObject
;
6038 * Get the timestamp associated with the current revision, adjusted for
6039 * the default server-local timestamp
6042 public function getRevisionTimestamp() {
6043 if ( is_null( $this->mRevisionTimestamp
) ) {
6046 $revObject = $this->getRevisionObject();
6047 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
6049 # The cryptic '' timezone parameter tells to use the site-default
6050 # timezone offset instead of the user settings.
6052 # Since this value will be saved into the parser cache, served
6053 # to other users, and potentially even used inside links and such,
6054 # it needs to be consistent for all visitors.
6055 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
6058 return $this->mRevisionTimestamp
;
6062 * Get the name of the user that edited the last revision
6064 * @return string User name
6066 public function getRevisionUser() {
6067 if ( is_null( $this->mRevisionUser
) ) {
6068 $revObject = $this->getRevisionObject();
6070 # if this template is subst: the revision id will be blank,
6071 # so just use the current user's name
6073 $this->mRevisionUser
= $revObject->getUserText();
6074 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6075 $this->mRevisionUser
= $this->getUser()->getName();
6078 return $this->mRevisionUser
;
6082 * Get the size of the revision
6084 * @return int|null Revision size
6086 public function getRevisionSize() {
6087 if ( is_null( $this->mRevisionSize
) ) {
6088 $revObject = $this->getRevisionObject();
6090 # if this variable is subst: the revision id will be blank,
6091 # so just use the parser input size, because the own substituation
6092 # will change the size.
6094 $this->mRevisionSize
= $revObject->getSize();
6095 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6096 $this->mRevisionSize
= $this->mInputSize
;
6099 return $this->mRevisionSize
;
6103 * Mutator for $mDefaultSort
6105 * @param string $sort New value
6107 public function setDefaultSort( $sort ) {
6108 $this->mDefaultSort
= $sort;
6109 $this->mOutput
->setProperty( 'defaultsort', $sort );
6113 * Accessor for $mDefaultSort
6114 * Will use the empty string if none is set.
6116 * This value is treated as a prefix, so the
6117 * empty string is equivalent to sorting by
6122 public function getDefaultSort() {
6123 if ( $this->mDefaultSort
!== false ) {
6124 return $this->mDefaultSort
;
6131 * Accessor for $mDefaultSort
6132 * Unlike getDefaultSort(), will return false if none is set
6134 * @return string|bool
6136 public function getCustomDefaultSort() {
6137 return $this->mDefaultSort
;
6141 * Try to guess the section anchor name based on a wikitext fragment
6142 * presumably extracted from a heading, for example "Header" from
6145 * @param string $text
6149 public function guessSectionNameFromWikiText( $text ) {
6150 # Strip out wikitext links(they break the anchor)
6151 $text = $this->stripSectionName( $text );
6152 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6153 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
6157 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6158 * instead. For use in redirects, since IE6 interprets Redirect: headers
6159 * as something other than UTF-8 (apparently?), resulting in breakage.
6161 * @param string $text The section name
6162 * @return string An anchor
6164 public function guessLegacySectionNameFromWikiText( $text ) {
6165 # Strip out wikitext links(they break the anchor)
6166 $text = $this->stripSectionName( $text );
6167 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6168 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
6172 * Strips a text string of wikitext for use in a section anchor
6174 * Accepts a text string and then removes all wikitext from the
6175 * string and leaves only the resultant text (i.e. the result of
6176 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6177 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6178 * to create valid section anchors by mimicing the output of the
6179 * parser when headings are parsed.
6181 * @param string $text Text string to be stripped of wikitext
6182 * for use in a Section anchor
6183 * @return string Filtered text string
6185 public function stripSectionName( $text ) {
6186 # Strip internal link markup
6187 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6188 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6190 # Strip external link markup
6191 # @todo FIXME: Not tolerant to blank link text
6192 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6193 # on how many empty links there are on the page - need to figure that out.
6194 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6196 # Parse wikitext quotes (italics & bold)
6197 $text = $this->doQuotes( $text );
6200 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
6205 * strip/replaceVariables/unstrip for preprocessor regression testing
6207 * @param string $text
6208 * @param Title $title
6209 * @param ParserOptions $options
6210 * @param int $outputType
6214 public function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
6215 $magicScopeVariable = $this->lock();
6216 $this->startParse( $title, $options, $outputType, true );
6218 $text = $this->replaceVariables( $text );
6219 $text = $this->mStripState
->unstripBoth( $text );
6220 $text = Sanitizer
::removeHTMLtags( $text );
6225 * @param string $text
6226 * @param Title $title
6227 * @param ParserOptions $options
6230 public function testPst( $text, Title
$title, ParserOptions
$options ) {
6231 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6235 * @param string $text
6236 * @param Title $title
6237 * @param ParserOptions $options
6240 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
6241 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
6245 * Call a callback function on all regions of the given text that are not
6246 * inside strip markers, and replace those regions with the return value
6247 * of the callback. For example, with input:
6251 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6252 * two strings will be replaced with the value returned by the callback in
6256 * @param callable $callback
6260 public function markerSkipCallback( $s, $callback ) {
6263 while ( $i < strlen( $s ) ) {
6264 $markerStart = strpos( $s, self
::MARKER_PREFIX
, $i );
6265 if ( $markerStart === false ) {
6266 $out .= call_user_func( $callback, substr( $s, $i ) );
6269 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6270 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6271 if ( $markerEnd === false ) {
6272 $out .= substr( $s, $markerStart );
6275 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6276 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6285 * Remove any strip markers found in the given text.
6287 * @param string $text Input string
6290 public function killMarkers( $text ) {
6291 return $this->mStripState
->killMarkers( $text );
6295 * Save the parser state required to convert the given half-parsed text to
6296 * HTML. "Half-parsed" in this context means the output of
6297 * recursiveTagParse() or internalParse(). This output has strip markers
6298 * from replaceVariables (extensionSubstitution() etc.), and link
6299 * placeholders from replaceLinkHolders().
6301 * Returns an array which can be serialized and stored persistently. This
6302 * array can later be loaded into another parser instance with
6303 * unserializeHalfParsedText(). The text can then be safely incorporated into
6304 * the return value of a parser hook.
6306 * @param string $text
6310 public function serializeHalfParsedText( $text ) {
6313 'version' => self
::HALF_PARSED_VERSION
,
6314 'stripState' => $this->mStripState
->getSubState( $text ),
6315 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6321 * Load the parser state given in the $data array, which is assumed to
6322 * have been generated by serializeHalfParsedText(). The text contents is
6323 * extracted from the array, and its markers are transformed into markers
6324 * appropriate for the current Parser instance. This transformed text is
6325 * returned, and can be safely included in the return value of a parser
6328 * If the $data array has been stored persistently, the caller should first
6329 * check whether it is still valid, by calling isValidHalfParsedText().
6331 * @param array $data Serialized data
6332 * @throws MWException
6335 public function unserializeHalfParsedText( $data ) {
6336 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6337 throw new MWException( __METHOD__
. ': invalid version' );
6340 # First, extract the strip state.
6341 $texts = array( $data['text'] );
6342 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6344 # Now renumber links
6345 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6347 # Should be good to go.
6352 * Returns true if the given array, presumed to be generated by
6353 * serializeHalfParsedText(), is compatible with the current version of the
6356 * @param array $data
6360 public function isValidHalfParsedText( $data ) {
6361 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6365 * Parsed a width param of imagelink like 300px or 200x300px
6367 * @param string $value
6372 public function parseWidthParam( $value ) {
6373 $parsedWidthParam = array();
6374 if ( $value === '' ) {
6375 return $parsedWidthParam;
6378 # (bug 13500) In both cases (width/height and width only),
6379 # permit trailing "px" for backward compatibility.
6380 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6381 $width = intval( $m[1] );
6382 $height = intval( $m[2] );
6383 $parsedWidthParam['width'] = $width;
6384 $parsedWidthParam['height'] = $height;
6385 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6386 $width = intval( $value );
6387 $parsedWidthParam['width'] = $width;
6389 return $parsedWidthParam;
6393 * Lock the current instance of the parser.
6395 * This is meant to stop someone from calling the parser
6396 * recursively and messing up all the strip state.
6398 * @throws MWException If parser is in a parse
6399 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6401 protected function lock() {
6402 if ( $this->mInParse
) {
6403 throw new MWException( "Parser state cleared while parsing. "
6404 . "Did you call Parser::parse recursively?" );
6406 $this->mInParse
= true;
6409 $recursiveCheck = new ScopedCallback( function() use ( $that ) {
6410 $that->mInParse
= false;
6413 return $recursiveCheck;
6417 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6419 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6420 * or if there is more than one <p/> tag in the input HTML.
6422 * @param string $html
6426 public static function stripOuterParagraph( $html ) {
6428 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6429 if ( strpos( $m[1], '</p>' ) === false ) {
6438 * Return this parser if it is not doing anything, otherwise
6439 * get a fresh parser. You can use this method by doing
6440 * $myParser = $wgParser->getFreshParser(), or more simply
6441 * $wgParser->getFreshParser()->parse( ... );
6442 * if you're unsure if $wgParser is safe to use.
6445 * @return Parser A parser object that is not parsing anything
6447 public function getFreshParser() {
6448 global $wgParserConf;
6449 if ( $this->mInParse
) {
6450 return new $wgParserConf['class']( $wgParserConf );
6457 * Set's up the PHP implementation of OOUI for use in this request
6458 * and instructs OutputPage to enable OOUI for itself.
6462 public function enableOOUI() {
6463 OutputPage
::setupOOUI();
6464 $this->mOutput
->setEnableOOUI( true );