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 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F\p{Zs}]+)
91 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
93 # Regular expression for a non-newline space
94 const SPACE_NOT_NL
= '(?:\t| |&\#0*160;|&\#[Xx]0*[Aa]0;|\p{Zs})';
96 # State constants for the definition list colon extraction
97 const COLON_STATE_TEXT
= 0;
98 const COLON_STATE_TAG
= 1;
99 const COLON_STATE_TAGSTART
= 2;
100 const COLON_STATE_CLOSETAG
= 3;
101 const COLON_STATE_TAGSLASH
= 4;
102 const COLON_STATE_COMMENT
= 5;
103 const COLON_STATE_COMMENTDASH
= 6;
104 const COLON_STATE_COMMENTDASHDASH
= 7;
106 # Flags for preprocessToDom
107 const PTD_FOR_INCLUSION
= 1;
109 # Allowed values for $this->mOutputType
110 # Parameter to startExternalParse().
111 const OT_HTML
= 1; # like parse()
112 const OT_WIKI
= 2; # like preSaveTransform()
113 const OT_PREPROCESS
= 3; # like preprocess()
115 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
118 * @var string Prefix and suffix for temporary replacement strings
119 * for the multipass parser.
121 * \x7f should never appear in input as it's disallowed in XML.
122 * Using it at the front also gives us a little extra robustness
123 * since it shouldn't match when butted up against identifier-like
126 * Must not consist of all title characters, or else it will change
127 * the behavior of <nowiki> in a link.
129 const MARKER_SUFFIX
= "-QINU\x7f";
130 const MARKER_PREFIX
= "\x7fUNIQ-";
132 # Markers used for wrapping the table of contents
133 const TOC_START
= '<mw:toc>';
134 const TOC_END
= '</mw:toc>';
137 public $mTagHooks = array();
138 public $mTransparentTagHooks = array();
139 public $mFunctionHooks = array();
140 public $mFunctionSynonyms = array( 0 => array(), 1 => array() );
141 public $mFunctionTagHooks = array();
142 public $mStripList = array();
143 public $mDefaultStripList = array();
144 public $mVarCache = array();
145 public $mImageParams = array();
146 public $mImageParamsMagicArray = array();
147 public $mMarkerIndex = 0;
148 public $mFirstCall = true;
150 # Initialised by initialiseVariables()
153 * @var MagicWordArray
158 * @var MagicWordArray
161 # Initialised in constructor
162 public $mConf, $mExtLinkBracketedRegex, $mUrlProtocols;
164 # Initialized in getPreprocessor()
165 /** @var Preprocessor */
166 public $mPreprocessor;
168 # Cleared with clearState():
173 public $mAutonumber, $mDTopen;
180 public $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
182 * @var LinkHolderArray
184 public $mLinkHolders;
187 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
188 public $mDefaultSort;
189 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
190 public $mExpensiveFunctionCount; # number of expensive parser function calls
191 public $mShowToc, $mForceTocPosition;
196 public $mUser; # User object; only used when doing pre-save transform
199 # These are variables reset at least once per parse regardless of $clearState
209 public $mTitle; # Title context, used for self-link rendering and similar things
210 public $mOutputType; # Output type, one of the OT_xxx constants
211 public $ot; # Shortcut alias, see setOutputType()
212 public $mRevisionObject; # The revision object of the specified revision ID
213 public $mRevisionId; # ID to display in {{REVISIONID}} tags
214 public $mRevisionTimestamp; # The timestamp of the specified revision ID
215 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag
216 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
217 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp
218 public $mInputSize = false; # For {{PAGESIZE}} on current page.
221 * @var string Deprecated accessor for the strip marker prefix.
222 * @deprecated since 1.26; use Parser::MARKER_PREFIX instead.
224 public $mUniqPrefix = Parser
::MARKER_PREFIX
;
227 * @var array Array with the language name of each language link (i.e. the
228 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
229 * duplicate language links to the ParserOutput.
231 public $mLangLinkLanguages;
234 * @var MapCacheLRU|null
237 * A cache of the current revisions of titles. Keys are $title->getPrefixedDbKey()
239 public $currentRevisionCache;
242 * @var bool Recursive call protection.
243 * This variable should be treated as if it were private.
245 public $mInParse = false;
247 /** @var SectionProfiler */
248 protected $mProfiler;
253 public function __construct( $conf = array() ) {
254 $this->mConf
= $conf;
255 $this->mUrlProtocols
= wfUrlProtocols();
256 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
257 self
::EXT_LINK_URL_CLASS
. '+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
258 if ( isset( $conf['preprocessorClass'] ) ) {
259 $this->mPreprocessorClass
= $conf['preprocessorClass'];
260 } elseif ( defined( 'HPHP_VERSION' ) ) {
261 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
262 $this->mPreprocessorClass
= 'Preprocessor_Hash';
263 } elseif ( extension_loaded( 'domxml' ) ) {
264 # PECL extension that conflicts with the core DOM extension (bug 13770)
265 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
266 $this->mPreprocessorClass
= 'Preprocessor_Hash';
267 } elseif ( extension_loaded( 'dom' ) ) {
268 $this->mPreprocessorClass
= 'Preprocessor_DOM';
270 $this->mPreprocessorClass
= 'Preprocessor_Hash';
272 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
276 * Reduce memory usage to reduce the impact of circular references
278 public function __destruct() {
279 if ( isset( $this->mLinkHolders
) ) {
280 unset( $this->mLinkHolders
);
282 foreach ( $this as $name => $value ) {
283 unset( $this->$name );
288 * Allow extensions to clean up when the parser is cloned
290 public function __clone() {
291 $this->mInParse
= false;
293 // Bug 56226: When you create a reference "to" an object field, that
294 // makes the object field itself be a reference too (until the other
295 // reference goes out of scope). When cloning, any field that's a
296 // reference is copied as a reference in the new object. Both of these
297 // are defined PHP5 behaviors, as inconvenient as it is for us when old
298 // hooks from PHP4 days are passing fields by reference.
299 foreach ( array( 'mStripState', 'mVarCache' ) as $k ) {
300 // Make a non-reference copy of the field, then rebind the field to
301 // reference the new copy.
307 Hooks
::run( 'ParserCloned', array( $this ) );
311 * Do various kinds of initialisation on the first call of the parser
313 public function firstCallInit() {
314 if ( !$this->mFirstCall
) {
317 $this->mFirstCall
= false;
319 CoreParserFunctions
::register( $this );
320 CoreTagHooks
::register( $this );
321 $this->initialiseVariables();
323 Hooks
::run( 'ParserFirstCallInit', array( &$this ) );
331 public function clearState() {
332 if ( $this->mFirstCall
) {
333 $this->firstCallInit();
335 $this->mOutput
= new ParserOutput
;
336 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
337 $this->mAutonumber
= 0;
338 $this->mLastSection
= '';
339 $this->mDTopen
= false;
340 $this->mIncludeCount
= array();
341 $this->mArgStack
= false;
342 $this->mInPre
= false;
343 $this->mLinkHolders
= new LinkHolderArray( $this );
345 $this->mRevisionObject
= $this->mRevisionTimestamp
=
346 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
347 $this->mVarCache
= array();
349 $this->mLangLinkLanguages
= array();
350 $this->currentRevisionCache
= null;
352 $this->mStripState
= new StripState
;
354 # Clear these on every parse, bug 4549
355 $this->mTplRedirCache
= $this->mTplDomCache
= array();
357 $this->mShowToc
= true;
358 $this->mForceTocPosition
= false;
359 $this->mIncludeSizes
= array(
363 $this->mPPNodeCount
= 0;
364 $this->mGeneratedPPNodeCount
= 0;
365 $this->mHighestExpansionDepth
= 0;
366 $this->mDefaultSort
= false;
367 $this->mHeadings
= array();
368 $this->mDoubleUnderscores
= array();
369 $this->mExpensiveFunctionCount
= 0;
372 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
373 $this->mPreprocessor
= null;
376 $this->mProfiler
= new SectionProfiler();
378 Hooks
::run( 'ParserClearState', array( &$this ) );
382 * Convert wikitext to HTML
383 * Do not call this function recursively.
385 * @param string $text Text we want to parse
386 * @param Title $title
387 * @param ParserOptions $options
388 * @param bool $linestart
389 * @param bool $clearState
390 * @param int $revid Number to pass in {{REVISIONID}}
391 * @return ParserOutput A ParserOutput
393 public function parse( $text, Title
$title, ParserOptions
$options,
394 $linestart = true, $clearState = true, $revid = null
397 * First pass--just handle <nowiki> sections, pass the rest off
398 * to internalParse() which does all the real work.
401 global $wgShowHostnames;
404 // We use U+007F DELETE to construct strip markers, so we have to make
405 // sure that this character does not occur in the input text.
406 $text = strtr( $text, "\x7f", "?" );
407 $magicScopeVariable = $this->lock();
410 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
412 $this->currentRevisionCache
= null;
413 $this->mInputSize
= strlen( $text );
414 if ( $this->mOptions
->getEnableLimitReport() ) {
415 $this->mOutput
->resetParseStartTime();
418 $oldRevisionId = $this->mRevisionId
;
419 $oldRevisionObject = $this->mRevisionObject
;
420 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
421 $oldRevisionUser = $this->mRevisionUser
;
422 $oldRevisionSize = $this->mRevisionSize
;
423 if ( $revid !== null ) {
424 $this->mRevisionId
= $revid;
425 $this->mRevisionObject
= null;
426 $this->mRevisionTimestamp
= null;
427 $this->mRevisionUser
= null;
428 $this->mRevisionSize
= null;
431 Hooks
::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
433 Hooks
::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
434 $text = $this->internalParse( $text );
435 Hooks
::run( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
437 $text = $this->internalParseHalfParsed( $text, true, $linestart );
440 * A converted title will be provided in the output object if title and
441 * content conversion are enabled, the article text does not contain
442 * a conversion-suppressing double-underscore tag, and no
443 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
444 * automatic link conversion.
446 if ( !( $options->getDisableTitleConversion()
447 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
448 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
449 ||
$this->mOutput
->getDisplayTitle() !== false )
451 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
452 if ( $convruletitle ) {
453 $this->mOutput
->setTitleText( $convruletitle );
455 $titleText = $this->getConverterLanguage()->convertTitle( $title );
456 $this->mOutput
->setTitleText( $titleText );
460 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
461 $this->limitationWarn( 'expensive-parserfunction',
462 $this->mExpensiveFunctionCount
,
463 $this->mOptions
->getExpensiveParserFunctionLimit()
467 # Information on include size limits, for the benefit of users who try to skirt them
468 if ( $this->mOptions
->getEnableLimitReport() ) {
469 $max = $this->mOptions
->getMaxIncludeSize();
471 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
472 if ( $cpuTime !== null ) {
473 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
474 sprintf( "%.3f", $cpuTime )
478 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
479 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
480 sprintf( "%.3f", $wallTime )
483 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
484 array( $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() )
486 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
487 array( $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() )
489 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
490 array( $this->mIncludeSizes
['post-expand'], $max )
492 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
493 array( $this->mIncludeSizes
['arg'], $max )
495 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
496 array( $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() )
498 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
499 array( $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() )
501 Hooks
::run( 'ParserLimitReportPrepare', array( $this, $this->mOutput
) );
503 $limitReport = "NewPP limit report\n";
504 if ( $wgShowHostnames ) {
505 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
507 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
508 if ( Hooks
::run( 'ParserLimitReportFormat',
509 array( $key, &$value, &$limitReport, false, false )
511 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
512 $valueMsg = wfMessage( array( "$key-value-text", "$key-value" ) )
513 ->inLanguage( 'en' )->useDatabase( false );
514 if ( !$valueMsg->exists() ) {
515 $valueMsg = new RawMessage( '$1' );
517 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
518 $valueMsg->params( $value );
519 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
523 // Since we're not really outputting HTML, decode the entities and
524 // then re-encode the things that need hiding inside HTML comments.
525 $limitReport = htmlspecialchars_decode( $limitReport );
526 Hooks
::run( 'ParserLimitReport', array( $this, &$limitReport ) );
528 // Sanitize for comment. Note '‐' in the replacement is U+2010,
529 // which looks much like the problematic '-'.
530 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&' ), $limitReport );
531 $text .= "\n<!-- \n$limitReport-->\n";
533 // Add on template profiling data
534 $dataByFunc = $this->mProfiler
->getFunctionStats();
535 uasort( $dataByFunc, function ( $a, $b ) {
536 return $a['real'] < $b['real']; // descending order
538 $profileReport = "Transclusion expansion time report (%,ms,calls,template)\n";
539 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
540 $profileReport .= sprintf( "%6.2f%% %8.3f %6d - %s\n",
541 $item['%real'], $item['real'], $item['calls'],
542 htmlspecialchars( $item['name'] ) );
544 $text .= "\n<!-- \n$profileReport-->\n";
546 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
547 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
548 $this->mTitle
->getPrefixedDBkey() );
551 $this->mOutput
->setText( $text );
553 $this->mRevisionId
= $oldRevisionId;
554 $this->mRevisionObject
= $oldRevisionObject;
555 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
556 $this->mRevisionUser
= $oldRevisionUser;
557 $this->mRevisionSize
= $oldRevisionSize;
558 $this->mInputSize
= false;
559 $this->currentRevisionCache
= null;
561 return $this->mOutput
;
565 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
566 * can be called from an extension tag hook.
568 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
569 * instead, which means that lists and links have not been fully parsed yet,
570 * and strip markers are still present.
572 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
574 * Use this function if you're a parser tag hook and you want to parse
575 * wikitext before or after applying additional transformations, and you
576 * intend to *return the result as hook output*, which will cause it to go
577 * through the rest of parsing process automatically.
579 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
580 * $text are not expanded
582 * @param string $text Text extension wants to have parsed
583 * @param bool|PPFrame $frame The frame to use for expanding any template variables
584 * @return string UNSAFE half-parsed HTML
586 public function recursiveTagParse( $text, $frame = false ) {
587 Hooks
::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
588 Hooks
::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
589 $text = $this->internalParse( $text, false, $frame );
594 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
595 * point can be called from an extension tag hook.
597 * The output of this function is fully-parsed HTML that is safe for output.
598 * If you're a parser tag hook, you might want to use recursiveTagParse()
601 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
602 * $text are not expanded
606 * @param string $text Text extension wants to have parsed
607 * @param bool|PPFrame $frame The frame to use for expanding any template variables
608 * @return string Fully parsed HTML
610 public function recursiveTagParseFully( $text, $frame = false ) {
611 $text = $this->recursiveTagParse( $text, $frame );
612 $text = $this->internalParseHalfParsed( $text, false );
617 * Expand templates and variables in the text, producing valid, static wikitext.
618 * Also removes comments.
619 * Do not call this function recursively.
620 * @param string $text
621 * @param Title $title
622 * @param ParserOptions $options
623 * @param int|null $revid
624 * @param bool|PPFrame $frame
625 * @return mixed|string
627 public function preprocess( $text, Title
$title = null,
628 ParserOptions
$options, $revid = null, $frame = false
630 $magicScopeVariable = $this->lock();
631 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
632 if ( $revid !== null ) {
633 $this->mRevisionId
= $revid;
635 Hooks
::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
636 Hooks
::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
637 $text = $this->replaceVariables( $text, $frame );
638 $text = $this->mStripState
->unstripBoth( $text );
643 * Recursive parser entry point that can be called from an extension tag
646 * @param string $text Text to be expanded
647 * @param bool|PPFrame $frame The frame to use for expanding any template variables
651 public function recursivePreprocess( $text, $frame = false ) {
652 $text = $this->replaceVariables( $text, $frame );
653 $text = $this->mStripState
->unstripBoth( $text );
658 * Process the wikitext for the "?preload=" feature. (bug 5210)
660 * "<noinclude>", "<includeonly>" etc. are parsed as for template
661 * transclusion, comments, templates, arguments, tags hooks and parser
662 * functions are untouched.
664 * @param string $text
665 * @param Title $title
666 * @param ParserOptions $options
667 * @param array $params
670 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = array() ) {
671 $msg = new RawMessage( $text );
672 $text = $msg->params( $params )->plain();
674 # Parser (re)initialisation
675 $magicScopeVariable = $this->lock();
676 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
678 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
679 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
680 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
681 $text = $this->mStripState
->unstripBoth( $text );
686 * Get a random string
689 * @deprecated since 1.26; use wfRandomString() instead.
691 public static function getRandomString() {
692 wfDeprecated( __METHOD__
, '1.26' );
693 return wfRandomString( 16 );
697 * Set the current user.
698 * Should only be used when doing pre-save transform.
700 * @param User|null $user User object or null (to reset)
702 public function setUser( $user ) {
703 $this->mUser
= $user;
707 * Accessor for mUniqPrefix.
710 * @deprecated since 1.26; use Parser::MARKER_PREFIX instead.
712 public function uniqPrefix() {
713 wfDeprecated( __METHOD__
, '1.26' );
714 return self
::MARKER_PREFIX
;
718 * Set the context title
722 public function setTitle( $t ) {
724 $t = Title
::newFromText( 'NO TITLE' );
727 if ( $t->hasFragment() ) {
728 # Strip the fragment to avoid various odd effects
729 $this->mTitle
= clone $t;
730 $this->mTitle
->setFragment( '' );
737 * Accessor for the Title object
741 public function getTitle() {
742 return $this->mTitle
;
746 * Accessor/mutator for the Title object
748 * @param Title $x Title object or null to just get the current one
751 public function Title( $x = null ) {
752 return wfSetVar( $this->mTitle
, $x );
756 * Set the output type
758 * @param int $ot New value
760 public function setOutputType( $ot ) {
761 $this->mOutputType
= $ot;
764 'html' => $ot == self
::OT_HTML
,
765 'wiki' => $ot == self
::OT_WIKI
,
766 'pre' => $ot == self
::OT_PREPROCESS
,
767 'plain' => $ot == self
::OT_PLAIN
,
772 * Accessor/mutator for the output type
774 * @param int|null $x New value or null to just get the current one
777 public function OutputType( $x = null ) {
778 return wfSetVar( $this->mOutputType
, $x );
782 * Get the ParserOutput object
784 * @return ParserOutput
786 public function getOutput() {
787 return $this->mOutput
;
791 * Get the ParserOptions object
793 * @return ParserOptions
795 public function getOptions() {
796 return $this->mOptions
;
800 * Accessor/mutator for the ParserOptions object
802 * @param ParserOptions $x New value or null to just get the current one
803 * @return ParserOptions Current ParserOptions object
805 public function Options( $x = null ) {
806 return wfSetVar( $this->mOptions
, $x );
812 public function nextLinkID() {
813 return $this->mLinkID++
;
819 public function setLinkID( $id ) {
820 $this->mLinkID
= $id;
824 * Get a language object for use in parser functions such as {{FORMATNUM:}}
827 public function getFunctionLang() {
828 return $this->getTargetLanguage();
832 * Get the target language for the content being parsed. This is usually the
833 * language that the content is in.
837 * @throws MWException
840 public function getTargetLanguage() {
841 $target = $this->mOptions
->getTargetLanguage();
843 if ( $target !== null ) {
845 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
846 return $this->mOptions
->getUserLangObj();
847 } elseif ( is_null( $this->mTitle
) ) {
848 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
851 return $this->mTitle
->getPageLanguage();
855 * Get the language object for language conversion
856 * @return Language|null
858 public function getConverterLanguage() {
859 return $this->getTargetLanguage();
863 * Get a User object either from $this->mUser, if set, or from the
864 * ParserOptions object otherwise
868 public function getUser() {
869 if ( !is_null( $this->mUser
) ) {
872 return $this->mOptions
->getUser();
876 * Get a preprocessor object
878 * @return Preprocessor
880 public function getPreprocessor() {
881 if ( !isset( $this->mPreprocessor
) ) {
882 $class = $this->mPreprocessorClass
;
883 $this->mPreprocessor
= new $class( $this );
885 return $this->mPreprocessor
;
889 * Replaces all occurrences of HTML-style comments and the given tags
890 * in the text with a random marker and returns the next text. The output
891 * parameter $matches will be an associative array filled with data in
895 * 'UNIQ-xxxxx' => array(
898 * array( 'param' => 'x' ),
899 * '<element param="x">tag content</element>' ) )
902 * @param array $elements List of element names. Comments are always extracted.
903 * @param string $text Source text string.
904 * @param array $matches Out parameter, Array: extracted tags
905 * @param string|null $uniq_prefix
906 * @return string Stripped text
907 * @since 1.26 The uniq_prefix argument is deprecated.
909 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = null ) {
910 if ( $uniq_prefix !== null ) {
911 wfDeprecated( __METHOD__
. ' called with $prefix argument', '1.26' );
917 $taglist = implode( '|', $elements );
918 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
920 while ( $text != '' ) {
921 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
923 if ( count( $p ) < 5 ) {
926 if ( count( $p ) > 5 ) {
940 $marker = self
::MARKER_PREFIX
. "-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
941 $stripped .= $marker;
943 if ( $close === '/>' ) {
944 # Empty element tag, <tag />
949 if ( $element === '!--' ) {
952 $end = "/(<\\/$element\\s*>)/i";
954 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
956 if ( count( $q ) < 3 ) {
957 # No end tag -- let it run out to the end of the text.
966 $matches[$marker] = array( $element,
968 Sanitizer
::decodeTagAttributes( $attributes ),
969 "<$element$attributes$close$content$tail" );
975 * Get a list of strippable XML-like elements
979 public function getStripList() {
980 return $this->mStripList
;
984 * Add an item to the strip state
985 * Returns the unique tag which must be inserted into the stripped text
986 * The tag will be replaced with the original text in unstrip()
988 * @param string $text
992 public function insertStripItem( $text ) {
993 $marker = self
::MARKER_PREFIX
. "-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
994 $this->mMarkerIndex++
;
995 $this->mStripState
->addGeneral( $marker, $text );
1000 * parse the wiki syntax used to render tables
1003 * @param string $text
1006 public function doTableStuff( $text ) {
1008 $lines = StringUtils
::explode( "\n", $text );
1010 $td_history = array(); # Is currently a td tag open?
1011 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
1012 $tr_history = array(); # Is currently a tr tag open?
1013 $tr_attributes = array(); # history of tr attributes
1014 $has_opened_tr = array(); # Did this table open a <tr> element?
1015 $indent_level = 0; # indent level of the table
1017 foreach ( $lines as $outLine ) {
1018 $line = trim( $outLine );
1020 if ( $line === '' ) { # empty line, go to next line
1021 $out .= $outLine . "\n";
1025 $first_character = $line[0];
1026 $first_two = substr( $line, 0, 2 );
1029 if ( preg_match( '/^(:*)\s*\{\|(.*)$/', $line, $matches ) ) {
1030 # First check if we are starting a new table
1031 $indent_level = strlen( $matches[1] );
1033 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1034 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1036 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1037 array_push( $td_history, false );
1038 array_push( $last_tag_history, '' );
1039 array_push( $tr_history, false );
1040 array_push( $tr_attributes, '' );
1041 array_push( $has_opened_tr, false );
1042 } elseif ( count( $td_history ) == 0 ) {
1043 # Don't do any of the following
1044 $out .= $outLine . "\n";
1046 } elseif ( $first_two === '|}' ) {
1047 # We are ending a table
1048 $line = '</table>' . substr( $line, 2 );
1049 $last_tag = array_pop( $last_tag_history );
1051 if ( !array_pop( $has_opened_tr ) ) {
1052 $line = "<tr><td></td></tr>{$line}";
1055 if ( array_pop( $tr_history ) ) {
1056 $line = "</tr>{$line}";
1059 if ( array_pop( $td_history ) ) {
1060 $line = "</{$last_tag}>{$line}";
1062 array_pop( $tr_attributes );
1063 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
1064 } elseif ( $first_two === '|-' ) {
1065 # Now we have a table row
1066 $line = preg_replace( '#^\|-+#', '', $line );
1068 # Whats after the tag is now only attributes
1069 $attributes = $this->mStripState
->unstripBoth( $line );
1070 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1071 array_pop( $tr_attributes );
1072 array_push( $tr_attributes, $attributes );
1075 $last_tag = array_pop( $last_tag_history );
1076 array_pop( $has_opened_tr );
1077 array_push( $has_opened_tr, true );
1079 if ( array_pop( $tr_history ) ) {
1083 if ( array_pop( $td_history ) ) {
1084 $line = "</{$last_tag}>{$line}";
1088 array_push( $tr_history, false );
1089 array_push( $td_history, false );
1090 array_push( $last_tag_history, '' );
1091 } elseif ( $first_character === '|'
1092 ||
$first_character === '!'
1093 ||
$first_two === '|+'
1095 # This might be cell elements, td, th or captions
1096 if ( $first_two === '|+' ) {
1097 $first_character = '+';
1098 $line = substr( $line, 2 );
1100 $line = substr( $line, 1 );
1103 if ( $first_character === '!' ) {
1104 $line = str_replace( '!!', '||', $line );
1107 # Split up multiple cells on the same line.
1108 # FIXME : This can result in improper nesting of tags processed
1109 # by earlier parser steps, but should avoid splitting up eg
1110 # attribute values containing literal "||".
1111 $cells = StringUtils
::explodeMarkup( '||', $line );
1115 # Loop through each table cell
1116 foreach ( $cells as $cell ) {
1118 if ( $first_character !== '+' ) {
1119 $tr_after = array_pop( $tr_attributes );
1120 if ( !array_pop( $tr_history ) ) {
1121 $previous = "<tr{$tr_after}>\n";
1123 array_push( $tr_history, true );
1124 array_push( $tr_attributes, '' );
1125 array_pop( $has_opened_tr );
1126 array_push( $has_opened_tr, true );
1129 $last_tag = array_pop( $last_tag_history );
1131 if ( array_pop( $td_history ) ) {
1132 $previous = "</{$last_tag}>\n{$previous}";
1135 if ( $first_character === '|' ) {
1137 } elseif ( $first_character === '!' ) {
1139 } elseif ( $first_character === '+' ) {
1140 $last_tag = 'caption';
1145 array_push( $last_tag_history, $last_tag );
1147 # A cell could contain both parameters and data
1148 $cell_data = explode( '|', $cell, 2 );
1150 # Bug 553: Note that a '|' inside an invalid link should not
1151 # be mistaken as delimiting cell parameters
1152 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1153 $cell = "{$previous}<{$last_tag}>{$cell}";
1154 } elseif ( count( $cell_data ) == 1 ) {
1155 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1157 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1158 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1159 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1163 array_push( $td_history, true );
1166 $out .= $outLine . "\n";
1169 # Closing open td, tr && table
1170 while ( count( $td_history ) > 0 ) {
1171 if ( array_pop( $td_history ) ) {
1174 if ( array_pop( $tr_history ) ) {
1177 if ( !array_pop( $has_opened_tr ) ) {
1178 $out .= "<tr><td></td></tr>\n";
1181 $out .= "</table>\n";
1184 # Remove trailing line-ending (b/c)
1185 if ( substr( $out, -1 ) === "\n" ) {
1186 $out = substr( $out, 0, -1 );
1189 # special case: don't return empty table
1190 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1198 * Helper function for parse() that transforms wiki markup into half-parsed
1199 * HTML. Only called for $mOutputType == self::OT_HTML.
1203 * @param string $text
1204 * @param bool $isMain
1205 * @param PPFrame|bool $frame
1209 public function internalParse( $text, $isMain = true, $frame = false ) {
1213 # Hook to suspend the parser in this state
1214 if ( !Hooks
::run( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1218 # if $frame is provided, then use $frame for replacing any variables
1220 # use frame depth to infer how include/noinclude tags should be handled
1221 # depth=0 means this is the top-level document; otherwise it's an included document
1222 if ( !$frame->depth
) {
1225 $flag = Parser
::PTD_FOR_INCLUSION
;
1227 $dom = $this->preprocessToDom( $text, $flag );
1228 $text = $frame->expand( $dom );
1230 # if $frame is not provided, then use old-style replaceVariables
1231 $text = $this->replaceVariables( $text );
1234 Hooks
::run( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1235 $text = Sanitizer
::removeHTMLtags(
1237 array( &$this, 'attributeStripCallback' ),
1239 array_keys( $this->mTransparentTagHooks
)
1241 Hooks
::run( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1243 # Tables need to come after variable replacement for things to work
1244 # properly; putting them before other transformations should keep
1245 # exciting things like link expansions from showing up in surprising
1247 $text = $this->doTableStuff( $text );
1249 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1251 $text = $this->doDoubleUnderscore( $text );
1253 $text = $this->doHeadings( $text );
1254 $text = $this->replaceInternalLinks( $text );
1255 $text = $this->doAllQuotes( $text );
1256 $text = $this->replaceExternalLinks( $text );
1258 # replaceInternalLinks may sometimes leave behind
1259 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1260 $text = str_replace( self
::MARKER_PREFIX
. 'NOPARSE', '', $text );
1262 $text = $this->doMagicLinks( $text );
1263 $text = $this->formatHeadings( $text, $origText, $isMain );
1269 * Helper function for parse() that transforms half-parsed HTML into fully
1272 * @param string $text
1273 * @param bool $isMain
1274 * @param bool $linestart
1277 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1278 global $wgUseTidy, $wgAlwaysUseTidy;
1280 $text = $this->mStripState
->unstripGeneral( $text );
1283 Hooks
::run( 'ParserAfterUnstrip', array( &$this, &$text ) );
1286 # Clean up special characters, only run once, next-to-last before doBlockLevels
1288 # french spaces, last one Guillemet-left
1289 # only if there is something before the space
1290 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
1291 # french spaces, Guillemet-right
1292 '/(\\302\\253) /' => '\\1 ',
1293 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
1295 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
1297 $text = $this->doBlockLevels( $text, $linestart );
1299 $this->replaceLinkHolders( $text );
1302 * The input doesn't get language converted if
1304 * b) Content isn't converted
1305 * c) It's a conversion table
1306 * d) it is an interface message (which is in the user language)
1308 if ( !( $this->mOptions
->getDisableContentConversion()
1309 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
1311 if ( !$this->mOptions
->getInterfaceMessage() ) {
1312 # The position of the convert() call should not be changed. it
1313 # assumes that the links are all replaced and the only thing left
1314 # is the <nowiki> mark.
1315 $text = $this->getConverterLanguage()->convert( $text );
1319 $text = $this->mStripState
->unstripNoWiki( $text );
1322 Hooks
::run( 'ParserBeforeTidy', array( &$this, &$text ) );
1325 $text = $this->replaceTransparentTags( $text );
1326 $text = $this->mStripState
->unstripGeneral( $text );
1328 $text = Sanitizer
::normalizeCharReferences( $text );
1330 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
1331 $text = MWTidy
::tidy( $text );
1333 # attempt to sanitize at least some nesting problems
1334 # (bug #2702 and quite a few others)
1336 # ''Something [http://www.cool.com cool''] -->
1337 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1338 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1339 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1340 # fix up an anchor inside another anchor, only
1341 # at least for a single single nested link (bug 3695)
1342 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1343 '\\1\\2</a>\\3</a>\\1\\4</a>',
1344 # fix div inside inline elements- doBlockLevels won't wrap a line which
1345 # contains a div, so fix it up here; replace
1346 # div with escaped text
1347 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1348 '\\1\\3<div\\5>\\6</div>\\8\\9',
1349 # remove empty italic or bold tag pairs, some
1350 # introduced by rules above
1351 '/<([bi])><\/\\1>/' => '',
1354 $text = preg_replace(
1355 array_keys( $tidyregs ),
1356 array_values( $tidyregs ),
1361 Hooks
::run( 'ParserAfterTidy', array( &$this, &$text ) );
1368 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1369 * magic external links.
1374 * @param string $text
1378 public function doMagicLinks( $text ) {
1379 $prots = wfUrlProtocolsWithoutProtRel();
1380 $urlChar = self
::EXT_LINK_URL_CLASS
;
1381 $space = self
::SPACE_NOT_NL
; # non-newline space
1382 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1383 $spaces = "$space++"; # possessive match of 1 or more spaces
1384 $text = preg_replace_callback(
1386 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1387 (<.*?>) | # m[2]: Skip stuff inside
1388 # HTML elements' . "
1389 (\b(?i:$prots)($urlChar+)) | # m[3]: Free external links
1390 # m[4]: Post-protocol path
1391 \b(?:RFC|PMID) $spaces # m[5]: RFC or PMID, capture number
1393 \bISBN $spaces ( # m[6]: ISBN, capture number
1394 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1395 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1396 [0-9Xx] # check digit
1398 )!xu", array( &$this, 'magicLinkCallback' ), $text );
1403 * @throws MWException
1405 * @return HTML|string
1407 public function magicLinkCallback( $m ) {
1408 if ( isset( $m[1] ) && $m[1] !== '' ) {
1411 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1414 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1415 # Free external link
1416 return $this->makeFreeExternalLink( $m[0], strlen( $m[4] ) );
1417 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1419 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1422 $cssClass = 'mw-magiclink-rfc';
1424 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1426 $urlmsg = 'pubmedurl';
1427 $cssClass = 'mw-magiclink-pmid';
1430 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1431 substr( $m[0], 0, 20 ) . '"' );
1433 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1434 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass );
1435 } elseif ( isset( $m[6] ) && $m[6] !== '' ) {
1438 $space = self
::SPACE_NOT_NL
; # non-newline space
1439 $isbn = preg_replace( "/$space/", ' ', $isbn );
1440 $num = strtr( $isbn, array(
1445 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1446 return '<a href="' .
1447 htmlspecialchars( $titleObj->getLocalURL() ) .
1448 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1455 * Make a free external link, given a user-supplied URL
1457 * @param string $url
1458 * @param int $numPostProto
1459 * The number of characters after the protocol.
1460 * @return string HTML
1463 public function makeFreeExternalLink( $url, $numPostProto ) {
1467 # The characters '<' and '>' (which were escaped by
1468 # removeHTMLtags()) should not be included in
1469 # URLs, per RFC 2396.
1471 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1472 $trail = substr( $url, $m2[0][1] ) . $trail;
1473 $url = substr( $url, 0, $m2[0][1] );
1476 # Move trailing punctuation to $trail
1478 # If there is no left bracket, then consider right brackets fair game too
1479 if ( strpos( $url, '(' ) === false ) {
1483 $urlRev = strrev( $url );
1484 $numSepChars = strspn( $urlRev, $sep );
1485 # Don't break a trailing HTML entity by moving the ; into $trail
1486 # This is in hot code, so use substr_compare to avoid having to
1487 # create a new string object for the comparison
1488 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0 ) {
1489 # more optimization: instead of running preg_match with a $
1490 # anchor, which can be slow, do the match on the reversed
1491 # string starting at the desired offset.
1492 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1493 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1497 if ( $numSepChars ) {
1498 $trail = substr( $url, -$numSepChars ) . $trail;
1499 $url = substr( $url, 0, -$numSepChars );
1502 $url = Sanitizer
::cleanUrl( $url );
1504 # Verify that we still have a real URL after trail removal, and
1505 # not just lone protocol
1506 if ( strlen( $trail ) >= $numPostProto ) {
1507 return $url . $trail;
1510 # Is this an external image?
1511 $text = $this->maybeMakeExternalImage( $url );
1512 if ( $text === false ) {
1513 # Not an image, make a link
1514 $text = Linker
::makeExternalLink( $url,
1515 $this->getConverterLanguage()->markNoConversion( $url, true ),
1517 $this->getExternalLinkAttribs( $url ) );
1518 # Register it in the output object...
1519 # Replace unnecessary URL escape codes with their equivalent characters
1520 $pasteurized = self
::normalizeLinkUrl( $url );
1521 $this->mOutput
->addExternalLink( $pasteurized );
1523 return $text . $trail;
1527 * Parse headers and return html
1531 * @param string $text
1535 public function doHeadings( $text ) {
1536 for ( $i = 6; $i >= 1; --$i ) {
1537 $h = str_repeat( '=', $i );
1538 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1544 * Replace single quotes with HTML markup
1547 * @param string $text
1549 * @return string The altered text
1551 public function doAllQuotes( $text ) {
1553 $lines = StringUtils
::explode( "\n", $text );
1554 foreach ( $lines as $line ) {
1555 $outtext .= $this->doQuotes( $line ) . "\n";
1557 $outtext = substr( $outtext, 0, -1 );
1562 * Helper function for doAllQuotes()
1564 * @param string $text
1568 public function doQuotes( $text ) {
1569 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1570 $countarr = count( $arr );
1571 if ( $countarr == 1 ) {
1575 // First, do some preliminary work. This may shift some apostrophes from
1576 // being mark-up to being text. It also counts the number of occurrences
1577 // of bold and italics mark-ups.
1580 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1581 $thislen = strlen( $arr[$i] );
1582 // If there are ever four apostrophes, assume the first is supposed to
1583 // be text, and the remaining three constitute mark-up for bold text.
1584 // (bug 13227: ''''foo'''' turns into ' ''' foo ' ''')
1585 if ( $thislen == 4 ) {
1586 $arr[$i - 1] .= "'";
1589 } elseif ( $thislen > 5 ) {
1590 // If there are more than 5 apostrophes in a row, assume they're all
1591 // text except for the last 5.
1592 // (bug 13227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1593 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1597 // Count the number of occurrences of bold and italics mark-ups.
1598 if ( $thislen == 2 ) {
1600 } elseif ( $thislen == 3 ) {
1602 } elseif ( $thislen == 5 ) {
1608 // If there is an odd number of both bold and italics, it is likely
1609 // that one of the bold ones was meant to be an apostrophe followed
1610 // by italics. Which one we cannot know for certain, but it is more
1611 // likely to be one that has a single-letter word before it.
1612 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1613 $firstsingleletterword = -1;
1614 $firstmultiletterword = -1;
1616 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1617 if ( strlen( $arr[$i] ) == 3 ) {
1618 $x1 = substr( $arr[$i - 1], -1 );
1619 $x2 = substr( $arr[$i - 1], -2, 1 );
1620 if ( $x1 === ' ' ) {
1621 if ( $firstspace == -1 ) {
1624 } elseif ( $x2 === ' ' ) {
1625 if ( $firstsingleletterword == -1 ) {
1626 $firstsingleletterword = $i;
1627 // if $firstsingleletterword is set, we don't
1628 // look at the other options, so we can bail early.
1632 if ( $firstmultiletterword == -1 ) {
1633 $firstmultiletterword = $i;
1639 // If there is a single-letter word, use it!
1640 if ( $firstsingleletterword > -1 ) {
1641 $arr[$firstsingleletterword] = "''";
1642 $arr[$firstsingleletterword - 1] .= "'";
1643 } elseif ( $firstmultiletterword > -1 ) {
1644 // If not, but there's a multi-letter word, use that one.
1645 $arr[$firstmultiletterword] = "''";
1646 $arr[$firstmultiletterword - 1] .= "'";
1647 } elseif ( $firstspace > -1 ) {
1648 // ... otherwise use the first one that has neither.
1649 // (notice that it is possible for all three to be -1 if, for example,
1650 // there is only one pentuple-apostrophe in the line)
1651 $arr[$firstspace] = "''";
1652 $arr[$firstspace - 1] .= "'";
1656 // Now let's actually convert our apostrophic mush to HTML!
1661 foreach ( $arr as $r ) {
1662 if ( ( $i %
2 ) == 0 ) {
1663 if ( $state === 'both' ) {
1669 $thislen = strlen( $r );
1670 if ( $thislen == 2 ) {
1671 if ( $state === 'i' ) {
1674 } elseif ( $state === 'bi' ) {
1677 } elseif ( $state === 'ib' ) {
1678 $output .= '</b></i><b>';
1680 } elseif ( $state === 'both' ) {
1681 $output .= '<b><i>' . $buffer . '</i>';
1683 } else { // $state can be 'b' or ''
1687 } elseif ( $thislen == 3 ) {
1688 if ( $state === 'b' ) {
1691 } elseif ( $state === 'bi' ) {
1692 $output .= '</i></b><i>';
1694 } elseif ( $state === 'ib' ) {
1697 } elseif ( $state === 'both' ) {
1698 $output .= '<i><b>' . $buffer . '</b>';
1700 } else { // $state can be 'i' or ''
1704 } elseif ( $thislen == 5 ) {
1705 if ( $state === 'b' ) {
1706 $output .= '</b><i>';
1708 } elseif ( $state === 'i' ) {
1709 $output .= '</i><b>';
1711 } elseif ( $state === 'bi' ) {
1712 $output .= '</i></b>';
1714 } elseif ( $state === 'ib' ) {
1715 $output .= '</b></i>';
1717 } elseif ( $state === 'both' ) {
1718 $output .= '<i><b>' . $buffer . '</b></i>';
1720 } else { // ($state == '')
1728 // Now close all remaining tags. Notice that the order is important.
1729 if ( $state === 'b' ||
$state === 'ib' ) {
1732 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1735 if ( $state === 'bi' ) {
1738 // There might be lonely ''''', so make sure we have a buffer
1739 if ( $state === 'both' && $buffer ) {
1740 $output .= '<b><i>' . $buffer . '</i></b>';
1746 * Replace external links (REL)
1748 * Note: this is all very hackish and the order of execution matters a lot.
1749 * Make sure to run tests/parserTests.php if you change this code.
1753 * @param string $text
1755 * @throws MWException
1758 public function replaceExternalLinks( $text ) {
1760 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1761 if ( $bits === false ) {
1762 throw new MWException( "PCRE needs to be compiled with "
1763 . "--enable-unicode-properties in order for MediaWiki to function" );
1765 $s = array_shift( $bits );
1768 while ( $i < count( $bits ) ) {
1771 $text = $bits[$i++
];
1772 $trail = $bits[$i++
];
1774 # The characters '<' and '>' (which were escaped by
1775 # removeHTMLtags()) should not be included in
1776 # URLs, per RFC 2396.
1778 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1779 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1780 $url = substr( $url, 0, $m2[0][1] );
1783 # If the link text is an image URL, replace it with an <img> tag
1784 # This happened by accident in the original parser, but some people used it extensively
1785 $img = $this->maybeMakeExternalImage( $text );
1786 if ( $img !== false ) {
1792 # Set linktype for CSS - if URL==text, link is essentially free
1793 $linktype = ( $text === $url ) ?
'free' : 'text';
1795 # No link text, e.g. [http://domain.tld/some.link]
1796 if ( $text == '' ) {
1798 $langObj = $this->getTargetLanguage();
1799 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1800 $linktype = 'autonumber';
1802 # Have link text, e.g. [http://domain.tld/some.link text]s
1804 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1807 $text = $this->getConverterLanguage()->markNoConversion( $text );
1809 $url = Sanitizer
::cleanUrl( $url );
1811 # Use the encoded URL
1812 # This means that users can paste URLs directly into the text
1813 # Funny characters like ö aren't valid in URLs anyway
1814 # This was changed in August 2004
1815 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1816 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1818 # Register link in the output object.
1819 # Replace unnecessary URL escape codes with the referenced character
1820 # This prevents spammers from hiding links from the filters
1821 $pasteurized = self
::normalizeLinkUrl( $url );
1822 $this->mOutput
->addExternalLink( $pasteurized );
1829 * Get the rel attribute for a particular external link.
1832 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1833 * nofollow if appropriate
1834 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1835 * @return string|null Rel attribute for $url
1837 public static function getExternalLinkRel( $url = false, $title = null ) {
1838 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1839 $ns = $title ?
$title->getNamespace() : false;
1840 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1841 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1849 * Get an associative array of additional HTML attributes appropriate for a
1850 * particular external link. This currently may include rel => nofollow
1851 * (depending on configuration, namespace, and the URL's domain) and/or a
1852 * target attribute (depending on configuration).
1854 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1855 * nofollow if appropriate
1856 * @return array Associative array of HTML attributes
1858 public function getExternalLinkAttribs( $url = false ) {
1860 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1862 if ( $this->mOptions
->getExternalLinkTarget() ) {
1863 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1869 * Replace unusual escape codes in a URL with their equivalent characters
1871 * @deprecated since 1.24, use normalizeLinkUrl
1872 * @param string $url
1875 public static function replaceUnusualEscapes( $url ) {
1876 wfDeprecated( __METHOD__
, '1.24' );
1877 return self
::normalizeLinkUrl( $url );
1881 * Replace unusual escape codes in a URL with their equivalent characters
1883 * This generally follows the syntax defined in RFC 3986, with special
1884 * consideration for HTTP query strings.
1886 * @param string $url
1889 public static function normalizeLinkUrl( $url ) {
1890 # First, make sure unsafe characters are encoded
1891 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
1893 return rawurlencode( $m[0] );
1899 $end = strlen( $url );
1901 # Fragment part - 'fragment'
1902 $start = strpos( $url, '#' );
1903 if ( $start !== false && $start < $end ) {
1904 $ret = self
::normalizeUrlComponent(
1905 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
1909 # Query part - 'query' minus &=+;
1910 $start = strpos( $url, '?' );
1911 if ( $start !== false && $start < $end ) {
1912 $ret = self
::normalizeUrlComponent(
1913 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
1917 # Scheme and path part - 'pchar'
1918 # (we assume no userinfo or encoded colons in the host)
1919 $ret = self
::normalizeUrlComponent(
1920 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
1925 private static function normalizeUrlComponent( $component, $unsafe ) {
1926 $callback = function ( $matches ) use ( $unsafe ) {
1927 $char = urldecode( $matches[0] );
1928 $ord = ord( $char );
1929 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
1933 # Leave it escaped, but use uppercase for a-f
1934 return strtoupper( $matches[0] );
1937 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
1941 * make an image if it's allowed, either through the global
1942 * option, through the exception, or through the on-wiki whitelist
1944 * @param string $url
1948 private function maybeMakeExternalImage( $url ) {
1949 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1950 $imagesexception = !empty( $imagesfrom );
1952 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1953 if ( $imagesexception && is_array( $imagesfrom ) ) {
1954 $imagematch = false;
1955 foreach ( $imagesfrom as $match ) {
1956 if ( strpos( $url, $match ) === 0 ) {
1961 } elseif ( $imagesexception ) {
1962 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1964 $imagematch = false;
1967 if ( $this->mOptions
->getAllowExternalImages()
1968 ||
( $imagesexception && $imagematch )
1970 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1972 $text = Linker
::makeExternalImage( $url );
1975 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1976 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
1978 $whitelist = explode(
1980 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
1983 foreach ( $whitelist as $entry ) {
1984 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1985 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1988 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1989 # Image matches a whitelist entry
1990 $text = Linker
::makeExternalImage( $url );
1999 * Process [[ ]] wikilinks
2003 * @return string Processed text
2007 public function replaceInternalLinks( $s ) {
2008 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
2013 * Process [[ ]] wikilinks (RIL)
2015 * @throws MWException
2016 * @return LinkHolderArray
2020 public function replaceInternalLinks2( &$s ) {
2021 global $wgExtraInterlanguageLinkPrefixes;
2023 static $tc = false, $e1, $e1_img;
2024 # the % is needed to support urlencoded titles as well
2026 $tc = Title
::legalChars() . '#%';
2027 # Match a link having the form [[namespace:link|alternate]]trail
2028 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2029 # Match cases where there is no "]]", which might still be images
2030 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2033 $holders = new LinkHolderArray( $this );
2035 # split the entire text string on occurrences of [[
2036 $a = StringUtils
::explode( '[[', ' ' . $s );
2037 # get the first element (all text up to first [[), and remove the space we added
2040 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2041 $s = substr( $s, 1 );
2043 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2045 if ( $useLinkPrefixExtension ) {
2046 # Match the end of a line for a word that's not followed by whitespace,
2047 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2049 $charset = $wgContLang->linkPrefixCharset();
2050 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2053 if ( is_null( $this->mTitle
) ) {
2054 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
2056 $nottalk = !$this->mTitle
->isTalkPage();
2058 if ( $useLinkPrefixExtension ) {
2060 if ( preg_match( $e2, $s, $m ) ) {
2061 $first_prefix = $m[2];
2063 $first_prefix = false;
2069 $useSubpages = $this->areSubpagesAllowed();
2071 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
2072 # Loop for each link
2073 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2074 // @codingStandardsIgnoreStart
2076 # Check for excessive memory usage
2077 if ( $holders->isBig() ) {
2079 # Do the existence check, replace the link holders and clear the array
2080 $holders->replace( $s );
2084 if ( $useLinkPrefixExtension ) {
2085 if ( preg_match( $e2, $s, $m ) ) {
2092 if ( $first_prefix ) {
2093 $prefix = $first_prefix;
2094 $first_prefix = false;
2098 $might_be_img = false;
2100 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2102 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2103 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2104 # the real problem is with the $e1 regex
2107 # Still some problems for cases where the ] is meant to be outside punctuation,
2108 # and no image is in sight. See bug 2095.
2111 && substr( $m[3], 0, 1 ) === ']'
2112 && strpos( $text, '[' ) !== false
2114 $text .= ']'; # so that replaceExternalLinks($text) works later
2115 $m[3] = substr( $m[3], 1 );
2117 # fix up urlencoded title texts
2118 if ( strpos( $m[1], '%' ) !== false ) {
2119 # Should anchors '#' also be rejected?
2120 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) );
2123 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2124 # Invalid, but might be an image with a link in its caption
2125 $might_be_img = true;
2127 if ( strpos( $m[1], '%' ) !== false ) {
2128 $m[1] = rawurldecode( $m[1] );
2131 } else { # Invalid form; output directly
2132 $s .= $prefix . '[[' . $line;
2138 # Don't allow internal links to pages containing
2139 # PROTO: where PROTO is a valid URL protocol; these
2140 # should be external links.
2141 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2142 $s .= $prefix . '[[' . $line;
2146 # Make subpage if necessary
2147 if ( $useSubpages ) {
2148 $link = $this->maybeDoSubpageLink( $origLink, $text );
2153 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2155 # Strip off leading ':'
2156 $link = substr( $link, 1 );
2159 $unstrip = $this->mStripState
->unstripNoWiki( $link );
2160 $nt = is_string( $unstrip ) ? Title
::newFromText( $unstrip ) : null;
2161 if ( $nt === null ) {
2162 $s .= $prefix . '[[' . $line;
2166 $ns = $nt->getNamespace();
2167 $iw = $nt->getInterwiki();
2169 if ( $might_be_img ) { # if this is actually an invalid link
2170 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2173 # look at the next 'line' to see if we can close it there
2175 $next_line = $a->current();
2176 if ( $next_line === false ||
$next_line === null ) {
2179 $m = explode( ']]', $next_line, 3 );
2180 if ( count( $m ) == 3 ) {
2181 # the first ]] closes the inner link, the second the image
2183 $text .= "[[{$m[0]}]]{$m[1]}";
2186 } elseif ( count( $m ) == 2 ) {
2187 # if there's exactly one ]] that's fine, we'll keep looking
2188 $text .= "[[{$m[0]}]]{$m[1]}";
2190 # if $next_line is invalid too, we need look no further
2191 $text .= '[[' . $next_line;
2196 # we couldn't find the end of this imageLink, so output it raw
2197 # but don't ignore what might be perfectly normal links in the text we've examined
2198 $holders->merge( $this->replaceInternalLinks2( $text ) );
2199 $s .= "{$prefix}[[$link|$text";
2200 # note: no $trail, because without an end, there *is* no trail
2203 } else { # it's not an image, so output it raw
2204 $s .= "{$prefix}[[$link|$text";
2205 # note: no $trail, because without an end, there *is* no trail
2210 $wasblank = ( $text == '' );
2214 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
2215 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2216 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2217 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2218 $text = $this->doQuotes( $text );
2221 # Link not escaped by : , create the various objects
2222 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2225 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2226 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2227 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2230 # Bug 24502: filter duplicates
2231 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2232 $this->mLangLinkLanguages
[$iw] = true;
2233 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2236 $s = rtrim( $s . $prefix );
2237 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2241 if ( $ns == NS_FILE
) {
2242 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2244 # if no parameters were passed, $text
2245 # becomes something like "File:Foo.png",
2246 # which we don't want to pass on to the
2250 # recursively parse links inside the image caption
2251 # actually, this will parse them in any other parameters, too,
2252 # but it might be hard to fix that, and it doesn't matter ATM
2253 $text = $this->replaceExternalLinks( $text );
2254 $holders->merge( $this->replaceInternalLinks2( $text ) );
2256 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2257 $s .= $prefix . $this->armorLinks(
2258 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2260 $s .= $prefix . $trail;
2265 if ( $ns == NS_CATEGORY
) {
2266 $s = rtrim( $s . "\n" ); # bug 87
2269 $sortkey = $this->getDefaultSort();
2273 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2274 $sortkey = str_replace( "\n", '', $sortkey );
2275 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2276 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2279 * Strip the whitespace Category links produce, see bug 87
2281 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2287 # Self-link checking. For some languages, variants of the title are checked in
2288 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2289 # for linking to a different variant.
2290 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2291 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2295 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2296 # @todo FIXME: Should do batch file existence checks, see comment below
2297 if ( $ns == NS_MEDIA
) {
2298 # Give extensions a chance to select the file revision for us
2301 Hooks
::run( 'BeforeParserFetchFileAndTitle',
2302 array( $this, $nt, &$options, &$descQuery ) );
2303 # Fetch and register the file (file title may be different via hooks)
2304 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2305 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2306 $s .= $prefix . $this->armorLinks(
2307 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2311 # Some titles, such as valid special pages or files in foreign repos, should
2312 # be shown as bluelinks even though they're not included in the page table
2314 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2315 # batch file existence checks for NS_FILE and NS_MEDIA
2316 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2317 $this->mOutput
->addLink( $nt );
2318 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2320 # Links will be added to the output link list after checking
2321 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2328 * Render a forced-blue link inline; protect against double expansion of
2329 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2330 * Since this little disaster has to split off the trail text to avoid
2331 * breaking URLs in the following text without breaking trails on the
2332 * wiki links, it's been made into a horrible function.
2335 * @param string $text
2336 * @param array|string $query
2337 * @param string $trail
2338 * @param string $prefix
2339 * @return string HTML-wikitext mix oh yuck
2341 public function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2342 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2344 if ( is_string( $query ) ) {
2345 $query = wfCgiToArray( $query );
2347 if ( $text == '' ) {
2348 $text = htmlspecialchars( $nt->getPrefixedText() );
2351 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2353 return $this->armorLinks( $link ) . $trail;
2357 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2358 * going to go through further parsing steps before inline URL expansion.
2360 * Not needed quite as much as it used to be since free links are a bit
2361 * more sensible these days. But bracketed links are still an issue.
2363 * @param string $text More-or-less HTML
2364 * @return string Less-or-more HTML with NOPARSE bits
2366 public function armorLinks( $text ) {
2367 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2368 self
::MARKER_PREFIX
. "NOPARSE$1", $text );
2372 * Return true if subpage links should be expanded on this page.
2375 public function areSubpagesAllowed() {
2376 # Some namespaces don't allow subpages
2377 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2381 * Handle link to subpage if necessary
2383 * @param string $target The source of the link
2384 * @param string &$text The link text, modified as necessary
2385 * @return string The full name of the link
2388 public function maybeDoSubpageLink( $target, &$text ) {
2389 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2393 * Used by doBlockLevels()
2398 public function closeParagraph() {
2400 if ( $this->mLastSection
!= '' ) {
2401 $result = '</' . $this->mLastSection
. ">\n";
2403 $this->mInPre
= false;
2404 $this->mLastSection
= '';
2409 * getCommon() returns the length of the longest common substring
2410 * of both arguments, starting at the beginning of both.
2413 * @param string $st1
2414 * @param string $st2
2418 public function getCommon( $st1, $st2 ) {
2419 $fl = strlen( $st1 );
2420 $shorter = strlen( $st2 );
2421 if ( $fl < $shorter ) {
2425 for ( $i = 0; $i < $shorter; ++
$i ) {
2426 if ( $st1[$i] != $st2[$i] ) {
2434 * These next three functions open, continue, and close the list
2435 * element appropriate to the prefix character passed into them.
2438 * @param string $char
2442 public function openList( $char ) {
2443 $result = $this->closeParagraph();
2445 if ( '*' === $char ) {
2446 $result .= "<ul><li>";
2447 } elseif ( '#' === $char ) {
2448 $result .= "<ol><li>";
2449 } elseif ( ':' === $char ) {
2450 $result .= "<dl><dd>";
2451 } elseif ( ';' === $char ) {
2452 $result .= "<dl><dt>";
2453 $this->mDTopen
= true;
2455 $result = '<!-- ERR 1 -->';
2463 * @param string $char
2468 public function nextItem( $char ) {
2469 if ( '*' === $char ||
'#' === $char ) {
2470 return "</li>\n<li>";
2471 } elseif ( ':' === $char ||
';' === $char ) {
2473 if ( $this->mDTopen
) {
2476 if ( ';' === $char ) {
2477 $this->mDTopen
= true;
2478 return $close . '<dt>';
2480 $this->mDTopen
= false;
2481 return $close . '<dd>';
2484 return '<!-- ERR 2 -->';
2489 * @param string $char
2494 public function closeList( $char ) {
2495 if ( '*' === $char ) {
2496 $text = "</li></ul>";
2497 } elseif ( '#' === $char ) {
2498 $text = "</li></ol>";
2499 } elseif ( ':' === $char ) {
2500 if ( $this->mDTopen
) {
2501 $this->mDTopen
= false;
2502 $text = "</dt></dl>";
2504 $text = "</dd></dl>";
2507 return '<!-- ERR 3 -->';
2514 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2516 * @param string $text
2517 * @param bool $linestart Whether or not this is at the start of a line.
2519 * @return string The lists rendered as HTML
2521 public function doBlockLevels( $text, $linestart ) {
2523 # Parsing through the text line by line. The main thing
2524 # happening here is handling of block-level elements p, pre,
2525 # and making lists from lines starting with * # : etc.
2527 $textLines = StringUtils
::explode( "\n", $text );
2529 $lastPrefix = $output = '';
2530 $this->mDTopen
= $inBlockElem = false;
2532 $paragraphStack = false;
2533 $inBlockquote = false;
2535 foreach ( $textLines as $oLine ) {
2537 if ( !$linestart ) {
2547 $lastPrefixLength = strlen( $lastPrefix );
2548 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2549 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2550 # If not in a <pre> element, scan for and figure out what prefixes are there.
2551 if ( !$this->mInPre
) {
2552 # Multiple prefixes may abut each other for nested lists.
2553 $prefixLength = strspn( $oLine, '*#:;' );
2554 $prefix = substr( $oLine, 0, $prefixLength );
2557 # ; and : are both from definition-lists, so they're equivalent
2558 # for the purposes of determining whether or not we need to open/close
2560 $prefix2 = str_replace( ';', ':', $prefix );
2561 $t = substr( $oLine, $prefixLength );
2562 $this->mInPre
= (bool)$preOpenMatch;
2564 # Don't interpret any other prefixes in preformatted text
2566 $prefix = $prefix2 = '';
2571 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2572 # Same as the last item, so no need to deal with nesting or opening stuff
2573 $output .= $this->nextItem( substr( $prefix, -1 ) );
2574 $paragraphStack = false;
2576 if ( substr( $prefix, -1 ) === ';' ) {
2577 # The one nasty exception: definition lists work like this:
2578 # ; title : definition text
2579 # So we check for : in the remainder text to split up the
2580 # title and definition, without b0rking links.
2582 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2584 $output .= $term . $this->nextItem( ':' );
2587 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2588 # We need to open or close prefixes, or both.
2590 # Either open or close a level...
2591 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2592 $paragraphStack = false;
2594 # Close all the prefixes which aren't shared.
2595 while ( $commonPrefixLength < $lastPrefixLength ) {
2596 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2597 --$lastPrefixLength;
2600 # Continue the current prefix if appropriate.
2601 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2602 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2605 # Open prefixes where appropriate.
2606 if ( $lastPrefix && $prefixLength > $commonPrefixLength ) {
2609 while ( $prefixLength > $commonPrefixLength ) {
2610 $char = substr( $prefix, $commonPrefixLength, 1 );
2611 $output .= $this->openList( $char );
2613 if ( ';' === $char ) {
2614 # @todo FIXME: This is dupe of code above
2615 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2617 $output .= $term . $this->nextItem( ':' );
2620 ++
$commonPrefixLength;
2622 if ( !$prefixLength && $lastPrefix ) {
2625 $lastPrefix = $prefix2;
2628 # If we have no prefixes, go to paragraph mode.
2629 if ( 0 == $prefixLength ) {
2630 # No prefix (not in list)--go to paragraph mode
2631 # XXX: use a stack for nestable elements like span, table and div
2632 $openmatch = preg_match(
2633 '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|'
2634 . '<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS',
2637 $closematch = preg_match(
2638 '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'
2639 . '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|<\\/mw:|'
2640 . self
::MARKER_PREFIX
2641 . '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS',
2645 if ( $openmatch ||
$closematch ) {
2646 $paragraphStack = false;
2647 # @todo bug 5718: paragraph closed
2648 $output .= $this->closeParagraph();
2649 if ( $preOpenMatch && !$preCloseMatch ) {
2650 $this->mInPre
= true;
2653 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t, $bqMatch, PREG_OFFSET_CAPTURE
, $bqOffset ) ) {
2654 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
2655 $bqOffset = $bqMatch[0][1] +
strlen( $bqMatch[0][0] );
2657 $inBlockElem = !$closematch;
2658 } elseif ( !$inBlockElem && !$this->mInPre
) {
2659 if ( ' ' == substr( $t, 0, 1 )
2660 && ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' )
2664 if ( $this->mLastSection
!== 'pre' ) {
2665 $paragraphStack = false;
2666 $output .= $this->closeParagraph() . '<pre>';
2667 $this->mLastSection
= 'pre';
2669 $t = substr( $t, 1 );
2672 if ( trim( $t ) === '' ) {
2673 if ( $paragraphStack ) {
2674 $output .= $paragraphStack . '<br />';
2675 $paragraphStack = false;
2676 $this->mLastSection
= 'p';
2678 if ( $this->mLastSection
!== 'p' ) {
2679 $output .= $this->closeParagraph();
2680 $this->mLastSection
= '';
2681 $paragraphStack = '<p>';
2683 $paragraphStack = '</p><p>';
2687 if ( $paragraphStack ) {
2688 $output .= $paragraphStack;
2689 $paragraphStack = false;
2690 $this->mLastSection
= 'p';
2691 } elseif ( $this->mLastSection
!== 'p' ) {
2692 $output .= $this->closeParagraph() . '<p>';
2693 $this->mLastSection
= 'p';
2699 # somewhere above we forget to get out of pre block (bug 785)
2700 if ( $preCloseMatch && $this->mInPre
) {
2701 $this->mInPre
= false;
2703 if ( $paragraphStack === false ) {
2705 if ( $prefixLength === 0 ) {
2710 while ( $prefixLength ) {
2711 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2713 if ( !$prefixLength ) {
2717 if ( $this->mLastSection
!= '' ) {
2718 $output .= '</' . $this->mLastSection
. '>';
2719 $this->mLastSection
= '';
2726 * Split up a string on ':', ignoring any occurrences inside tags
2727 * to prevent illegal overlapping.
2729 * @param string $str The string to split
2730 * @param string &$before Set to everything before the ':'
2731 * @param string &$after Set to everything after the ':'
2732 * @throws MWException
2733 * @return string The position of the ':', or false if none found
2735 public function findColonNoLinks( $str, &$before, &$after ) {
2737 $pos = strpos( $str, ':' );
2738 if ( $pos === false ) {
2743 $lt = strpos( $str, '<' );
2744 if ( $lt === false ||
$lt > $pos ) {
2745 # Easy; no tag nesting to worry about
2746 $before = substr( $str, 0, $pos );
2747 $after = substr( $str, $pos +
1 );
2751 # Ugly state machine to walk through avoiding tags.
2752 $state = self
::COLON_STATE_TEXT
;
2754 $len = strlen( $str );
2755 for ( $i = 0; $i < $len; $i++
) {
2759 # (Using the number is a performance hack for common cases)
2760 case 0: # self::COLON_STATE_TEXT:
2763 # Could be either a <start> tag or an </end> tag
2764 $state = self
::COLON_STATE_TAGSTART
;
2767 if ( $stack == 0 ) {
2769 $before = substr( $str, 0, $i );
2770 $after = substr( $str, $i +
1 );
2773 # Embedded in a tag; don't break it.
2776 # Skip ahead looking for something interesting
2777 $colon = strpos( $str, ':', $i );
2778 if ( $colon === false ) {
2779 # Nothing else interesting
2782 $lt = strpos( $str, '<', $i );
2783 if ( $stack === 0 ) {
2784 if ( $lt === false ||
$colon < $lt ) {
2786 $before = substr( $str, 0, $colon );
2787 $after = substr( $str, $colon +
1 );
2791 if ( $lt === false ) {
2792 # Nothing else interesting to find; abort!
2793 # We're nested, but there's no close tags left. Abort!
2796 # Skip ahead to next tag start
2798 $state = self
::COLON_STATE_TAGSTART
;
2801 case 1: # self::COLON_STATE_TAG:
2806 $state = self
::COLON_STATE_TEXT
;
2809 # Slash may be followed by >?
2810 $state = self
::COLON_STATE_TAGSLASH
;
2816 case 2: # self::COLON_STATE_TAGSTART:
2819 $state = self
::COLON_STATE_CLOSETAG
;
2822 $state = self
::COLON_STATE_COMMENT
;
2825 # Illegal early close? This shouldn't happen D:
2826 $state = self
::COLON_STATE_TEXT
;
2829 $state = self
::COLON_STATE_TAG
;
2832 case 3: # self::COLON_STATE_CLOSETAG:
2837 wfDebug( __METHOD__
. ": Invalid input; too many close tags\n" );
2840 $state = self
::COLON_STATE_TEXT
;
2843 case self
::COLON_STATE_TAGSLASH
:
2845 # Yes, a self-closed tag <blah/>
2846 $state = self
::COLON_STATE_TEXT
;
2848 # Probably we're jumping the gun, and this is an attribute
2849 $state = self
::COLON_STATE_TAG
;
2852 case 5: # self::COLON_STATE_COMMENT:
2854 $state = self
::COLON_STATE_COMMENTDASH
;
2857 case self
::COLON_STATE_COMMENTDASH
:
2859 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2861 $state = self
::COLON_STATE_COMMENT
;
2864 case self
::COLON_STATE_COMMENTDASHDASH
:
2866 $state = self
::COLON_STATE_TEXT
;
2868 $state = self
::COLON_STATE_COMMENT
;
2872 throw new MWException( "State machine error in " . __METHOD__
);
2876 wfDebug( __METHOD__
. ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2883 * Return value of a magic variable (like PAGENAME)
2888 * @param bool|PPFrame $frame
2890 * @throws MWException
2893 public function getVariableValue( $index, $frame = false ) {
2894 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2895 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2897 if ( is_null( $this->mTitle
) ) {
2898 // If no title set, bad things are going to happen
2899 // later. Title should always be set since this
2900 // should only be called in the middle of a parse
2901 // operation (but the unit-tests do funky stuff)
2902 throw new MWException( __METHOD__
. ' Should only be '
2903 . ' called while parsing (no title set)' );
2907 * Some of these require message or data lookups and can be
2908 * expensive to check many times.
2910 if ( Hooks
::run( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2911 if ( isset( $this->mVarCache
[$index] ) ) {
2912 return $this->mVarCache
[$index];
2916 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2917 Hooks
::run( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2919 $pageLang = $this->getFunctionLang();
2925 case 'currentmonth':
2926 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ) );
2928 case 'currentmonth1':
2929 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2931 case 'currentmonthname':
2932 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2934 case 'currentmonthnamegen':
2935 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2937 case 'currentmonthabbrev':
2938 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2941 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ) );
2944 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ) );
2947 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ) );
2950 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2952 case 'localmonthname':
2953 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2955 case 'localmonthnamegen':
2956 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2958 case 'localmonthabbrev':
2959 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2962 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ) );
2965 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ) );
2968 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2971 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2973 case 'fullpagename':
2974 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2976 case 'fullpagenamee':
2977 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2980 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2982 case 'subpagenamee':
2983 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2985 case 'rootpagename':
2986 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2988 case 'rootpagenamee':
2989 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
2992 $this->mTitle
->getRootText()
2995 case 'basepagename':
2996 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2998 case 'basepagenamee':
2999 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
3002 $this->mTitle
->getBaseText()
3005 case 'talkpagename':
3006 if ( $this->mTitle
->canTalk() ) {
3007 $talkPage = $this->mTitle
->getTalkPage();
3008 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
3013 case 'talkpagenamee':
3014 if ( $this->mTitle
->canTalk() ) {
3015 $talkPage = $this->mTitle
->getTalkPage();
3016 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
3021 case 'subjectpagename':
3022 $subjPage = $this->mTitle
->getSubjectPage();
3023 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
3025 case 'subjectpagenamee':
3026 $subjPage = $this->mTitle
->getSubjectPage();
3027 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
3029 case 'pageid': // requested in bug 23427
3030 $pageid = $this->getTitle()->getArticleID();
3031 if ( $pageid == 0 ) {
3032 # 0 means the page doesn't exist in the database,
3033 # which means the user is previewing a new page.
3034 # The vary-revision flag must be set, because the magic word
3035 # will have a different value once the page is saved.
3036 $this->mOutput
->setFlag( 'vary-revision' );
3037 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
3039 $value = $pageid ?
$pageid : null;
3042 # Let the edit saving system know we should parse the page
3043 # *after* a revision ID has been assigned.
3044 $this->mOutput
->setFlag( 'vary-revision' );
3045 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
3046 $value = $this->mRevisionId
;
3049 # Let the edit saving system know we should parse the page
3050 # *after* a revision ID has been assigned. This is for null edits.
3051 $this->mOutput
->setFlag( 'vary-revision' );
3052 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
3053 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
3055 case 'revisionday2':
3056 # Let the edit saving system know we should parse the page
3057 # *after* a revision ID has been assigned. This is for null edits.
3058 $this->mOutput
->setFlag( 'vary-revision' );
3059 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
3060 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
3062 case 'revisionmonth':
3063 # Let the edit saving system know we should parse the page
3064 # *after* a revision ID has been assigned. This is for null edits.
3065 $this->mOutput
->setFlag( 'vary-revision' );
3066 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
3067 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
3069 case 'revisionmonth1':
3070 # Let the edit saving system know we should parse the page
3071 # *after* a revision ID has been assigned. This is for null edits.
3072 $this->mOutput
->setFlag( 'vary-revision' );
3073 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
3074 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
3076 case 'revisionyear':
3077 # Let the edit saving system know we should parse the page
3078 # *after* a revision ID has been assigned. This is for null edits.
3079 $this->mOutput
->setFlag( 'vary-revision' );
3080 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
3081 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
3083 case 'revisiontimestamp':
3084 # Let the edit saving system know we should parse the page
3085 # *after* a revision ID has been assigned. This is for null edits.
3086 $this->mOutput
->setFlag( 'vary-revision' );
3087 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
3088 $value = $this->getRevisionTimestamp();
3090 case 'revisionuser':
3091 # Let the edit saving system know we should parse the page
3092 # *after* a revision ID has been assigned. This is for null edits.
3093 $this->mOutput
->setFlag( 'vary-revision' );
3094 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
3095 $value = $this->getRevisionUser();
3097 case 'revisionsize':
3098 # Let the edit saving system know we should parse the page
3099 # *after* a revision ID has been assigned. This is for null edits.
3100 $this->mOutput
->setFlag( 'vary-revision' );
3101 wfDebug( __METHOD__
. ": {{REVISIONSIZE}} used, setting vary-revision...\n" );
3102 $value = $this->getRevisionSize();
3105 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3108 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3110 case 'namespacenumber':
3111 $value = $this->mTitle
->getNamespace();
3114 $value = $this->mTitle
->canTalk()
3115 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
3119 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
3121 case 'subjectspace':
3122 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
3124 case 'subjectspacee':
3125 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
3127 case 'currentdayname':
3128 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
3131 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
3134 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
3137 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
3140 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3141 # int to remove the padding
3142 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
3145 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
3147 case 'localdayname':
3148 $value = $pageLang->getWeekdayName(
3149 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
3153 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
3156 $value = $pageLang->time(
3157 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
3163 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
3166 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3167 # int to remove the padding
3168 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
3171 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
3173 case 'numberofarticles':
3174 $value = $pageLang->formatNum( SiteStats
::articles() );
3176 case 'numberoffiles':
3177 $value = $pageLang->formatNum( SiteStats
::images() );
3179 case 'numberofusers':
3180 $value = $pageLang->formatNum( SiteStats
::users() );
3182 case 'numberofactiveusers':
3183 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
3185 case 'numberofpages':
3186 $value = $pageLang->formatNum( SiteStats
::pages() );
3188 case 'numberofadmins':
3189 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
3191 case 'numberofedits':
3192 $value = $pageLang->formatNum( SiteStats
::edits() );
3194 case 'currenttimestamp':
3195 $value = wfTimestamp( TS_MW
, $ts );
3197 case 'localtimestamp':
3198 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
3200 case 'currentversion':
3201 $value = SpecialVersion
::getVersion();
3204 return $wgArticlePath;
3210 return $wgServerName;
3212 return $wgScriptPath;
3214 return $wgStylePath;
3215 case 'directionmark':
3216 return $pageLang->getDirMark();
3217 case 'contentlanguage':
3218 global $wgLanguageCode;
3219 return $wgLanguageCode;
3220 case 'cascadingsources':
3221 $value = CoreParserFunctions
::cascadingsources( $this );
3226 'ParserGetVariableValueSwitch',
3227 array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame )
3234 $this->mVarCache
[$index] = $value;
3241 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3245 public function initialiseVariables() {
3246 $variableIDs = MagicWord
::getVariableIDs();
3247 $substIDs = MagicWord
::getSubstIDs();
3249 $this->mVariables
= new MagicWordArray( $variableIDs );
3250 $this->mSubstWords
= new MagicWordArray( $substIDs );
3254 * Preprocess some wikitext and return the document tree.
3255 * This is the ghost of replace_variables().
3257 * @param string $text The text to parse
3258 * @param int $flags Bitwise combination of:
3259 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
3260 * included. Default is to assume a direct page view.
3262 * The generated DOM tree must depend only on the input text and the flags.
3263 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3265 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3266 * change in the DOM tree for a given text, must be passed through the section identifier
3267 * in the section edit link and thus back to extractSections().
3269 * The output of this function is currently only cached in process memory, but a persistent
3270 * cache may be implemented at a later date which takes further advantage of these strict
3271 * dependency requirements.
3275 public function preprocessToDom( $text, $flags = 0 ) {
3276 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3281 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3287 public static function splitWhitespace( $s ) {
3288 $ltrimmed = ltrim( $s );
3289 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3290 $trimmed = rtrim( $ltrimmed );
3291 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3293 $w2 = substr( $ltrimmed, -$diff );
3297 return array( $w1, $trimmed, $w2 );
3301 * Replace magic variables, templates, and template arguments
3302 * with the appropriate text. Templates are substituted recursively,
3303 * taking care to avoid infinite loops.
3305 * Note that the substitution depends on value of $mOutputType:
3306 * self::OT_WIKI: only {{subst:}} templates
3307 * self::OT_PREPROCESS: templates but not extension tags
3308 * self::OT_HTML: all templates and extension tags
3310 * @param string $text The text to transform
3311 * @param bool|PPFrame $frame Object describing the arguments passed to the
3312 * template. Arguments may also be provided as an associative array, as
3313 * was the usual case before MW1.12. Providing arguments this way may be
3314 * useful for extensions wishing to perform variable replacement
3316 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3317 * double-brace expansion.
3320 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3321 # Is there any text? Also, Prevent too big inclusions!
3322 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3326 if ( $frame === false ) {
3327 $frame = $this->getPreprocessor()->newFrame();
3328 } elseif ( !( $frame instanceof PPFrame
) ) {
3329 wfDebug( __METHOD__
. " called using plain parameters instead of "
3330 . "a PPFrame instance. Creating custom frame.\n" );
3331 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3334 $dom = $this->preprocessToDom( $text );
3335 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3336 $text = $frame->expand( $dom, $flags );
3342 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3344 * @param array $args
3348 public static function createAssocArgs( $args ) {
3349 $assocArgs = array();
3351 foreach ( $args as $arg ) {
3352 $eqpos = strpos( $arg, '=' );
3353 if ( $eqpos === false ) {
3354 $assocArgs[$index++
] = $arg;
3356 $name = trim( substr( $arg, 0, $eqpos ) );
3357 $value = trim( substr( $arg, $eqpos +
1 ) );
3358 if ( $value === false ) {
3361 if ( $name !== false ) {
3362 $assocArgs[$name] = $value;
3371 * Warn the user when a parser limitation is reached
3372 * Will warn at most once the user per limitation type
3374 * @param string $limitationType Should be one of:
3375 * 'expensive-parserfunction' (corresponding messages:
3376 * 'expensive-parserfunction-warning',
3377 * 'expensive-parserfunction-category')
3378 * 'post-expand-template-argument' (corresponding messages:
3379 * 'post-expand-template-argument-warning',
3380 * 'post-expand-template-argument-category')
3381 * 'post-expand-template-inclusion' (corresponding messages:
3382 * 'post-expand-template-inclusion-warning',
3383 * 'post-expand-template-inclusion-category')
3384 * 'node-count-exceeded' (corresponding messages:
3385 * 'node-count-exceeded-warning',
3386 * 'node-count-exceeded-category')
3387 * 'expansion-depth-exceeded' (corresponding messages:
3388 * 'expansion-depth-exceeded-warning',
3389 * 'expansion-depth-exceeded-category')
3390 * @param string|int|null $current Current value
3391 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3392 * exceeded, provide the values (optional)
3394 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3395 # does no harm if $current and $max are present but are unnecessary for the message
3396 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3397 ->inLanguage( $this->mOptions
->getUserLangObj() )->text();
3398 $this->mOutput
->addWarning( $warning );
3399 $this->addTrackingCategory( "$limitationType-category" );
3403 * Return the text of a template, after recursively
3404 * replacing any variables or templates within the template.
3406 * @param array $piece The parts of the template
3407 * $piece['title']: the title, i.e. the part before the |
3408 * $piece['parts']: the parameter array
3409 * $piece['lineStart']: whether the brace was at the start of a line
3410 * @param PPFrame $frame The current frame, contains template arguments
3412 * @return string The text of the template
3414 public function braceSubstitution( $piece, $frame ) {
3418 // $text has been filled
3420 // wiki markup in $text should be escaped
3422 // $text is HTML, armour it against wikitext transformation
3424 // Force interwiki transclusion to be done in raw mode not rendered
3425 $forceRawInterwiki = false;
3426 // $text is a DOM node needing expansion in a child frame
3427 $isChildObj = false;
3428 // $text is a DOM node needing expansion in the current frame
3429 $isLocalObj = false;
3431 # Title object, where $text came from
3434 # $part1 is the bit before the first |, and must contain only title characters.
3435 # Various prefixes will be stripped from it later.
3436 $titleWithSpaces = $frame->expand( $piece['title'] );
3437 $part1 = trim( $titleWithSpaces );
3440 # Original title text preserved for various purposes
3441 $originalTitle = $part1;
3443 # $args is a list of argument nodes, starting from index 0, not including $part1
3444 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3445 # below won't work b/c this $args isn't an object
3446 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3448 $profileSection = null; // profile templates
3452 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3454 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3455 # Decide whether to expand template or keep wikitext as-is.
3456 if ( $this->ot
['wiki'] ) {
3457 if ( $substMatch === false ) {
3458 $literal = true; # literal when in PST with no prefix
3460 $literal = false; # expand when in PST with subst: or safesubst:
3463 if ( $substMatch == 'subst' ) {
3464 $literal = true; # literal when not in PST with plain subst:
3466 $literal = false; # expand when not in PST with safesubst: or no prefix
3470 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3477 if ( !$found && $args->getLength() == 0 ) {
3478 $id = $this->mVariables
->matchStartToEnd( $part1 );
3479 if ( $id !== false ) {
3480 $text = $this->getVariableValue( $id, $frame );
3481 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3482 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3488 # MSG, MSGNW and RAW
3491 $mwMsgnw = MagicWord
::get( 'msgnw' );
3492 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3495 # Remove obsolete MSG:
3496 $mwMsg = MagicWord
::get( 'msg' );
3497 $mwMsg->matchStartAndRemove( $part1 );
3501 $mwRaw = MagicWord
::get( 'raw' );
3502 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3503 $forceRawInterwiki = true;
3509 $colonPos = strpos( $part1, ':' );
3510 if ( $colonPos !== false ) {
3511 $func = substr( $part1, 0, $colonPos );
3512 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3513 for ( $i = 0; $i < $args->getLength(); $i++
) {
3514 $funcArgs[] = $args->item( $i );
3517 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3518 } catch ( Exception
$ex ) {
3522 # The interface for parser functions allows for extracting
3523 # flags into the local scope. Extract any forwarded flags
3529 # Finish mangling title and then check for loops.
3530 # Set $title to a Title object and $titleText to the PDBK
3533 # Split the title into page and subpage
3535 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3536 if ( $part1 !== $relative ) {
3538 $ns = $this->mTitle
->getNamespace();
3540 $title = Title
::newFromText( $part1, $ns );
3542 $titleText = $title->getPrefixedText();
3543 # Check for language variants if the template is not found
3544 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3545 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3547 # Do recursion depth check
3548 $limit = $this->mOptions
->getMaxTemplateDepth();
3549 if ( $frame->depth
>= $limit ) {
3551 $text = '<span class="error">'
3552 . wfMessage( 'parser-template-recursion-depth-warning' )
3553 ->numParams( $limit )->inContentLanguage()->text()
3559 # Load from database
3560 if ( !$found && $title ) {
3561 $profileSection = $this->mProfiler
->scopedProfileIn( $title->getPrefixedDBkey() );
3562 if ( !$title->isExternal() ) {
3563 if ( $title->isSpecialPage()
3564 && $this->mOptions
->getAllowSpecialInclusion()
3565 && $this->ot
['html']
3567 // Pass the template arguments as URL parameters.
3568 // "uselang" will have no effect since the Language object
3569 // is forced to the one defined in ParserOptions.
3570 $pageArgs = array();
3571 $argsLength = $args->getLength();
3572 for ( $i = 0; $i < $argsLength; $i++
) {
3573 $bits = $args->item( $i )->splitArg();
3574 if ( strval( $bits['index'] ) === '' ) {
3575 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3576 $value = trim( $frame->expand( $bits['value'] ) );
3577 $pageArgs[$name] = $value;
3581 // Create a new context to execute the special page
3582 $context = new RequestContext
;
3583 $context->setTitle( $title );
3584 $context->setRequest( new FauxRequest( $pageArgs ) );
3585 $context->setUser( $this->getUser() );
3586 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3587 $ret = SpecialPageFactory
::capturePath( $title, $context );
3589 $text = $context->getOutput()->getHTML();
3590 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3593 $this->disableCache();
3595 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3596 $found = false; # access denied
3597 wfDebug( __METHOD__
. ": template inclusion denied for " .
3598 $title->getPrefixedDBkey() . "\n" );
3600 list( $text, $title ) = $this->getTemplateDom( $title );
3601 if ( $text !== false ) {
3607 # If the title is valid but undisplayable, make a link to it
3608 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3609 $text = "[[:$titleText]]";
3612 } elseif ( $title->isTrans() ) {
3613 # Interwiki transclusion
3614 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3615 $text = $this->interwikiTransclude( $title, 'render' );
3618 $text = $this->interwikiTransclude( $title, 'raw' );
3619 # Preprocess it like a template
3620 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3626 # Do infinite loop check
3627 # This has to be done after redirect resolution to avoid infinite loops via redirects
3628 if ( !$frame->loopCheck( $title ) ) {
3630 $text = '<span class="error">'
3631 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3633 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3637 # If we haven't found text to substitute by now, we're done
3638 # Recover the source wikitext and return it
3640 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3641 if ( $profileSection ) {
3642 $this->mProfiler
->scopedProfileOut( $profileSection );
3644 return array( 'object' => $text );
3647 # Expand DOM-style return values in a child frame
3648 if ( $isChildObj ) {
3649 # Clean up argument array
3650 $newFrame = $frame->newChild( $args, $title );
3653 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3654 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3655 # Expansion is eligible for the empty-frame cache
3656 $text = $newFrame->cachedExpand( $titleText, $text );
3658 # Uncached expansion
3659 $text = $newFrame->expand( $text );
3662 if ( $isLocalObj && $nowiki ) {
3663 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3664 $isLocalObj = false;
3667 if ( $profileSection ) {
3668 $this->mProfiler
->scopedProfileOut( $profileSection );
3671 # Replace raw HTML by a placeholder
3673 $text = $this->insertStripItem( $text );
3674 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3675 # Escape nowiki-style return values
3676 $text = wfEscapeWikiText( $text );
3677 } elseif ( is_string( $text )
3678 && !$piece['lineStart']
3679 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3681 # Bug 529: if the template begins with a table or block-level
3682 # element, it should be treated as beginning a new line.
3683 # This behavior is somewhat controversial.
3684 $text = "\n" . $text;
3687 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3688 # Error, oversize inclusion
3689 if ( $titleText !== false ) {
3690 # Make a working, properly escaped link if possible (bug 23588)
3691 $text = "[[:$titleText]]";
3693 # This will probably not be a working link, but at least it may
3694 # provide some hint of where the problem is
3695 preg_replace( '/^:/', '', $originalTitle );
3696 $text = "[[:$originalTitle]]";
3698 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3699 . 'post-expand include size too large -->' );
3700 $this->limitationWarn( 'post-expand-template-inclusion' );
3703 if ( $isLocalObj ) {
3704 $ret = array( 'object' => $text );
3706 $ret = array( 'text' => $text );
3713 * Call a parser function and return an array with text and flags.
3715 * The returned array will always contain a boolean 'found', indicating
3716 * whether the parser function was found or not. It may also contain the
3718 * text: string|object, resulting wikitext or PP DOM object
3719 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3720 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3721 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3722 * nowiki: bool, wiki markup in $text should be escaped
3725 * @param PPFrame $frame The current frame, contains template arguments
3726 * @param string $function Function name
3727 * @param array $args Arguments to the function
3728 * @throws MWException
3731 public function callParserFunction( $frame, $function, array $args = array() ) {
3735 # Case sensitive functions
3736 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3737 $function = $this->mFunctionSynonyms
[1][$function];
3739 # Case insensitive functions
3740 $function = $wgContLang->lc( $function );
3741 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3742 $function = $this->mFunctionSynonyms
[0][$function];
3744 return array( 'found' => false );
3748 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3750 # Workaround for PHP bug 35229 and similar
3751 if ( !is_callable( $callback ) ) {
3752 throw new MWException( "Tag hook for $function is not callable\n" );
3755 $allArgs = array( &$this );
3756 if ( $flags & self
::SFH_OBJECT_ARGS
) {
3757 # Convert arguments to PPNodes and collect for appending to $allArgs
3758 $funcArgs = array();
3759 foreach ( $args as $k => $v ) {
3760 if ( $v instanceof PPNode ||
$k === 0 ) {
3763 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( array( $k => $v ) )->item( 0 );
3767 # Add a frame parameter, and pass the arguments as an array
3768 $allArgs[] = $frame;
3769 $allArgs[] = $funcArgs;
3771 # Convert arguments to plain text and append to $allArgs
3772 foreach ( $args as $k => $v ) {
3773 if ( $v instanceof PPNode
) {
3774 $allArgs[] = trim( $frame->expand( $v ) );
3775 } elseif ( is_int( $k ) && $k >= 0 ) {
3776 $allArgs[] = trim( $v );
3778 $allArgs[] = trim( "$k=$v" );
3783 $result = call_user_func_array( $callback, $allArgs );
3785 # The interface for function hooks allows them to return a wikitext
3786 # string or an array containing the string and any flags. This mungs
3787 # things around to match what this method should return.
3788 if ( !is_array( $result ) ) {
3794 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3795 $result['text'] = $result[0];
3797 unset( $result[0] );
3804 $preprocessFlags = 0;
3805 if ( isset( $result['noparse'] ) ) {
3806 $noparse = $result['noparse'];
3808 if ( isset( $result['preprocessFlags'] ) ) {
3809 $preprocessFlags = $result['preprocessFlags'];
3813 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3814 $result['isChildObj'] = true;
3821 * Get the semi-parsed DOM representation of a template with a given title,
3822 * and its redirect destination title. Cached.
3824 * @param Title $title
3828 public function getTemplateDom( $title ) {
3829 $cacheTitle = $title;
3830 $titleText = $title->getPrefixedDBkey();
3832 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3833 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3834 $title = Title
::makeTitle( $ns, $dbk );
3835 $titleText = $title->getPrefixedDBkey();
3837 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3838 return array( $this->mTplDomCache
[$titleText], $title );
3841 # Cache miss, go to the database
3842 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3844 if ( $text === false ) {
3845 $this->mTplDomCache
[$titleText] = false;
3846 return array( false, $title );
3849 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3850 $this->mTplDomCache
[$titleText] = $dom;
3852 if ( !$title->equals( $cacheTitle ) ) {
3853 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3854 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3857 return array( $dom, $title );
3861 * Fetch the current revision of a given title. Note that the revision
3862 * (and even the title) may not exist in the database, so everything
3863 * contributing to the output of the parser should use this method
3864 * where possible, rather than getting the revisions themselves. This
3865 * method also caches its results, so using it benefits performance.
3868 * @param Title $title
3871 public function fetchCurrentRevisionOfTitle( $title ) {
3872 $cacheKey = $title->getPrefixedDBkey();
3873 if ( !$this->currentRevisionCache
) {
3874 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3876 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3877 $this->currentRevisionCache
->set( $cacheKey,
3878 // Defaults to Parser::statelessFetchRevision()
3879 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3882 return $this->currentRevisionCache
->get( $cacheKey );
3886 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3887 * without passing them on to it.
3890 * @param Title $title
3891 * @param Parser|bool $parser
3894 public static function statelessFetchRevision( $title, $parser = false ) {
3895 return Revision
::newFromTitle( $title );
3899 * Fetch the unparsed text of a template and register a reference to it.
3900 * @param Title $title
3901 * @return array ( string or false, Title )
3903 public function fetchTemplateAndTitle( $title ) {
3904 // Defaults to Parser::statelessFetchTemplate()
3905 $templateCb = $this->mOptions
->getTemplateCallback();
3906 $stuff = call_user_func( $templateCb, $title, $this );
3907 // We use U+007F DELETE to distinguish strip markers from regular text.
3908 $text = $stuff['text'];
3909 if ( is_string( $stuff['text'] ) ) {
3910 $text = strtr( $text, "\x7f", "?" );
3912 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3913 if ( isset( $stuff['deps'] ) ) {
3914 foreach ( $stuff['deps'] as $dep ) {
3915 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3916 if ( $dep['title']->equals( $this->getTitle() ) ) {
3917 // If we transclude ourselves, the final result
3918 // will change based on the new version of the page
3919 $this->mOutput
->setFlag( 'vary-revision' );
3923 return array( $text, $finalTitle );
3927 * Fetch the unparsed text of a template and register a reference to it.
3928 * @param Title $title
3929 * @return string|bool
3931 public function fetchTemplate( $title ) {
3932 $rv = $this->fetchTemplateAndTitle( $title );
3937 * Static function to get a template
3938 * Can be overridden via ParserOptions::setTemplateCallback().
3940 * @param Title $title
3941 * @param bool|Parser $parser
3945 public static function statelessFetchTemplate( $title, $parser = false ) {
3946 $text = $skip = false;
3947 $finalTitle = $title;
3950 # Loop to fetch the article, with up to 1 redirect
3951 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3952 # Give extensions a chance to select the revision instead
3953 $id = false; # Assume current
3954 Hooks
::run( 'BeforeParserFetchTemplateAndtitle',
3955 array( $parser, $title, &$skip, &$id ) );
3961 'page_id' => $title->getArticleID(),
3968 $rev = Revision
::newFromId( $id );
3969 } elseif ( $parser ) {
3970 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3972 $rev = Revision
::newFromTitle( $title );
3974 $rev_id = $rev ?
$rev->getId() : 0;
3975 # If there is no current revision, there is no page
3976 if ( $id === false && !$rev ) {
3977 $linkCache = LinkCache
::singleton();
3978 $linkCache->addBadLinkObj( $title );
3983 'page_id' => $title->getArticleID(),
3984 'rev_id' => $rev_id );
3985 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3986 # We fetched a rev from a different title; register it too...
3988 'title' => $rev->getTitle(),
3989 'page_id' => $rev->getPage(),
3990 'rev_id' => $rev_id );
3994 $content = $rev->getContent();
3995 $text = $content ?
$content->getWikitextForTransclusion() : null;
3997 if ( $text === false ||
$text === null ) {
4001 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
4003 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
4004 if ( !$message->exists() ) {
4008 $content = $message->content();
4009 $text = $message->plain();
4017 $finalTitle = $title;
4018 $title = $content->getRedirectTarget();
4022 'finalTitle' => $finalTitle,
4027 * Fetch a file and its title and register a reference to it.
4028 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4029 * @param Title $title
4030 * @param array $options Array of options to RepoGroup::findFile
4033 public function fetchFile( $title, $options = array() ) {
4034 $res = $this->fetchFileAndTitle( $title, $options );
4039 * Fetch a file and its title and register a reference to it.
4040 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4041 * @param Title $title
4042 * @param array $options Array of options to RepoGroup::findFile
4043 * @return array ( File or false, Title of file )
4045 public function fetchFileAndTitle( $title, $options = array() ) {
4046 $file = $this->fetchFileNoRegister( $title, $options );
4048 $time = $file ?
$file->getTimestamp() : false;
4049 $sha1 = $file ?
$file->getSha1() : false;
4050 # Register the file as a dependency...
4051 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4052 if ( $file && !$title->equals( $file->getTitle() ) ) {
4053 # Update fetched file title
4054 $title = $file->getTitle();
4055 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4057 return array( $file, $title );
4061 * Helper function for fetchFileAndTitle.
4063 * Also useful if you need to fetch a file but not use it yet,
4064 * for example to get the file's handler.
4066 * @param Title $title
4067 * @param array $options Array of options to RepoGroup::findFile
4070 protected function fetchFileNoRegister( $title, $options = array() ) {
4071 if ( isset( $options['broken'] ) ) {
4072 $file = false; // broken thumbnail forced by hook
4073 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
4074 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
4075 } else { // get by (name,timestamp)
4076 $file = wfFindFile( $title, $options );
4082 * Transclude an interwiki link.
4084 * @param Title $title
4085 * @param string $action
4089 public function interwikiTransclude( $title, $action ) {
4090 global $wgEnableScaryTranscluding;
4092 if ( !$wgEnableScaryTranscluding ) {
4093 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
4096 $url = $title->getFullURL( array( 'action' => $action ) );
4098 if ( strlen( $url ) > 255 ) {
4099 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
4101 return $this->fetchScaryTemplateMaybeFromCache( $url );
4105 * @param string $url
4106 * @return mixed|string
4108 public function fetchScaryTemplateMaybeFromCache( $url ) {
4109 global $wgTranscludeCacheExpiry;
4110 $dbr = wfGetDB( DB_SLAVE
);
4111 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
4112 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
4113 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
4115 return $obj->tc_contents
;
4118 $req = MWHttpRequest
::factory( $url, array(), __METHOD__
);
4119 $status = $req->execute(); // Status object
4120 if ( $status->isOK() ) {
4121 $text = $req->getContent();
4122 } elseif ( $req->getStatus() != 200 ) {
4123 // Though we failed to fetch the content, this status is useless.
4124 return wfMessage( 'scarytranscludefailed-httpstatus' )
4125 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
4127 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
4130 $dbw = wfGetDB( DB_MASTER
);
4131 $dbw->replace( 'transcache', array( 'tc_url' ), array(
4133 'tc_time' => $dbw->timestamp( time() ),
4134 'tc_contents' => $text
4140 * Triple brace replacement -- used for template arguments
4143 * @param array $piece
4144 * @param PPFrame $frame
4148 public function argSubstitution( $piece, $frame ) {
4151 $parts = $piece['parts'];
4152 $nameWithSpaces = $frame->expand( $piece['title'] );
4153 $argName = trim( $nameWithSpaces );
4155 $text = $frame->getArgument( $argName );
4156 if ( $text === false && $parts->getLength() > 0
4157 && ( $this->ot
['html']
4159 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
4162 # No match in frame, use the supplied default
4163 $object = $parts->item( 0 )->getChildren();
4165 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
4166 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
4167 $this->limitationWarn( 'post-expand-template-argument' );
4170 if ( $text === false && $object === false ) {
4172 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
4174 if ( $error !== false ) {
4177 if ( $object !== false ) {
4178 $ret = array( 'object' => $object );
4180 $ret = array( 'text' => $text );
4187 * Return the text to be used for a given extension tag.
4188 * This is the ghost of strip().
4190 * @param array $params Associative array of parameters:
4191 * name PPNode for the tag name
4192 * attr PPNode for unparsed text where tag attributes are thought to be
4193 * attributes Optional associative array of parsed attributes
4194 * inner Contents of extension element
4195 * noClose Original text did not have a close tag
4196 * @param PPFrame $frame
4198 * @throws MWException
4201 public function extensionSubstitution( $params, $frame ) {
4202 $name = $frame->expand( $params['name'] );
4203 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
4204 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
4205 $marker = self
::MARKER_PREFIX
. "-$name-"
4206 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
4208 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
4209 ( $this->ot
['html'] ||
$this->ot
['pre'] );
4210 if ( $isFunctionTag ) {
4211 $markerType = 'none';
4213 $markerType = 'general';
4215 if ( $this->ot
['html'] ||
$isFunctionTag ) {
4216 $name = strtolower( $name );
4217 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
4218 if ( isset( $params['attributes'] ) ) {
4219 $attributes = $attributes +
$params['attributes'];
4222 if ( isset( $this->mTagHooks
[$name] ) ) {
4223 # Workaround for PHP bug 35229 and similar
4224 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
4225 throw new MWException( "Tag hook for $name is not callable\n" );
4227 $output = call_user_func_array( $this->mTagHooks
[$name],
4228 array( $content, $attributes, $this, $frame ) );
4229 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
4230 list( $callback, ) = $this->mFunctionTagHooks
[$name];
4231 if ( !is_callable( $callback ) ) {
4232 throw new MWException( "Tag hook for $name is not callable\n" );
4235 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
4237 $output = '<span class="error">Invalid tag extension name: ' .
4238 htmlspecialchars( $name ) . '</span>';
4241 if ( is_array( $output ) ) {
4242 # Extract flags to local scope (to override $markerType)
4244 $output = $flags[0];
4249 if ( is_null( $attrText ) ) {
4252 if ( isset( $params['attributes'] ) ) {
4253 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4254 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4255 htmlspecialchars( $attrValue ) . '"';
4258 if ( $content === null ) {
4259 $output = "<$name$attrText/>";
4261 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4262 $output = "<$name$attrText>$content$close";
4266 if ( $markerType === 'none' ) {
4268 } elseif ( $markerType === 'nowiki' ) {
4269 $this->mStripState
->addNoWiki( $marker, $output );
4270 } elseif ( $markerType === 'general' ) {
4271 $this->mStripState
->addGeneral( $marker, $output );
4273 throw new MWException( __METHOD__
. ': invalid marker type' );
4279 * Increment an include size counter
4281 * @param string $type The type of expansion
4282 * @param int $size The size of the text
4283 * @return bool False if this inclusion would take it over the maximum, true otherwise
4285 public function incrementIncludeSize( $type, $size ) {
4286 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4289 $this->mIncludeSizes
[$type] +
= $size;
4295 * Increment the expensive function count
4297 * @return bool False if the limit has been exceeded
4299 public function incrementExpensiveFunctionCount() {
4300 $this->mExpensiveFunctionCount++
;
4301 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4305 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4306 * Fills $this->mDoubleUnderscores, returns the modified text
4308 * @param string $text
4312 public function doDoubleUnderscore( $text ) {
4314 # The position of __TOC__ needs to be recorded
4315 $mw = MagicWord
::get( 'toc' );
4316 if ( $mw->match( $text ) ) {
4317 $this->mShowToc
= true;
4318 $this->mForceTocPosition
= true;
4320 # Set a placeholder. At the end we'll fill it in with the TOC.
4321 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4323 # Only keep the first one.
4324 $text = $mw->replace( '', $text );
4327 # Now match and remove the rest of them
4328 $mwa = MagicWord
::getDoubleUnderscoreArray();
4329 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4331 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4332 $this->mOutput
->mNoGallery
= true;
4334 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4335 $this->mShowToc
= false;
4337 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4338 && $this->mTitle
->getNamespace() == NS_CATEGORY
4340 $this->addTrackingCategory( 'hidden-category-category' );
4342 # (bug 8068) Allow control over whether robots index a page.
4344 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4345 # is not desirable, the last one on the page should win.
4346 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4347 $this->mOutput
->setIndexPolicy( 'noindex' );
4348 $this->addTrackingCategory( 'noindex-category' );
4350 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4351 $this->mOutput
->setIndexPolicy( 'index' );
4352 $this->addTrackingCategory( 'index-category' );
4355 # Cache all double underscores in the database
4356 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4357 $this->mOutput
->setProperty( $key, '' );
4364 * @see ParserOutput::addTrackingCategory()
4365 * @param string $msg Message key
4366 * @return bool Whether the addition was successful
4368 public function addTrackingCategory( $msg ) {
4369 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4373 * This function accomplishes several tasks:
4374 * 1) Auto-number headings if that option is enabled
4375 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4376 * 3) Add a Table of contents on the top for users who have enabled the option
4377 * 4) Auto-anchor headings
4379 * It loops through all headlines, collects the necessary data, then splits up the
4380 * string and re-inserts the newly formatted headlines.
4382 * @param string $text
4383 * @param string $origText Original, untouched wikitext
4384 * @param bool $isMain
4385 * @return mixed|string
4388 public function formatHeadings( $text, $origText, $isMain = true ) {
4389 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4391 # Inhibit editsection links if requested in the page
4392 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4393 $maybeShowEditLink = $showEditLink = false;
4395 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4396 $showEditLink = $this->mOptions
->getEditSection();
4398 if ( $showEditLink ) {
4399 $this->mOutput
->setEditSectionTokens( true );
4402 # Get all headlines for numbering them and adding funky stuff like [edit]
4403 # links - this is for later, but we need the number of headlines right now
4405 $numMatches = preg_match_all(
4406 '/<H(?P<level>[1-6])(?P<attrib>.*?>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i',
4411 # if there are fewer than 4 headlines in the article, do not show TOC
4412 # unless it's been explicitly enabled.
4413 $enoughToc = $this->mShowToc
&&
4414 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4416 # Allow user to stipulate that a page should have a "new section"
4417 # link added via __NEWSECTIONLINK__
4418 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4419 $this->mOutput
->setNewSection( true );
4422 # Allow user to remove the "new section"
4423 # link via __NONEWSECTIONLINK__
4424 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4425 $this->mOutput
->hideNewSection( true );
4428 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4429 # override above conditions and always show TOC above first header
4430 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4431 $this->mShowToc
= true;
4439 # Ugh .. the TOC should have neat indentation levels which can be
4440 # passed to the skin functions. These are determined here
4444 $sublevelCount = array();
4445 $levelCount = array();
4450 $markerRegex = self
::MARKER_PREFIX
. "-h-(\d+)-" . self
::MARKER_SUFFIX
;
4451 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4452 $oldType = $this->mOutputType
;
4453 $this->setOutputType( self
::OT_WIKI
);
4454 $frame = $this->getPreprocessor()->newFrame();
4455 $root = $this->preprocessToDom( $origText );
4456 $node = $root->getFirstChild();
4461 $headlines = $numMatches !== false ?
$matches[3] : array();
4463 foreach ( $headlines as $headline ) {
4464 $isTemplate = false;
4466 $sectionIndex = false;
4468 $markerMatches = array();
4469 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4470 $serial = $markerMatches[1];
4471 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4472 $isTemplate = ( $titleText != $baseTitleText );
4473 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4477 $prevlevel = $level;
4479 $level = $matches[1][$headlineCount];
4481 if ( $level > $prevlevel ) {
4482 # Increase TOC level
4484 $sublevelCount[$toclevel] = 0;
4485 if ( $toclevel < $wgMaxTocLevel ) {
4486 $prevtoclevel = $toclevel;
4487 $toc .= Linker
::tocIndent();
4490 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4491 # Decrease TOC level, find level to jump to
4493 for ( $i = $toclevel; $i > 0; $i-- ) {
4494 if ( $levelCount[$i] == $level ) {
4495 # Found last matching level
4498 } elseif ( $levelCount[$i] < $level ) {
4499 # Found first matching level below current level
4507 if ( $toclevel < $wgMaxTocLevel ) {
4508 if ( $prevtoclevel < $wgMaxTocLevel ) {
4509 # Unindent only if the previous toc level was shown :p
4510 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4511 $prevtoclevel = $toclevel;
4513 $toc .= Linker
::tocLineEnd();
4517 # No change in level, end TOC line
4518 if ( $toclevel < $wgMaxTocLevel ) {
4519 $toc .= Linker
::tocLineEnd();
4523 $levelCount[$toclevel] = $level;
4525 # count number of headlines for each level
4526 $sublevelCount[$toclevel]++
;
4528 for ( $i = 1; $i <= $toclevel; $i++
) {
4529 if ( !empty( $sublevelCount[$i] ) ) {
4533 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4538 # The safe header is a version of the header text safe to use for links
4540 # Remove link placeholders by the link text.
4541 # <!--LINK number-->
4543 # link text with suffix
4544 # Do this before unstrip since link text can contain strip markers
4545 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4547 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4548 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4550 # Strip out HTML (first regex removes any tag not allowed)
4552 # * <sup> and <sub> (bug 8393)
4555 # * <bdi> (bug 72884)
4556 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4558 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4559 # to allow setting directionality in toc items.
4560 $tocline = preg_replace(
4562 '#<(?!/?(span|sup|sub|bdi|i|b)(?: [^>]*)?>).*?>#',
4563 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b))(?: .*?)?>#'
4565 array( '', '<$1>' ),
4569 # Strip '<span></span>', which is the result from the above if
4570 # <span id="foo"></span> is used to produce an additional anchor
4572 $tocline = str_replace( '<span></span>', '', $tocline );
4574 $tocline = trim( $tocline );
4576 # For the anchor, strip out HTML-y stuff period
4577 $safeHeadline = preg_replace( '/<.*?>/', '', $safeHeadline );
4578 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4580 # Save headline for section edit hint before it's escaped
4581 $headlineHint = $safeHeadline;
4583 if ( $wgExperimentalHtmlIds ) {
4584 # For reverse compatibility, provide an id that's
4585 # HTML4-compatible, like we used to.
4587 # It may be worth noting, academically, that it's possible for
4588 # the legacy anchor to conflict with a non-legacy headline
4589 # anchor on the page. In this case likely the "correct" thing
4590 # would be to either drop the legacy anchors or make sure
4591 # they're numbered first. However, this would require people
4592 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4593 # manually, so let's not bother worrying about it.
4594 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4595 array( 'noninitial', 'legacy' ) );
4596 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4598 if ( $legacyHeadline == $safeHeadline ) {
4599 # No reason to have both (in fact, we can't)
4600 $legacyHeadline = false;
4603 $legacyHeadline = false;
4604 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4608 # HTML names must be case-insensitively unique (bug 10721).
4609 # This does not apply to Unicode characters per
4610 # http://www.w3.org/TR/html5/infrastructure.html#case-sensitivity-and-string-comparison
4611 # @todo FIXME: We may be changing them depending on the current locale.
4612 $arrayKey = strtolower( $safeHeadline );
4613 if ( $legacyHeadline === false ) {
4614 $legacyArrayKey = false;
4616 $legacyArrayKey = strtolower( $legacyHeadline );
4619 # Create the anchor for linking from the TOC to the section
4620 $anchor = $safeHeadline;
4621 $legacyAnchor = $legacyHeadline;
4622 if ( isset( $refers[$arrayKey] ) ) {
4623 for ( $i = 2; isset( $refers["${arrayKey}_$i"] ); ++
$i );
4625 $refers["${arrayKey}_$i"] = true;
4627 $refers[$arrayKey] = true;
4629 if ( $legacyHeadline !== false && isset( $refers[$legacyArrayKey] ) ) {
4630 for ( $i = 2; isset( $refers["${legacyArrayKey}_$i"] ); ++
$i );
4631 $legacyAnchor .= "_$i";
4632 $refers["${legacyArrayKey}_$i"] = true;
4634 $refers[$legacyArrayKey] = true;
4637 # Don't number the heading if it is the only one (looks silly)
4638 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4639 # the two are different if the line contains a link
4640 $headline = Html
::element(
4642 array( 'class' => 'mw-headline-number' ),
4644 ) . ' ' . $headline;
4647 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4648 $toc .= Linker
::tocLine( $anchor, $tocline,
4649 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4652 # Add the section to the section tree
4653 # Find the DOM node for this header
4654 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4655 while ( $node && !$noOffset ) {
4656 if ( $node->getName() === 'h' ) {
4657 $bits = $node->splitHeading();
4658 if ( $bits['i'] == $sectionIndex ) {
4662 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4663 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4664 $node = $node->getNextSibling();
4667 'toclevel' => $toclevel,
4670 'number' => $numbering,
4671 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4672 'fromtitle' => $titleText,
4673 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4674 'anchor' => $anchor,
4677 # give headline the correct <h#> tag
4678 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4679 // Output edit section links as markers with styles that can be customized by skins
4680 if ( $isTemplate ) {
4681 # Put a T flag in the section identifier, to indicate to extractSections()
4682 # that sections inside <includeonly> should be counted.
4683 $editsectionPage = $titleText;
4684 $editsectionSection = "T-$sectionIndex";
4685 $editsectionContent = null;
4687 $editsectionPage = $this->mTitle
->getPrefixedText();
4688 $editsectionSection = $sectionIndex;
4689 $editsectionContent = $headlineHint;
4691 // We use a bit of pesudo-xml for editsection markers. The
4692 // language converter is run later on. Using a UNIQ style marker
4693 // leads to the converter screwing up the tokens when it
4694 // converts stuff. And trying to insert strip tags fails too. At
4695 // this point all real inputted tags have already been escaped,
4696 // so we don't have to worry about a user trying to input one of
4697 // these markers directly. We use a page and section attribute
4698 // to stop the language converter from converting these
4699 // important bits of data, but put the headline hint inside a
4700 // content block because the language converter is supposed to
4701 // be able to convert that piece of data.
4702 // Gets replaced with html in ParserOutput::getText
4703 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4704 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4705 if ( $editsectionContent !== null ) {
4706 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4713 $head[$headlineCount] = Linker
::makeHeadline( $level,
4714 $matches['attrib'][$headlineCount], $anchor, $headline,
4715 $editlink, $legacyAnchor );
4720 $this->setOutputType( $oldType );
4722 # Never ever show TOC if no headers
4723 if ( $numVisible < 1 ) {
4728 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4729 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4731 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4732 $this->mOutput
->setTOCHTML( $toc );
4733 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4734 $this->mOutput
->addModules( 'mediawiki.toc' );
4738 $this->mOutput
->setSections( $tocraw );
4741 # split up and insert constructed headlines
4742 $blocks = preg_split( '/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4745 // build an array of document sections
4746 $sections = array();
4747 foreach ( $blocks as $block ) {
4748 // $head is zero-based, sections aren't.
4749 if ( empty( $head[$i - 1] ) ) {
4750 $sections[$i] = $block;
4752 $sections[$i] = $head[$i - 1] . $block;
4756 * Send a hook, one per section.
4757 * The idea here is to be able to make section-level DIVs, but to do so in a
4758 * lower-impact, more correct way than r50769
4761 * $section : the section number
4762 * &$sectionContent : ref to the content of the section
4763 * $showEditLinks : boolean describing whether this section has an edit link
4765 Hooks
::run( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4770 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4771 // append the TOC at the beginning
4772 // Top anchor now in skin
4773 $sections[0] = $sections[0] . $toc . "\n";
4776 $full .= join( '', $sections );
4778 if ( $this->mForceTocPosition
) {
4779 return str_replace( '<!--MWTOC-->', $toc, $full );
4786 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4787 * conversion, substituting signatures, {{subst:}} templates, etc.
4789 * @param string $text The text to transform
4790 * @param Title $title The Title object for the current article
4791 * @param User $user The User object describing the current user
4792 * @param ParserOptions $options Parsing options
4793 * @param bool $clearState Whether to clear the parser state first
4794 * @return string The altered wiki markup
4796 public function preSaveTransform( $text, Title
$title, User
$user,
4797 ParserOptions
$options, $clearState = true
4799 if ( $clearState ) {
4800 $magicScopeVariable = $this->lock();
4802 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4803 $this->setUser( $user );
4809 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4810 if ( $options->getPreSaveTransform() ) {
4811 $text = $this->pstPass2( $text, $user );
4813 $text = $this->mStripState
->unstripBoth( $text );
4815 $this->setUser( null ); #Reset
4821 * Pre-save transform helper function
4823 * @param string $text
4828 private function pstPass2( $text, $user ) {
4831 # Note: This is the timestamp saved as hardcoded wikitext to
4832 # the database, we use $wgContLang here in order to give
4833 # everyone the same signature and use the default one rather
4834 # than the one selected in each user's preferences.
4835 # (see also bug 12815)
4836 $ts = $this->mOptions
->getTimestamp();
4837 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4838 $ts = $timestamp->format( 'YmdHis' );
4839 $tzMsg = $timestamp->format( 'T' ); # might vary on DST changeover!
4841 # Allow translation of timezones through wiki. format() can return
4842 # whatever crap the system uses, localised or not, so we cannot
4843 # ship premade translations.
4844 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4845 $msg = wfMessage( $key )->inContentLanguage();
4846 if ( $msg->exists() ) {
4847 $tzMsg = $msg->text();
4850 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4852 # Variable replacement
4853 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4854 $text = $this->replaceVariables( $text );
4856 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4857 # which may corrupt this parser instance via its wfMessage()->text() call-
4860 $sigText = $this->getUserSig( $user );
4861 $text = strtr( $text, array(
4863 '~~~~' => "$sigText $d",
4867 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4868 $tc = '[' . Title
::legalChars() . ']';
4869 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4871 // [[ns:page (context)|]]
4872 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4873 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4874 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4875 // [[ns:page (context), context|]] (using either single or double-width comma)
4876 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4877 // [[|page]] (reverse pipe trick: add context from page title)
4878 $p2 = "/\[\[\\|($tc+)]]/";
4880 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4881 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4882 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4883 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4885 $t = $this->mTitle
->getText();
4887 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4888 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4889 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4890 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4892 # if there's no context, don't bother duplicating the title
4893 $text = preg_replace( $p2, '[[\\1]]', $text );
4896 # Trim trailing whitespace
4897 $text = rtrim( $text );
4903 * Fetch the user's signature text, if any, and normalize to
4904 * validated, ready-to-insert wikitext.
4905 * If you have pre-fetched the nickname or the fancySig option, you can
4906 * specify them here to save a database query.
4907 * Do not reuse this parser instance after calling getUserSig(),
4908 * as it may have changed if it's the $wgParser.
4911 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4912 * @param bool|null $fancySig whether the nicknname is the complete signature
4913 * or null to use default value
4916 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4917 global $wgMaxSigChars;
4919 $username = $user->getName();
4921 # If not given, retrieve from the user object.
4922 if ( $nickname === false ) {
4923 $nickname = $user->getOption( 'nickname' );
4926 if ( is_null( $fancySig ) ) {
4927 $fancySig = $user->getBoolOption( 'fancysig' );
4930 $nickname = $nickname == null ?
$username : $nickname;
4932 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4933 $nickname = $username;
4934 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4935 } elseif ( $fancySig !== false ) {
4936 # Sig. might contain markup; validate this
4937 if ( $this->validateSig( $nickname ) !== false ) {
4938 # Validated; clean up (if needed) and return it
4939 return $this->cleanSig( $nickname, true );
4941 # Failed to validate; fall back to the default
4942 $nickname = $username;
4943 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4947 # Make sure nickname doesnt get a sig in a sig
4948 $nickname = self
::cleanSigInSig( $nickname );
4950 # If we're still here, make it a link to the user page
4951 $userText = wfEscapeWikiText( $username );
4952 $nickText = wfEscapeWikiText( $nickname );
4953 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4955 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4956 ->title( $this->getTitle() )->text();
4960 * Check that the user's signature contains no bad XML
4962 * @param string $text
4963 * @return string|bool An expanded string, or false if invalid.
4965 public function validateSig( $text ) {
4966 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4970 * Clean up signature text
4972 * 1) Strip 3, 4 or 5 tildes out of signatures @see cleanSigInSig
4973 * 2) Substitute all transclusions
4975 * @param string $text
4976 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4977 * @return string Signature text
4979 public function cleanSig( $text, $parsing = false ) {
4982 $magicScopeVariable = $this->lock();
4983 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4986 # Option to disable this feature
4987 if ( !$this->mOptions
->getCleanSignatures() ) {
4991 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4992 # => Move this logic to braceSubstitution()
4993 $substWord = MagicWord
::get( 'subst' );
4994 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4995 $substText = '{{' . $substWord->getSynonym( 0 );
4997 $text = preg_replace( $substRegex, $substText, $text );
4998 $text = self
::cleanSigInSig( $text );
4999 $dom = $this->preprocessToDom( $text );
5000 $frame = $this->getPreprocessor()->newFrame();
5001 $text = $frame->expand( $dom );
5004 $text = $this->mStripState
->unstripBoth( $text );
5011 * Strip 3, 4 or 5 tildes out of signatures.
5013 * @param string $text
5014 * @return string Signature text with /~{3,5}/ removed
5016 public static function cleanSigInSig( $text ) {
5017 $text = preg_replace( '/~{3,5}/', '', $text );
5022 * Set up some variables which are usually set up in parse()
5023 * so that an external function can call some class members with confidence
5025 * @param Title|null $title
5026 * @param ParserOptions $options
5027 * @param int $outputType
5028 * @param bool $clearState
5030 public function startExternalParse( Title
$title = null, ParserOptions
$options,
5031 $outputType, $clearState = true
5033 $this->startParse( $title, $options, $outputType, $clearState );
5037 * @param Title|null $title
5038 * @param ParserOptions $options
5039 * @param int $outputType
5040 * @param bool $clearState
5042 private function startParse( Title
$title = null, ParserOptions
$options,
5043 $outputType, $clearState = true
5045 $this->setTitle( $title );
5046 $this->mOptions
= $options;
5047 $this->setOutputType( $outputType );
5048 if ( $clearState ) {
5049 $this->clearState();
5054 * Wrapper for preprocess()
5056 * @param string $text The text to preprocess
5057 * @param ParserOptions $options Options
5058 * @param Title|null $title Title object or null to use $wgTitle
5061 public function transformMsg( $text, $options, $title = null ) {
5062 static $executing = false;
5064 # Guard against infinite recursion
5075 $text = $this->preprocess( $text, $title, $options );
5082 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
5083 * The callback should have the following form:
5084 * function myParserHook( $text, $params, $parser, $frame ) { ... }
5086 * Transform and return $text. Use $parser for any required context, e.g. use
5087 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
5089 * Hooks may return extended information by returning an array, of which the
5090 * first numbered element (index 0) must be the return string, and all other
5091 * entries are extracted into local variables within an internal function
5092 * in the Parser class.
5094 * This interface (introduced r61913) appears to be undocumented, but
5095 * 'markerType' is used by some core tag hooks to override which strip
5096 * array their results are placed in. **Use great caution if attempting
5097 * this interface, as it is not documented and injudicious use could smash
5098 * private variables.**
5100 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5101 * @param callable $callback The callback function (and object) to use for the tag
5102 * @throws MWException
5103 * @return callable|null The old value of the mTagHooks array associated with the hook
5105 public function setHook( $tag, $callback ) {
5106 $tag = strtolower( $tag );
5107 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5108 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
5110 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
5111 $this->mTagHooks
[$tag] = $callback;
5112 if ( !in_array( $tag, $this->mStripList
) ) {
5113 $this->mStripList
[] = $tag;
5120 * As setHook(), but letting the contents be parsed.
5122 * Transparent tag hooks are like regular XML-style tag hooks, except they
5123 * operate late in the transformation sequence, on HTML instead of wikitext.
5125 * This is probably obsoleted by things dealing with parser frames?
5126 * The only extension currently using it is geoserver.
5129 * @todo better document or deprecate this
5131 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5132 * @param callable $callback The callback function (and object) to use for the tag
5133 * @throws MWException
5134 * @return callable|null The old value of the mTagHooks array associated with the hook
5136 public function setTransparentTagHook( $tag, $callback ) {
5137 $tag = strtolower( $tag );
5138 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5139 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
5141 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
5142 $this->mTransparentTagHooks
[$tag] = $callback;
5148 * Remove all tag hooks
5150 public function clearTagHooks() {
5151 $this->mTagHooks
= array();
5152 $this->mFunctionTagHooks
= array();
5153 $this->mStripList
= $this->mDefaultStripList
;
5157 * Create a function, e.g. {{sum:1|2|3}}
5158 * The callback function should have the form:
5159 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
5161 * Or with Parser::SFH_OBJECT_ARGS:
5162 * function myParserFunction( $parser, $frame, $args ) { ... }
5164 * The callback may either return the text result of the function, or an array with the text
5165 * in element 0, and a number of flags in the other elements. The names of the flags are
5166 * specified in the keys. Valid flags are:
5167 * found The text returned is valid, stop processing the template. This
5169 * nowiki Wiki markup in the return value should be escaped
5170 * isHTML The returned text is HTML, armour it against wikitext transformation
5172 * @param string $id The magic word ID
5173 * @param callable $callback The callback function (and object) to use
5174 * @param int $flags A combination of the following flags:
5175 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
5177 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
5178 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
5179 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
5180 * the arguments, and to control the way they are expanded.
5182 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
5183 * arguments, for instance:
5184 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
5186 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
5187 * future versions. Please call $frame->expand() on it anyway so that your code keeps
5188 * working if/when this is changed.
5190 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
5193 * Please read the documentation in includes/parser/Preprocessor.php for more information
5194 * about the methods available in PPFrame and PPNode.
5196 * @throws MWException
5197 * @return string|callable The old callback function for this name, if any
5199 public function setFunctionHook( $id, $callback, $flags = 0 ) {
5202 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
5203 $this->mFunctionHooks
[$id] = array( $callback, $flags );
5205 # Add to function cache
5206 $mw = MagicWord
::get( $id );
5208 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
5211 $synonyms = $mw->getSynonyms();
5212 $sensitive = intval( $mw->isCaseSensitive() );
5214 foreach ( $synonyms as $syn ) {
5216 if ( !$sensitive ) {
5217 $syn = $wgContLang->lc( $syn );
5220 if ( !( $flags & self
::SFH_NO_HASH
) ) {
5223 # Remove trailing colon
5224 if ( substr( $syn, -1, 1 ) === ':' ) {
5225 $syn = substr( $syn, 0, -1 );
5227 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
5233 * Get all registered function hook identifiers
5237 public function getFunctionHooks() {
5238 return array_keys( $this->mFunctionHooks
);
5242 * Create a tag function, e.g. "<test>some stuff</test>".
5243 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5244 * Unlike parser functions, their content is not preprocessed.
5245 * @param string $tag
5246 * @param callable $callback
5248 * @throws MWException
5251 public function setFunctionTagHook( $tag, $callback, $flags ) {
5252 $tag = strtolower( $tag );
5253 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5254 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5256 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
5257 $this->mFunctionTagHooks
[$tag] : null;
5258 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
5260 if ( !in_array( $tag, $this->mStripList
) ) {
5261 $this->mStripList
[] = $tag;
5268 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
5269 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5270 * Placeholders created in Skin::makeLinkObj()
5272 * @param string $text
5273 * @param int $options
5275 public function replaceLinkHolders( &$text, $options = 0 ) {
5276 $this->mLinkHolders
->replace( $text );
5280 * Replace "<!--LINK-->" link placeholders with plain text of links
5281 * (not HTML-formatted).
5283 * @param string $text
5286 public function replaceLinkHoldersText( $text ) {
5287 return $this->mLinkHolders
->replaceText( $text );
5291 * Renders an image gallery from a text with one line per image.
5292 * text labels may be given by using |-style alternative text. E.g.
5293 * Image:one.jpg|The number "1"
5294 * Image:tree.jpg|A tree
5295 * given as text will return the HTML of a gallery with two images,
5296 * labeled 'The number "1"' and
5299 * @param string $text
5300 * @param array $params
5301 * @return string HTML
5303 public function renderImageGallery( $text, $params ) {
5306 if ( isset( $params['mode'] ) ) {
5307 $mode = $params['mode'];
5311 $ig = ImageGalleryBase
::factory( $mode );
5312 } catch ( Exception
$e ) {
5313 // If invalid type set, fallback to default.
5314 $ig = ImageGalleryBase
::factory( false );
5317 $ig->setContextTitle( $this->mTitle
);
5318 $ig->setShowBytes( false );
5319 $ig->setShowFilename( false );
5320 $ig->setParser( $this );
5321 $ig->setHideBadImages();
5322 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
5324 if ( isset( $params['showfilename'] ) ) {
5325 $ig->setShowFilename( true );
5327 $ig->setShowFilename( false );
5329 if ( isset( $params['caption'] ) ) {
5330 $caption = $params['caption'];
5331 $caption = htmlspecialchars( $caption );
5332 $caption = $this->replaceInternalLinks( $caption );
5333 $ig->setCaptionHtml( $caption );
5335 if ( isset( $params['perrow'] ) ) {
5336 $ig->setPerRow( $params['perrow'] );
5338 if ( isset( $params['widths'] ) ) {
5339 $ig->setWidths( $params['widths'] );
5341 if ( isset( $params['heights'] ) ) {
5342 $ig->setHeights( $params['heights'] );
5344 $ig->setAdditionalOptions( $params );
5346 Hooks
::run( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5348 $lines = StringUtils
::explode( "\n", $text );
5349 foreach ( $lines as $line ) {
5350 # match lines like these:
5351 # Image:someimage.jpg|This is some image
5353 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5355 if ( count( $matches ) == 0 ) {
5359 if ( strpos( $matches[0], '%' ) !== false ) {
5360 $matches[1] = rawurldecode( $matches[1] );
5362 $title = Title
::newFromText( $matches[1], NS_FILE
);
5363 if ( is_null( $title ) ) {
5364 # Bogus title. Ignore these so we don't bomb out later.
5368 # We need to get what handler the file uses, to figure out parameters.
5369 # Note, a hook can overide the file name, and chose an entirely different
5370 # file (which potentially could be of a different type and have different handler).
5373 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5374 array( $this, $title, &$options, &$descQuery ) );
5375 # Don't register it now, as ImageGallery does that later.
5376 $file = $this->fetchFileNoRegister( $title, $options );
5377 $handler = $file ?
$file->getHandler() : false;
5380 'img_alt' => 'gallery-internal-alt',
5381 'img_link' => 'gallery-internal-link',
5384 $paramMap = $paramMap +
$handler->getParamMap();
5385 // We don't want people to specify per-image widths.
5386 // Additionally the width parameter would need special casing anyhow.
5387 unset( $paramMap['img_width'] );
5390 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5395 $handlerOptions = array();
5396 if ( isset( $matches[3] ) ) {
5397 // look for an |alt= definition while trying not to break existing
5398 // captions with multiple pipes (|) in it, until a more sensible grammar
5399 // is defined for images in galleries
5401 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5402 // splitting on '|' is a bit odd, and different from makeImage.
5403 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5404 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
5406 foreach ( $parameterMatches as $parameterMatch ) {
5407 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5409 $paramName = $paramMap[$magicName];
5411 switch ( $paramName ) {
5412 case 'gallery-internal-alt':
5413 $alt = $this->stripAltText( $match, false );
5415 case 'gallery-internal-link':
5416 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5417 $chars = self
::EXT_LINK_URL_CLASS
;
5418 $prots = $this->mUrlProtocols
;
5419 //check to see if link matches an absolute url, if not then it must be a wiki link.
5420 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5423 $localLinkTitle = Title
::newFromText( $linkValue );
5424 if ( $localLinkTitle !== null ) {
5425 $link = $localLinkTitle->getLinkURL();
5430 // Must be a handler specific parameter.
5431 if ( $handler->validateParam( $paramName, $match ) ) {
5432 $handlerOptions[$paramName] = $match;
5434 // Guess not. Append it to the caption.
5435 wfDebug( "$parameterMatch failed parameter validation\n" );
5436 $label .= '|' . $parameterMatch;
5441 // concatenate all other pipes
5442 $label .= '|' . $parameterMatch;
5445 // remove the first pipe
5446 $label = substr( $label, 1 );
5449 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5451 $html = $ig->toHTML();
5452 Hooks
::run( 'AfterParserFetchFileAndTitle', array( $this, $ig, &$html ) );
5457 * @param MediaHandler $handler
5460 public function getImageParams( $handler ) {
5462 $handlerClass = get_class( $handler );
5466 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5467 # Initialise static lists
5468 static $internalParamNames = array(
5469 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5470 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5471 'bottom', 'text-bottom' ),
5472 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5473 'upright', 'border', 'link', 'alt', 'class' ),
5475 static $internalParamMap;
5476 if ( !$internalParamMap ) {
5477 $internalParamMap = array();
5478 foreach ( $internalParamNames as $type => $names ) {
5479 foreach ( $names as $name ) {
5480 $magicName = str_replace( '-', '_', "img_$name" );
5481 $internalParamMap[$magicName] = array( $type, $name );
5486 # Add handler params
5487 $paramMap = $internalParamMap;
5489 $handlerParamMap = $handler->getParamMap();
5490 foreach ( $handlerParamMap as $magic => $paramName ) {
5491 $paramMap[$magic] = array( 'handler', $paramName );
5494 $this->mImageParams
[$handlerClass] = $paramMap;
5495 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5497 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5501 * Parse image options text and use it to make an image
5503 * @param Title $title
5504 * @param string $options
5505 * @param LinkHolderArray|bool $holders
5506 * @return string HTML
5508 public function makeImage( $title, $options, $holders = false ) {
5509 # Check if the options text is of the form "options|alt text"
5511 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5512 # * left no resizing, just left align. label is used for alt= only
5513 # * right same, but right aligned
5514 # * none same, but not aligned
5515 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5516 # * center center the image
5517 # * frame Keep original image size, no magnify-button.
5518 # * framed Same as "frame"
5519 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5520 # * upright reduce width for upright images, rounded to full __0 px
5521 # * border draw a 1px border around the image
5522 # * alt Text for HTML alt attribute (defaults to empty)
5523 # * class Set a class for img node
5524 # * link Set the target of the image link. Can be external, interwiki, or local
5525 # vertical-align values (no % or length right now):
5535 $parts = StringUtils
::explode( "|", $options );
5537 # Give extensions a chance to select the file revision for us
5540 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5541 array( $this, $title, &$options, &$descQuery ) );
5542 # Fetch and register the file (file title may be different via hooks)
5543 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5546 $handler = $file ?
$file->getHandler() : false;
5548 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5551 $this->addTrackingCategory( 'broken-file-category' );
5554 # Process the input parameters
5556 $params = array( 'frame' => array(), 'handler' => array(),
5557 'horizAlign' => array(), 'vertAlign' => array() );
5558 $seenformat = false;
5559 foreach ( $parts as $part ) {
5560 $part = trim( $part );
5561 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5563 if ( isset( $paramMap[$magicName] ) ) {
5564 list( $type, $paramName ) = $paramMap[$magicName];
5566 # Special case; width and height come in one variable together
5567 if ( $type === 'handler' && $paramName === 'width' ) {
5568 $parsedWidthParam = $this->parseWidthParam( $value );
5569 if ( isset( $parsedWidthParam['width'] ) ) {
5570 $width = $parsedWidthParam['width'];
5571 if ( $handler->validateParam( 'width', $width ) ) {
5572 $params[$type]['width'] = $width;
5576 if ( isset( $parsedWidthParam['height'] ) ) {
5577 $height = $parsedWidthParam['height'];
5578 if ( $handler->validateParam( 'height', $height ) ) {
5579 $params[$type]['height'] = $height;
5583 # else no validation -- bug 13436
5585 if ( $type === 'handler' ) {
5586 # Validate handler parameter
5587 $validated = $handler->validateParam( $paramName, $value );
5589 # Validate internal parameters
5590 switch ( $paramName ) {
5594 # @todo FIXME: Possibly check validity here for
5595 # manualthumb? downstream behavior seems odd with
5596 # missing manual thumbs.
5598 $value = $this->stripAltText( $value, $holders );
5601 $chars = self
::EXT_LINK_URL_CLASS
;
5602 $prots = $this->mUrlProtocols
;
5603 if ( $value === '' ) {
5604 $paramName = 'no-link';
5607 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5608 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5609 $paramName = 'link-url';
5610 $this->mOutput
->addExternalLink( $value );
5611 if ( $this->mOptions
->getExternalLinkTarget() ) {
5612 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5617 $linkTitle = Title
::newFromText( $value );
5619 $paramName = 'link-title';
5620 $value = $linkTitle;
5621 $this->mOutput
->addLink( $linkTitle );
5629 // use first appearing option, discard others.
5630 $validated = ! $seenformat;
5634 # Most other things appear to be empty or numeric...
5635 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5640 $params[$type][$paramName] = $value;
5644 if ( !$validated ) {
5649 # Process alignment parameters
5650 if ( $params['horizAlign'] ) {
5651 $params['frame']['align'] = key( $params['horizAlign'] );
5653 if ( $params['vertAlign'] ) {
5654 $params['frame']['valign'] = key( $params['vertAlign'] );
5657 $params['frame']['caption'] = $caption;
5659 # Will the image be presented in a frame, with the caption below?
5660 $imageIsFramed = isset( $params['frame']['frame'] )
5661 ||
isset( $params['frame']['framed'] )
5662 ||
isset( $params['frame']['thumbnail'] )
5663 ||
isset( $params['frame']['manualthumb'] );
5665 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5666 # came to also set the caption, ordinary text after the image -- which
5667 # makes no sense, because that just repeats the text multiple times in
5668 # screen readers. It *also* came to set the title attribute.
5670 # Now that we have an alt attribute, we should not set the alt text to
5671 # equal the caption: that's worse than useless, it just repeats the
5672 # text. This is the framed/thumbnail case. If there's no caption, we
5673 # use the unnamed parameter for alt text as well, just for the time be-
5674 # ing, if the unnamed param is set and the alt param is not.
5676 # For the future, we need to figure out if we want to tweak this more,
5677 # e.g., introducing a title= parameter for the title; ignoring the un-
5678 # named parameter entirely for images without a caption; adding an ex-
5679 # plicit caption= parameter and preserving the old magic unnamed para-
5681 if ( $imageIsFramed ) { # Framed image
5682 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5683 # No caption or alt text, add the filename as the alt text so
5684 # that screen readers at least get some description of the image
5685 $params['frame']['alt'] = $title->getText();
5687 # Do not set $params['frame']['title'] because tooltips don't make sense
5689 } else { # Inline image
5690 if ( !isset( $params['frame']['alt'] ) ) {
5691 # No alt text, use the "caption" for the alt text
5692 if ( $caption !== '' ) {
5693 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5695 # No caption, fall back to using the filename for the
5697 $params['frame']['alt'] = $title->getText();
5700 # Use the "caption" for the tooltip text
5701 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5704 Hooks
::run( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5706 # Linker does the rest
5707 $time = isset( $options['time'] ) ?
$options['time'] : false;
5708 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5709 $time, $descQuery, $this->mOptions
->getThumbSize() );
5711 # Give the handler a chance to modify the parser object
5713 $handler->parserTransformHook( $this, $file );
5720 * @param string $caption
5721 * @param LinkHolderArray|bool $holders
5722 * @return mixed|string
5724 protected function stripAltText( $caption, $holders ) {
5725 # Strip bad stuff out of the title (tooltip). We can't just use
5726 # replaceLinkHoldersText() here, because if this function is called
5727 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5729 $tooltip = $holders->replaceText( $caption );
5731 $tooltip = $this->replaceLinkHoldersText( $caption );
5734 # make sure there are no placeholders in thumbnail attributes
5735 # that are later expanded to html- so expand them now and
5737 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5738 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5744 * Set a flag in the output object indicating that the content is dynamic and
5745 * shouldn't be cached.
5747 public function disableCache() {
5748 wfDebug( "Parser output marked as uncacheable.\n" );
5749 if ( !$this->mOutput
) {
5750 throw new MWException( __METHOD__
.
5751 " can only be called when actually parsing something" );
5753 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5754 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5758 * Callback from the Sanitizer for expanding items found in HTML attribute
5759 * values, so they can be safely tested and escaped.
5761 * @param string $text
5762 * @param bool|PPFrame $frame
5765 public function attributeStripCallback( &$text, $frame = false ) {
5766 $text = $this->replaceVariables( $text, $frame );
5767 $text = $this->mStripState
->unstripBoth( $text );
5776 public function getTags() {
5778 array_keys( $this->mTransparentTagHooks
),
5779 array_keys( $this->mTagHooks
),
5780 array_keys( $this->mFunctionTagHooks
)
5785 * Replace transparent tags in $text with the values given by the callbacks.
5787 * Transparent tag hooks are like regular XML-style tag hooks, except they
5788 * operate late in the transformation sequence, on HTML instead of wikitext.
5790 * @param string $text
5794 public function replaceTransparentTags( $text ) {
5796 $elements = array_keys( $this->mTransparentTagHooks
);
5797 $text = self
::extractTagsAndParams( $elements, $text, $matches );
5798 $replacements = array();
5800 foreach ( $matches as $marker => $data ) {
5801 list( $element, $content, $params, $tag ) = $data;
5802 $tagName = strtolower( $element );
5803 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5804 $output = call_user_func_array(
5805 $this->mTransparentTagHooks
[$tagName],
5806 array( $content, $params, $this )
5811 $replacements[$marker] = $output;
5813 return strtr( $text, $replacements );
5817 * Break wikitext input into sections, and either pull or replace
5818 * some particular section's text.
5820 * External callers should use the getSection and replaceSection methods.
5822 * @param string $text Page wikitext
5823 * @param string|number $sectionId A section identifier string of the form:
5824 * "<flag1> - <flag2> - ... - <section number>"
5826 * Currently the only recognised flag is "T", which means the target section number
5827 * was derived during a template inclusion parse, in other words this is a template
5828 * section edit link. If no flags are given, it was an ordinary section edit link.
5829 * This flag is required to avoid a section numbering mismatch when a section is
5830 * enclosed by "<includeonly>" (bug 6563).
5832 * The section number 0 pulls the text before the first heading; other numbers will
5833 * pull the given section along with its lower-level subsections. If the section is
5834 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5836 * Section 0 is always considered to exist, even if it only contains the empty
5837 * string. If $text is the empty string and section 0 is replaced, $newText is
5840 * @param string $mode One of "get" or "replace"
5841 * @param string $newText Replacement text for section data.
5842 * @return string For "get", the extracted section text.
5843 * for "replace", the whole page with the section replaced.
5845 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5846 global $wgTitle; # not generally used but removes an ugly failure mode
5848 $magicScopeVariable = $this->lock();
5849 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5851 $frame = $this->getPreprocessor()->newFrame();
5853 # Process section extraction flags
5855 $sectionParts = explode( '-', $sectionId );
5856 $sectionIndex = array_pop( $sectionParts );
5857 foreach ( $sectionParts as $part ) {
5858 if ( $part === 'T' ) {
5859 $flags |
= self
::PTD_FOR_INCLUSION
;
5863 # Check for empty input
5864 if ( strval( $text ) === '' ) {
5865 # Only sections 0 and T-0 exist in an empty document
5866 if ( $sectionIndex == 0 ) {
5867 if ( $mode === 'get' ) {
5873 if ( $mode === 'get' ) {
5881 # Preprocess the text
5882 $root = $this->preprocessToDom( $text, $flags );
5884 # <h> nodes indicate section breaks
5885 # They can only occur at the top level, so we can find them by iterating the root's children
5886 $node = $root->getFirstChild();
5888 # Find the target section
5889 if ( $sectionIndex == 0 ) {
5890 # Section zero doesn't nest, level=big
5891 $targetLevel = 1000;
5894 if ( $node->getName() === 'h' ) {
5895 $bits = $node->splitHeading();
5896 if ( $bits['i'] == $sectionIndex ) {
5897 $targetLevel = $bits['level'];
5901 if ( $mode === 'replace' ) {
5902 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5904 $node = $node->getNextSibling();
5910 if ( $mode === 'get' ) {
5917 # Find the end of the section, including nested sections
5919 if ( $node->getName() === 'h' ) {
5920 $bits = $node->splitHeading();
5921 $curLevel = $bits['level'];
5922 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5926 if ( $mode === 'get' ) {
5927 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5929 $node = $node->getNextSibling();
5932 # Write out the remainder (in replace mode only)
5933 if ( $mode === 'replace' ) {
5934 # Output the replacement text
5935 # Add two newlines on -- trailing whitespace in $newText is conventionally
5936 # stripped by the editor, so we need both newlines to restore the paragraph gap
5937 # Only add trailing whitespace if there is newText
5938 if ( $newText != "" ) {
5939 $outText .= $newText . "\n\n";
5943 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5944 $node = $node->getNextSibling();
5948 if ( is_string( $outText ) ) {
5949 # Re-insert stripped tags
5950 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5957 * This function returns the text of a section, specified by a number ($section).
5958 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5959 * the first section before any such heading (section 0).
5961 * If a section contains subsections, these are also returned.
5963 * @param string $text Text to look in
5964 * @param string|number $sectionId Section identifier as a number or string
5965 * (e.g. 0, 1 or 'T-1').
5966 * @param string $defaultText Default to return if section is not found
5968 * @return string Text of the requested section
5970 public function getSection( $text, $sectionId, $defaultText = '' ) {
5971 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5975 * This function returns $oldtext after the content of the section
5976 * specified by $section has been replaced with $text. If the target
5977 * section does not exist, $oldtext is returned unchanged.
5979 * @param string $oldText Former text of the article
5980 * @param string|number $sectionId Section identifier as a number or string
5981 * (e.g. 0, 1 or 'T-1').
5982 * @param string $newText Replacing text
5984 * @return string Modified text
5986 public function replaceSection( $oldText, $sectionId, $newText ) {
5987 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5991 * Get the ID of the revision we are parsing
5995 public function getRevisionId() {
5996 return $this->mRevisionId
;
6000 * Get the revision object for $this->mRevisionId
6002 * @return Revision|null Either a Revision object or null
6003 * @since 1.23 (public since 1.23)
6005 public function getRevisionObject() {
6006 if ( !is_null( $this->mRevisionObject
) ) {
6007 return $this->mRevisionObject
;
6009 if ( is_null( $this->mRevisionId
) ) {
6013 $rev = call_user_func(
6014 $this->mOptions
->getCurrentRevisionCallback(), $this->getTitle(), $this
6017 # If the parse is for a new revision, then the callback should have
6018 # already been set to force the object and should match mRevisionId.
6019 # If not, try to fetch by mRevisionId for sanity.
6020 if ( $rev && $rev->getId() != $this->mRevisionId
) {
6021 $rev = Revision
::newFromId( $this->mRevisionId
);
6024 $this->mRevisionObject
= $rev;
6026 return $this->mRevisionObject
;
6030 * Get the timestamp associated with the current revision, adjusted for
6031 * the default server-local timestamp
6034 public function getRevisionTimestamp() {
6035 if ( is_null( $this->mRevisionTimestamp
) ) {
6038 $revObject = $this->getRevisionObject();
6039 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
6041 # The cryptic '' timezone parameter tells to use the site-default
6042 # timezone offset instead of the user settings.
6044 # Since this value will be saved into the parser cache, served
6045 # to other users, and potentially even used inside links and such,
6046 # it needs to be consistent for all visitors.
6047 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
6050 return $this->mRevisionTimestamp
;
6054 * Get the name of the user that edited the last revision
6056 * @return string User name
6058 public function getRevisionUser() {
6059 if ( is_null( $this->mRevisionUser
) ) {
6060 $revObject = $this->getRevisionObject();
6062 # if this template is subst: the revision id will be blank,
6063 # so just use the current user's name
6065 $this->mRevisionUser
= $revObject->getUserText();
6066 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6067 $this->mRevisionUser
= $this->getUser()->getName();
6070 return $this->mRevisionUser
;
6074 * Get the size of the revision
6076 * @return int|null Revision size
6078 public function getRevisionSize() {
6079 if ( is_null( $this->mRevisionSize
) ) {
6080 $revObject = $this->getRevisionObject();
6082 # if this variable is subst: the revision id will be blank,
6083 # so just use the parser input size, because the own substituation
6084 # will change the size.
6086 $this->mRevisionSize
= $revObject->getSize();
6087 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6088 $this->mRevisionSize
= $this->mInputSize
;
6091 return $this->mRevisionSize
;
6095 * Mutator for $mDefaultSort
6097 * @param string $sort New value
6099 public function setDefaultSort( $sort ) {
6100 $this->mDefaultSort
= $sort;
6101 $this->mOutput
->setProperty( 'defaultsort', $sort );
6105 * Accessor for $mDefaultSort
6106 * Will use the empty string if none is set.
6108 * This value is treated as a prefix, so the
6109 * empty string is equivalent to sorting by
6114 public function getDefaultSort() {
6115 if ( $this->mDefaultSort
!== false ) {
6116 return $this->mDefaultSort
;
6123 * Accessor for $mDefaultSort
6124 * Unlike getDefaultSort(), will return false if none is set
6126 * @return string|bool
6128 public function getCustomDefaultSort() {
6129 return $this->mDefaultSort
;
6133 * Try to guess the section anchor name based on a wikitext fragment
6134 * presumably extracted from a heading, for example "Header" from
6137 * @param string $text
6141 public function guessSectionNameFromWikiText( $text ) {
6142 # Strip out wikitext links(they break the anchor)
6143 $text = $this->stripSectionName( $text );
6144 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6145 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
6149 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6150 * instead. For use in redirects, since IE6 interprets Redirect: headers
6151 * as something other than UTF-8 (apparently?), resulting in breakage.
6153 * @param string $text The section name
6154 * @return string An anchor
6156 public function guessLegacySectionNameFromWikiText( $text ) {
6157 # Strip out wikitext links(they break the anchor)
6158 $text = $this->stripSectionName( $text );
6159 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6160 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
6164 * Strips a text string of wikitext for use in a section anchor
6166 * Accepts a text string and then removes all wikitext from the
6167 * string and leaves only the resultant text (i.e. the result of
6168 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6169 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6170 * to create valid section anchors by mimicing the output of the
6171 * parser when headings are parsed.
6173 * @param string $text Text string to be stripped of wikitext
6174 * for use in a Section anchor
6175 * @return string Filtered text string
6177 public function stripSectionName( $text ) {
6178 # Strip internal link markup
6179 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6180 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6182 # Strip external link markup
6183 # @todo FIXME: Not tolerant to blank link text
6184 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6185 # on how many empty links there are on the page - need to figure that out.
6186 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6188 # Parse wikitext quotes (italics & bold)
6189 $text = $this->doQuotes( $text );
6192 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
6197 * strip/replaceVariables/unstrip for preprocessor regression testing
6199 * @param string $text
6200 * @param Title $title
6201 * @param ParserOptions $options
6202 * @param int $outputType
6206 public function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
6207 $magicScopeVariable = $this->lock();
6208 $this->startParse( $title, $options, $outputType, true );
6210 $text = $this->replaceVariables( $text );
6211 $text = $this->mStripState
->unstripBoth( $text );
6212 $text = Sanitizer
::removeHTMLtags( $text );
6217 * @param string $text
6218 * @param Title $title
6219 * @param ParserOptions $options
6222 public function testPst( $text, Title
$title, ParserOptions
$options ) {
6223 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6227 * @param string $text
6228 * @param Title $title
6229 * @param ParserOptions $options
6232 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
6233 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
6237 * Call a callback function on all regions of the given text that are not
6238 * inside strip markers, and replace those regions with the return value
6239 * of the callback. For example, with input:
6243 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6244 * two strings will be replaced with the value returned by the callback in
6248 * @param callable $callback
6252 public function markerSkipCallback( $s, $callback ) {
6255 while ( $i < strlen( $s ) ) {
6256 $markerStart = strpos( $s, self
::MARKER_PREFIX
, $i );
6257 if ( $markerStart === false ) {
6258 $out .= call_user_func( $callback, substr( $s, $i ) );
6261 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6262 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6263 if ( $markerEnd === false ) {
6264 $out .= substr( $s, $markerStart );
6267 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6268 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6277 * Remove any strip markers found in the given text.
6279 * @param string $text Input string
6282 public function killMarkers( $text ) {
6283 return $this->mStripState
->killMarkers( $text );
6287 * Save the parser state required to convert the given half-parsed text to
6288 * HTML. "Half-parsed" in this context means the output of
6289 * recursiveTagParse() or internalParse(). This output has strip markers
6290 * from replaceVariables (extensionSubstitution() etc.), and link
6291 * placeholders from replaceLinkHolders().
6293 * Returns an array which can be serialized and stored persistently. This
6294 * array can later be loaded into another parser instance with
6295 * unserializeHalfParsedText(). The text can then be safely incorporated into
6296 * the return value of a parser hook.
6298 * @param string $text
6302 public function serializeHalfParsedText( $text ) {
6305 'version' => self
::HALF_PARSED_VERSION
,
6306 'stripState' => $this->mStripState
->getSubState( $text ),
6307 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6313 * Load the parser state given in the $data array, which is assumed to
6314 * have been generated by serializeHalfParsedText(). The text contents is
6315 * extracted from the array, and its markers are transformed into markers
6316 * appropriate for the current Parser instance. This transformed text is
6317 * returned, and can be safely included in the return value of a parser
6320 * If the $data array has been stored persistently, the caller should first
6321 * check whether it is still valid, by calling isValidHalfParsedText().
6323 * @param array $data Serialized data
6324 * @throws MWException
6327 public function unserializeHalfParsedText( $data ) {
6328 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6329 throw new MWException( __METHOD__
. ': invalid version' );
6332 # First, extract the strip state.
6333 $texts = array( $data['text'] );
6334 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6336 # Now renumber links
6337 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6339 # Should be good to go.
6344 * Returns true if the given array, presumed to be generated by
6345 * serializeHalfParsedText(), is compatible with the current version of the
6348 * @param array $data
6352 public function isValidHalfParsedText( $data ) {
6353 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6357 * Parsed a width param of imagelink like 300px or 200x300px
6359 * @param string $value
6364 public function parseWidthParam( $value ) {
6365 $parsedWidthParam = array();
6366 if ( $value === '' ) {
6367 return $parsedWidthParam;
6370 # (bug 13500) In both cases (width/height and width only),
6371 # permit trailing "px" for backward compatibility.
6372 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6373 $width = intval( $m[1] );
6374 $height = intval( $m[2] );
6375 $parsedWidthParam['width'] = $width;
6376 $parsedWidthParam['height'] = $height;
6377 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6378 $width = intval( $value );
6379 $parsedWidthParam['width'] = $width;
6381 return $parsedWidthParam;
6385 * Lock the current instance of the parser.
6387 * This is meant to stop someone from calling the parser
6388 * recursively and messing up all the strip state.
6390 * @throws MWException If parser is in a parse
6391 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6393 protected function lock() {
6394 if ( $this->mInParse
) {
6395 throw new MWException( "Parser state cleared while parsing. "
6396 . "Did you call Parser::parse recursively?" );
6398 $this->mInParse
= true;
6401 $recursiveCheck = new ScopedCallback( function() use ( $that ) {
6402 $that->mInParse
= false;
6405 return $recursiveCheck;
6409 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6411 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6412 * or if there is more than one <p/> tag in the input HTML.
6414 * @param string $html
6418 public static function stripOuterParagraph( $html ) {
6420 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6421 if ( strpos( $m[1], '</p>' ) === false ) {
6430 * Return this parser if it is not doing anything, otherwise
6431 * get a fresh parser. You can use this method by doing
6432 * $myParser = $wgParser->getFreshParser(), or more simply
6433 * $wgParser->getFreshParser()->parse( ... );
6434 * if you're unsure if $wgParser is safe to use.
6437 * @return Parser A parser object that is not parsing anything
6439 public function getFreshParser() {
6440 global $wgParserConf;
6441 if ( $this->mInParse
) {
6442 return new $wgParserConf['class']( $wgParserConf );
6449 * Set's up the PHP implementation of OOUI for use in this request
6450 * and instructs OutputPage to enable OOUI for itself.
6454 public function enableOOUI() {
6455 OutputPage
::setupOOUI();
6456 $this->mOutput
->setEnableOOUI( true );