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.
117 # Marker Suffix needs to be accessible staticly.
118 const MARKER_SUFFIX
= "-QINU\x7f";
120 # Markers used for wrapping the table of contents
121 const TOC_START
= '<mw:toc>';
122 const TOC_END
= '</mw:toc>';
125 public $mTagHooks = array();
126 public $mTransparentTagHooks = array();
127 public $mFunctionHooks = array();
128 public $mFunctionSynonyms = array( 0 => array(), 1 => array() );
129 public $mFunctionTagHooks = array();
130 public $mStripList = array();
131 public $mDefaultStripList = array();
132 public $mVarCache = array();
133 public $mImageParams = array();
134 public $mImageParamsMagicArray = array();
135 public $mMarkerIndex = 0;
136 public $mFirstCall = true;
138 # Initialised by initialiseVariables()
141 * @var MagicWordArray
146 * @var MagicWordArray
149 # Initialised in constructor
150 public $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols;
152 # Cleared with clearState():
157 public $mAutonumber, $mDTopen;
164 public $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
166 * @var LinkHolderArray
168 public $mLinkHolders;
171 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
172 public $mDefaultSort;
173 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
174 public $mExpensiveFunctionCount; # number of expensive parser function calls
175 public $mShowToc, $mForceTocPosition;
180 public $mUser; # User object; only used when doing pre-save transform
183 # These are variables reset at least once per parse regardless of $clearState
193 public $mTitle; # Title context, used for self-link rendering and similar things
194 public $mOutputType; # Output type, one of the OT_xxx constants
195 public $ot; # Shortcut alias, see setOutputType()
196 public $mRevisionObject; # The revision object of the specified revision ID
197 public $mRevisionId; # ID to display in {{REVISIONID}} tags
198 public $mRevisionTimestamp; # The timestamp of the specified revision ID
199 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag
200 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
201 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp
202 public $mInputSize = false; # For {{PAGESIZE}} on current page.
210 * @var array Array with the language name of each language link (i.e. the
211 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
212 * duplicate language links to the ParserOutput.
214 public $mLangLinkLanguages;
217 * @var MapCacheLRU|null
220 * A cache of the current revisions of titles. Keys are $title->getPrefixedDbKey()
222 public $currentRevisionCache;
225 * @var bool Recursive call protection.
226 * This variable should be treated as if it were private.
228 public $mInParse = false;
230 /** @var SectionProfiler */
231 protected $mProfiler;
236 public function __construct( $conf = array() ) {
237 $this->mConf
= $conf;
238 $this->mUrlProtocols
= wfUrlProtocols();
239 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
240 self
::EXT_LINK_URL_CLASS
. '+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
241 if ( isset( $conf['preprocessorClass'] ) ) {
242 $this->mPreprocessorClass
= $conf['preprocessorClass'];
243 } elseif ( defined( 'HPHP_VERSION' ) ) {
244 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
245 $this->mPreprocessorClass
= 'Preprocessor_Hash';
246 } elseif ( extension_loaded( 'domxml' ) ) {
247 # PECL extension that conflicts with the core DOM extension (bug 13770)
248 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
249 $this->mPreprocessorClass
= 'Preprocessor_Hash';
250 } elseif ( extension_loaded( 'dom' ) ) {
251 $this->mPreprocessorClass
= 'Preprocessor_DOM';
253 $this->mPreprocessorClass
= 'Preprocessor_Hash';
255 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
259 * Reduce memory usage to reduce the impact of circular references
261 public function __destruct() {
262 if ( isset( $this->mLinkHolders
) ) {
263 unset( $this->mLinkHolders
);
265 foreach ( $this as $name => $value ) {
266 unset( $this->$name );
271 * Allow extensions to clean up when the parser is cloned
273 public function __clone() {
274 $this->mInParse
= false;
276 // Bug 56226: When you create a reference "to" an object field, that
277 // makes the object field itself be a reference too (until the other
278 // reference goes out of scope). When cloning, any field that's a
279 // reference is copied as a reference in the new object. Both of these
280 // are defined PHP5 behaviors, as inconvenient as it is for us when old
281 // hooks from PHP4 days are passing fields by reference.
282 foreach ( array( 'mStripState', 'mVarCache' ) as $k ) {
283 // Make a non-reference copy of the field, then rebind the field to
284 // reference the new copy.
290 Hooks
::run( 'ParserCloned', array( $this ) );
294 * Do various kinds of initialisation on the first call of the parser
296 public function firstCallInit() {
297 if ( !$this->mFirstCall
) {
300 $this->mFirstCall
= false;
303 CoreParserFunctions
::register( $this );
304 CoreTagHooks
::register( $this );
305 $this->initialiseVariables();
307 Hooks
::run( 'ParserFirstCallInit', array( &$this ) );
315 public function clearState() {
316 if ( $this->mFirstCall
) {
317 $this->firstCallInit();
319 $this->mOutput
= new ParserOutput
;
320 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
321 $this->mAutonumber
= 0;
322 $this->mLastSection
= '';
323 $this->mDTopen
= false;
324 $this->mIncludeCount
= array();
325 $this->mArgStack
= false;
326 $this->mInPre
= false;
327 $this->mLinkHolders
= new LinkHolderArray( $this );
329 $this->mRevisionObject
= $this->mRevisionTimestamp
=
330 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
331 $this->mVarCache
= array();
333 $this->mLangLinkLanguages
= array();
334 $this->currentRevisionCache
= null;
337 * Prefix for temporary replacement strings for the multipass parser.
338 * \x07 should never appear in input as it's disallowed in XML.
339 * Using it at the front also gives us a little extra robustness
340 * since it shouldn't match when butted up against identifier-like
343 * Must not consist of all title characters, or else it will change
344 * the behavior of <nowiki> in a link.
346 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
347 $this->mStripState
= new StripState( $this->mUniqPrefix
);
349 # Clear these on every parse, bug 4549
350 $this->mTplRedirCache
= $this->mTplDomCache
= array();
352 $this->mShowToc
= true;
353 $this->mForceTocPosition
= false;
354 $this->mIncludeSizes
= array(
358 $this->mPPNodeCount
= 0;
359 $this->mGeneratedPPNodeCount
= 0;
360 $this->mHighestExpansionDepth
= 0;
361 $this->mDefaultSort
= false;
362 $this->mHeadings
= array();
363 $this->mDoubleUnderscores
= array();
364 $this->mExpensiveFunctionCount
= 0;
367 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
368 $this->mPreprocessor
= null;
371 $this->mProfiler
= new SectionProfiler();
373 Hooks
::run( 'ParserClearState', array( &$this ) );
377 * Convert wikitext to HTML
378 * Do not call this function recursively.
380 * @param string $text Text we want to parse
381 * @param Title $title
382 * @param ParserOptions $options
383 * @param bool $linestart
384 * @param bool $clearState
385 * @param int $revid Number to pass in {{REVISIONID}}
386 * @return ParserOutput A ParserOutput
388 public function parse( $text, Title
$title, ParserOptions
$options,
389 $linestart = true, $clearState = true, $revid = null
392 * First pass--just handle <nowiki> sections, pass the rest off
393 * to internalParse() which does all the real work.
396 global $wgShowHostnames;
397 $fname = __METHOD__
. '-' . wfGetCaller();
400 $magicScopeVariable = $this->lock();
403 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
405 $this->currentRevisionCache
= null;
406 $this->mInputSize
= strlen( $text );
407 if ( $this->mOptions
->getEnableLimitReport() ) {
408 $this->mOutput
->resetParseStartTime();
411 # Remove the strip marker tag prefix from the input, if present.
413 $text = str_replace( $this->mUniqPrefix
, '', $text );
416 $oldRevisionId = $this->mRevisionId
;
417 $oldRevisionObject = $this->mRevisionObject
;
418 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
419 $oldRevisionUser = $this->mRevisionUser
;
420 $oldRevisionSize = $this->mRevisionSize
;
421 if ( $revid !== null ) {
422 $this->mRevisionId
= $revid;
423 $this->mRevisionObject
= null;
424 $this->mRevisionTimestamp
= null;
425 $this->mRevisionUser
= null;
426 $this->mRevisionSize
= null;
429 Hooks
::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
431 Hooks
::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
432 $text = $this->internalParse( $text );
433 Hooks
::run( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
435 $text = $this->internalParseHalfParsed( $text, true, $linestart );
438 * A converted title will be provided in the output object if title and
439 * content conversion are enabled, the article text does not contain
440 * a conversion-suppressing double-underscore tag, and no
441 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
442 * automatic link conversion.
444 if ( !( $options->getDisableTitleConversion()
445 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
446 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
447 ||
$this->mOutput
->getDisplayTitle() !== false )
449 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
450 if ( $convruletitle ) {
451 $this->mOutput
->setTitleText( $convruletitle );
453 $titleText = $this->getConverterLanguage()->convertTitle( $title );
454 $this->mOutput
->setTitleText( $titleText );
458 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
459 $this->limitationWarn( 'expensive-parserfunction',
460 $this->mExpensiveFunctionCount
,
461 $this->mOptions
->getExpensiveParserFunctionLimit()
465 # Information on include size limits, for the benefit of users who try to skirt them
466 if ( $this->mOptions
->getEnableLimitReport() ) {
467 $max = $this->mOptions
->getMaxIncludeSize();
469 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
470 if ( $cpuTime !== null ) {
471 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
472 sprintf( "%.3f", $cpuTime )
476 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
477 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
478 sprintf( "%.3f", $wallTime )
481 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
482 array( $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() )
484 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
485 array( $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() )
487 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
488 array( $this->mIncludeSizes
['post-expand'], $max )
490 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
491 array( $this->mIncludeSizes
['arg'], $max )
493 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
494 array( $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() )
496 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
497 array( $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() )
499 Hooks
::run( 'ParserLimitReportPrepare', array( $this, $this->mOutput
) );
501 $limitReport = "NewPP limit report\n";
502 if ( $wgShowHostnames ) {
503 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
505 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
506 if ( Hooks
::run( 'ParserLimitReportFormat',
507 array( $key, &$value, &$limitReport, false, false )
509 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
510 $valueMsg = wfMessage( array( "$key-value-text", "$key-value" ) )
511 ->inLanguage( 'en' )->useDatabase( false );
512 if ( !$valueMsg->exists() ) {
513 $valueMsg = new RawMessage( '$1' );
515 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
516 $valueMsg->params( $value );
517 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
521 // Since we're not really outputting HTML, decode the entities and
522 // then re-encode the things that need hiding inside HTML comments.
523 $limitReport = htmlspecialchars_decode( $limitReport );
524 Hooks
::run( 'ParserLimitReport', array( $this, &$limitReport ) );
526 // Sanitize for comment. Note '‐' in the replacement is U+2010,
527 // which looks much like the problematic '-'.
528 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&' ), $limitReport );
529 $text .= "\n<!-- \n$limitReport-->\n";
531 // Add on template profiling data
532 $dataByFunc = $this->mProfiler
->getFunctionStats();
533 uasort( $dataByFunc, function ( $a, $b ) {
534 return $a['real'] < $b['real']; // descending order
536 $profileReport = "Transclusion expansion time report (%,ms,calls,template)\n";
537 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
538 $profileReport .= sprintf( "%6.2f%% %8.3f %6d - %s\n",
539 $item['%real'], $item['real'], $item['calls'],
540 htmlspecialchars( $item['name'] ) );
542 $text .= "\n<!-- \n$profileReport-->\n";
544 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
545 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
546 $this->mTitle
->getPrefixedDBkey() );
549 $this->mOutput
->setText( $text );
551 $this->mRevisionId
= $oldRevisionId;
552 $this->mRevisionObject
= $oldRevisionObject;
553 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
554 $this->mRevisionUser
= $oldRevisionUser;
555 $this->mRevisionSize
= $oldRevisionSize;
556 $this->mInputSize
= false;
557 $this->currentRevisionCache
= null;
559 return $this->mOutput
;
563 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
564 * can be called from an extension tag hook.
566 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
567 * instead, which means that lists and links have not been fully parsed yet,
568 * and strip markers are still present.
570 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
572 * Use this function if you're a parser tag hook and you want to parse
573 * wikitext before or after applying additional transformations, and you
574 * intend to *return the result as hook output*, which will cause it to go
575 * through the rest of parsing process automatically.
577 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
578 * $text are not expanded
580 * @param string $text Text extension wants to have parsed
581 * @param bool|PPFrame $frame The frame to use for expanding any template variables
582 * @return string UNSAFE half-parsed HTML
584 public function recursiveTagParse( $text, $frame = false ) {
585 Hooks
::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
586 Hooks
::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
587 $text = $this->internalParse( $text, false, $frame );
592 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
593 * point can be called from an extension tag hook.
595 * The output of this function is fully-parsed HTML that is safe for output.
596 * If you're a parser tag hook, you might want to use recursiveTagParse()
599 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
600 * $text are not expanded
604 * @param string $text Text extension wants to have parsed
605 * @param bool|PPFrame $frame The frame to use for expanding any template variables
606 * @return string Fully parsed HTML
608 public function recursiveTagParseFully( $text, $frame = false ) {
609 $text = $this->recursiveTagParse( $text, $frame );
610 $text = $this->internalParseHalfParsed( $text, false );
615 * Expand templates and variables in the text, producing valid, static wikitext.
616 * Also removes comments.
617 * Do not call this function recursively.
618 * @param string $text
619 * @param Title $title
620 * @param ParserOptions $options
621 * @param int|null $revid
622 * @param bool|PPFrame $frame
623 * @return mixed|string
625 public function preprocess( $text, Title
$title = null,
626 ParserOptions
$options, $revid = null, $frame = false
628 $magicScopeVariable = $this->lock();
629 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
630 if ( $revid !== null ) {
631 $this->mRevisionId
= $revid;
633 Hooks
::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
634 Hooks
::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
635 $text = $this->replaceVariables( $text, $frame );
636 $text = $this->mStripState
->unstripBoth( $text );
641 * Recursive parser entry point that can be called from an extension tag
644 * @param string $text Text to be expanded
645 * @param bool|PPFrame $frame The frame to use for expanding any template variables
649 public function recursivePreprocess( $text, $frame = false ) {
650 $text = $this->replaceVariables( $text, $frame );
651 $text = $this->mStripState
->unstripBoth( $text );
656 * Process the wikitext for the "?preload=" feature. (bug 5210)
658 * "<noinclude>", "<includeonly>" etc. are parsed as for template
659 * transclusion, comments, templates, arguments, tags hooks and parser
660 * functions are untouched.
662 * @param string $text
663 * @param Title $title
664 * @param ParserOptions $options
665 * @param array $params
668 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = array() ) {
669 $msg = new RawMessage( $text );
670 $text = $msg->params( $params )->plain();
672 # Parser (re)initialisation
673 $magicScopeVariable = $this->lock();
674 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
676 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
677 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
678 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
679 $text = $this->mStripState
->unstripBoth( $text );
684 * Get a random string
688 public static function getRandomString() {
689 return wfRandomString( 16 );
693 * Set the current user.
694 * Should only be used when doing pre-save transform.
696 * @param User|null $user User object or null (to reset)
698 public function setUser( $user ) {
699 $this->mUser
= $user;
703 * Accessor for mUniqPrefix.
707 public function uniqPrefix() {
708 if ( !isset( $this->mUniqPrefix
) ) {
709 # @todo FIXME: This is probably *horribly wrong*
710 # LanguageConverter seems to want $wgParser's uniqPrefix, however
711 # if this is called for a parser cache hit, the parser may not
712 # have ever been initialized in the first place.
713 # Not really sure what the heck is supposed to be going on here.
715 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
717 return $this->mUniqPrefix
;
721 * Set the context title
725 public function setTitle( $t ) {
727 $t = Title
::newFromText( 'NO TITLE' );
730 if ( $t->hasFragment() ) {
731 # Strip the fragment to avoid various odd effects
732 $this->mTitle
= clone $t;
733 $this->mTitle
->setFragment( '' );
740 * Accessor for the Title object
744 public function getTitle() {
745 return $this->mTitle
;
749 * Accessor/mutator for the Title object
751 * @param Title $x Title object or null to just get the current one
754 public function Title( $x = null ) {
755 return wfSetVar( $this->mTitle
, $x );
759 * Set the output type
761 * @param int $ot New value
763 public function setOutputType( $ot ) {
764 $this->mOutputType
= $ot;
767 'html' => $ot == self
::OT_HTML
,
768 'wiki' => $ot == self
::OT_WIKI
,
769 'pre' => $ot == self
::OT_PREPROCESS
,
770 'plain' => $ot == self
::OT_PLAIN
,
775 * Accessor/mutator for the output type
777 * @param int|null $x New value or null to just get the current one
780 public function OutputType( $x = null ) {
781 return wfSetVar( $this->mOutputType
, $x );
785 * Get the ParserOutput object
787 * @return ParserOutput
789 public function getOutput() {
790 return $this->mOutput
;
794 * Get the ParserOptions object
796 * @return ParserOptions
798 public function getOptions() {
799 return $this->mOptions
;
803 * Accessor/mutator for the ParserOptions object
805 * @param ParserOptions $x New value or null to just get the current one
806 * @return ParserOptions Current ParserOptions object
808 public function Options( $x = null ) {
809 return wfSetVar( $this->mOptions
, $x );
815 public function nextLinkID() {
816 return $this->mLinkID++
;
822 public function setLinkID( $id ) {
823 $this->mLinkID
= $id;
827 * Get a language object for use in parser functions such as {{FORMATNUM:}}
830 public function getFunctionLang() {
831 return $this->getTargetLanguage();
835 * Get the target language for the content being parsed. This is usually the
836 * language that the content is in.
840 * @throws MWException
843 public function getTargetLanguage() {
844 $target = $this->mOptions
->getTargetLanguage();
846 if ( $target !== null ) {
848 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
849 return $this->mOptions
->getUserLangObj();
850 } elseif ( is_null( $this->mTitle
) ) {
851 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
854 return $this->mTitle
->getPageLanguage();
858 * Get the language object for language conversion
859 * @return Language|null
861 public function getConverterLanguage() {
862 return $this->getTargetLanguage();
866 * Get a User object either from $this->mUser, if set, or from the
867 * ParserOptions object otherwise
871 public function getUser() {
872 if ( !is_null( $this->mUser
) ) {
875 return $this->mOptions
->getUser();
879 * Get a preprocessor object
881 * @return Preprocessor
883 public function getPreprocessor() {
884 if ( !isset( $this->mPreprocessor
) ) {
885 $class = $this->mPreprocessorClass
;
886 $this->mPreprocessor
= new $class( $this );
888 return $this->mPreprocessor
;
892 * Replaces all occurrences of HTML-style comments and the given tags
893 * in the text with a random marker and returns the next text. The output
894 * parameter $matches will be an associative array filled with data in
898 * 'UNIQ-xxxxx' => array(
901 * array( 'param' => 'x' ),
902 * '<element param="x">tag content</element>' ) )
905 * @param array $elements List of element names. Comments are always extracted.
906 * @param string $text Source text string.
907 * @param array $matches Out parameter, Array: extracted tags
908 * @param string $uniq_prefix
909 * @return string Stripped text
911 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
916 $taglist = implode( '|', $elements );
917 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
919 while ( $text != '' ) {
920 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
922 if ( count( $p ) < 5 ) {
925 if ( count( $p ) > 5 ) {
939 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
940 $stripped .= $marker;
942 if ( $close === '/>' ) {
943 # Empty element tag, <tag />
948 if ( $element === '!--' ) {
951 $end = "/(<\\/$element\\s*>)/i";
953 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
955 if ( count( $q ) < 3 ) {
956 # No end tag -- let it run out to the end of the text.
965 $matches[$marker] = array( $element,
967 Sanitizer
::decodeTagAttributes( $attributes ),
968 "<$element$attributes$close$content$tail" );
974 * Get a list of strippable XML-like elements
978 public function getStripList() {
979 return $this->mStripList
;
983 * Add an item to the strip state
984 * Returns the unique tag which must be inserted into the stripped text
985 * The tag will be replaced with the original text in unstrip()
987 * @param string $text
991 public function insertStripItem( $text ) {
992 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
993 $this->mMarkerIndex++
;
994 $this->mStripState
->addGeneral( $rnd, $text );
999 * parse the wiki syntax used to render tables
1002 * @param string $text
1005 public function doTableStuff( $text ) {
1007 $lines = StringUtils
::explode( "\n", $text );
1009 $td_history = array(); # Is currently a td tag open?
1010 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
1011 $tr_history = array(); # Is currently a tr tag open?
1012 $tr_attributes = array(); # history of tr attributes
1013 $has_opened_tr = array(); # Did this table open a <tr> element?
1014 $indent_level = 0; # indent level of the table
1016 foreach ( $lines as $outLine ) {
1017 $line = trim( $outLine );
1019 if ( $line === '' ) { # empty line, go to next line
1020 $out .= $outLine . "\n";
1024 $first_character = $line[0];
1027 if ( preg_match( '/^(:*)\{\|(.*)$/', $line, $matches ) ) {
1028 # First check if we are starting a new table
1029 $indent_level = strlen( $matches[1] );
1031 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1032 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1034 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1035 array_push( $td_history, false );
1036 array_push( $last_tag_history, '' );
1037 array_push( $tr_history, false );
1038 array_push( $tr_attributes, '' );
1039 array_push( $has_opened_tr, false );
1040 } elseif ( count( $td_history ) == 0 ) {
1041 # Don't do any of the following
1042 $out .= $outLine . "\n";
1044 } elseif ( substr( $line, 0, 2 ) === '|}' ) {
1045 # We are ending a table
1046 $line = '</table>' . substr( $line, 2 );
1047 $last_tag = array_pop( $last_tag_history );
1049 if ( !array_pop( $has_opened_tr ) ) {
1050 $line = "<tr><td></td></tr>{$line}";
1053 if ( array_pop( $tr_history ) ) {
1054 $line = "</tr>{$line}";
1057 if ( array_pop( $td_history ) ) {
1058 $line = "</{$last_tag}>{$line}";
1060 array_pop( $tr_attributes );
1061 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
1062 } elseif ( substr( $line, 0, 2 ) === '|-' ) {
1063 # Now we have a table row
1064 $line = preg_replace( '#^\|-+#', '', $line );
1066 # Whats after the tag is now only attributes
1067 $attributes = $this->mStripState
->unstripBoth( $line );
1068 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1069 array_pop( $tr_attributes );
1070 array_push( $tr_attributes, $attributes );
1073 $last_tag = array_pop( $last_tag_history );
1074 array_pop( $has_opened_tr );
1075 array_push( $has_opened_tr, true );
1077 if ( array_pop( $tr_history ) ) {
1081 if ( array_pop( $td_history ) ) {
1082 $line = "</{$last_tag}>{$line}";
1086 array_push( $tr_history, false );
1087 array_push( $td_history, false );
1088 array_push( $last_tag_history, '' );
1089 } elseif ( $first_character === '|'
1090 ||
$first_character === '!'
1091 ||
substr( $line, 0, 2 ) === '|+'
1093 # This might be cell elements, td, th or captions
1094 if ( substr( $line, 0, 2 ) === '|+' ) {
1095 $first_character = '+';
1096 $line = substr( $line, 1 );
1099 $line = substr( $line, 1 );
1101 if ( $first_character === '!' ) {
1102 $line = str_replace( '!!', '||', $line );
1105 # Split up multiple cells on the same line.
1106 # FIXME : This can result in improper nesting of tags processed
1107 # by earlier parser steps, but should avoid splitting up eg
1108 # attribute values containing literal "||".
1109 $cells = StringUtils
::explodeMarkup( '||', $line );
1113 # Loop through each table cell
1114 foreach ( $cells as $cell ) {
1116 if ( $first_character !== '+' ) {
1117 $tr_after = array_pop( $tr_attributes );
1118 if ( !array_pop( $tr_history ) ) {
1119 $previous = "<tr{$tr_after}>\n";
1121 array_push( $tr_history, true );
1122 array_push( $tr_attributes, '' );
1123 array_pop( $has_opened_tr );
1124 array_push( $has_opened_tr, true );
1127 $last_tag = array_pop( $last_tag_history );
1129 if ( array_pop( $td_history ) ) {
1130 $previous = "</{$last_tag}>\n{$previous}";
1133 if ( $first_character === '|' ) {
1135 } elseif ( $first_character === '!' ) {
1137 } elseif ( $first_character === '+' ) {
1138 $last_tag = 'caption';
1143 array_push( $last_tag_history, $last_tag );
1145 # A cell could contain both parameters and data
1146 $cell_data = explode( '|', $cell, 2 );
1148 # Bug 553: Note that a '|' inside an invalid link should not
1149 # be mistaken as delimiting cell parameters
1150 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1151 $cell = "{$previous}<{$last_tag}>{$cell}";
1152 } elseif ( count( $cell_data ) == 1 ) {
1153 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1155 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1156 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1157 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1161 array_push( $td_history, true );
1164 $out .= $outLine . "\n";
1167 # Closing open td, tr && table
1168 while ( count( $td_history ) > 0 ) {
1169 if ( array_pop( $td_history ) ) {
1172 if ( array_pop( $tr_history ) ) {
1175 if ( !array_pop( $has_opened_tr ) ) {
1176 $out .= "<tr><td></td></tr>\n";
1179 $out .= "</table>\n";
1182 # Remove trailing line-ending (b/c)
1183 if ( substr( $out, -1 ) === "\n" ) {
1184 $out = substr( $out, 0, -1 );
1187 # special case: don't return empty table
1188 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1197 * Helper function for parse() that transforms wiki markup into half-parsed
1198 * HTML. Only called for $mOutputType == self::OT_HTML.
1202 * @param string $text
1203 * @param bool $isMain
1204 * @param bool $frame
1208 public function internalParse( $text, $isMain = true, $frame = false ) {
1212 # Hook to suspend the parser in this state
1213 if ( !Hooks
::run( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1217 # if $frame is provided, then use $frame for replacing any variables
1219 # use frame depth to infer how include/noinclude tags should be handled
1220 # depth=0 means this is the top-level document; otherwise it's an included document
1221 if ( !$frame->depth
) {
1224 $flag = Parser
::PTD_FOR_INCLUSION
;
1226 $dom = $this->preprocessToDom( $text, $flag );
1227 $text = $frame->expand( $dom );
1229 # if $frame is not provided, then use old-style replaceVariables
1230 $text = $this->replaceVariables( $text );
1233 Hooks
::run( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1234 $text = Sanitizer
::removeHTMLtags(
1236 array( &$this, 'attributeStripCallback' ),
1238 array_keys( $this->mTransparentTagHooks
)
1240 Hooks
::run( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1242 # Tables need to come after variable replacement for things to work
1243 # properly; putting them before other transformations should keep
1244 # exciting things like link expansions from showing up in surprising
1246 $text = $this->doTableStuff( $text );
1248 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1250 $text = $this->doDoubleUnderscore( $text );
1252 $text = $this->doHeadings( $text );
1253 $text = $this->replaceInternalLinks( $text );
1254 $text = $this->doAllQuotes( $text );
1255 $text = $this->replaceExternalLinks( $text );
1257 # replaceInternalLinks may sometimes leave behind
1258 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1259 $text = str_replace( $this->mUniqPrefix
. 'NOPARSE', '', $text );
1261 $text = $this->doMagicLinks( $text );
1262 $text = $this->formatHeadings( $text, $origText, $isMain );
1268 * Helper function for parse() that transforms half-parsed HTML into fully
1271 * @param string $text
1272 * @param bool $isMain
1273 * @param bool $linestart
1276 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1277 global $wgUseTidy, $wgAlwaysUseTidy;
1279 $text = $this->mStripState
->unstripGeneral( $text );
1281 # Clean up special characters, only run once, next-to-last before doBlockLevels
1283 # french spaces, last one Guillemet-left
1284 # only if there is something before the space
1285 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
1286 # french spaces, Guillemet-right
1287 '/(\\302\\253) /' => '\\1 ',
1288 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
1290 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
1292 $text = $this->doBlockLevels( $text, $linestart );
1294 $this->replaceLinkHolders( $text );
1297 * The input doesn't get language converted if
1299 * b) Content isn't converted
1300 * c) It's a conversion table
1301 * d) it is an interface message (which is in the user language)
1303 if ( !( $this->mOptions
->getDisableContentConversion()
1304 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
1306 if ( !$this->mOptions
->getInterfaceMessage() ) {
1307 # The position of the convert() call should not be changed. it
1308 # assumes that the links are all replaced and the only thing left
1309 # is the <nowiki> mark.
1310 $text = $this->getConverterLanguage()->convert( $text );
1314 $text = $this->mStripState
->unstripNoWiki( $text );
1317 Hooks
::run( 'ParserBeforeTidy', array( &$this, &$text ) );
1320 $text = $this->replaceTransparentTags( $text );
1321 $text = $this->mStripState
->unstripGeneral( $text );
1323 $text = Sanitizer
::normalizeCharReferences( $text );
1325 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
1326 $text = MWTidy
::tidy( $text );
1328 # attempt to sanitize at least some nesting problems
1329 # (bug #2702 and quite a few others)
1331 # ''Something [http://www.cool.com cool''] -->
1332 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1333 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1334 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1335 # fix up an anchor inside another anchor, only
1336 # at least for a single single nested link (bug 3695)
1337 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1338 '\\1\\2</a>\\3</a>\\1\\4</a>',
1339 # fix div inside inline elements- doBlockLevels won't wrap a line which
1340 # contains a div, so fix it up here; replace
1341 # div with escaped text
1342 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1343 '\\1\\3<div\\5>\\6</div>\\8\\9',
1344 # remove empty italic or bold tag pairs, some
1345 # introduced by rules above
1346 '/<([bi])><\/\\1>/' => '',
1349 $text = preg_replace(
1350 array_keys( $tidyregs ),
1351 array_values( $tidyregs ),
1356 Hooks
::run( 'ParserAfterTidy', array( &$this, &$text ) );
1363 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1364 * magic external links.
1369 * @param string $text
1373 public function doMagicLinks( $text ) {
1374 $prots = wfUrlProtocolsWithoutProtRel();
1375 $urlChar = self
::EXT_LINK_URL_CLASS
;
1376 $space = self
::SPACE_NOT_NL
; # non-newline space
1377 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1378 $spaces = "$space++"; # possessive match of 1 or more spaces
1379 $text = preg_replace_callback(
1381 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1382 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1383 (\b(?i:$prots)$urlChar+) | # m[3]: Free external links
1384 \b(?:RFC|PMID) $spaces # m[4]: RFC or PMID, capture number
1386 \bISBN $spaces ( # m[5]: ISBN, capture number
1387 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1388 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1389 [0-9Xx] # check digit
1391 )!xu", array( &$this, 'magicLinkCallback' ), $text );
1396 * @throws MWException
1398 * @return HTML|string
1400 public function magicLinkCallback( $m ) {
1401 if ( isset( $m[1] ) && $m[1] !== '' ) {
1404 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1407 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1408 # Free external link
1409 return $this->makeFreeExternalLink( $m[0] );
1410 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1412 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1415 $cssClass = 'mw-magiclink-rfc';
1417 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1419 $urlmsg = 'pubmedurl';
1420 $cssClass = 'mw-magiclink-pmid';
1423 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1424 substr( $m[0], 0, 20 ) . '"' );
1426 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1427 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass );
1428 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1431 $space = self
::SPACE_NOT_NL
; # non-newline space
1432 $isbn = preg_replace( "/$space/", ' ', $isbn );
1433 $num = strtr( $isbn, array(
1438 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1439 return '<a href="' .
1440 htmlspecialchars( $titleObj->getLocalURL() ) .
1441 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1448 * Make a free external link, given a user-supplied URL
1450 * @param string $url
1452 * @return string HTML
1455 public function makeFreeExternalLink( $url ) {
1459 # The characters '<' and '>' (which were escaped by
1460 # removeHTMLtags()) should not be included in
1461 # URLs, per RFC 2396.
1463 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1464 $trail = substr( $url, $m2[0][1] ) . $trail;
1465 $url = substr( $url, 0, $m2[0][1] );
1468 # Move trailing punctuation to $trail
1470 # If there is no left bracket, then consider right brackets fair game too
1471 if ( strpos( $url, '(' ) === false ) {
1475 $urlRev = strrev( $url );
1476 $numSepChars = strspn( $urlRev, $sep );
1477 # Don't break a trailing HTML entity by moving the ; into $trail
1478 # This is in hot code, so use substr_compare to avoid having to
1479 # create a new string object for the comparison
1480 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0) {
1481 # more optimization: instead of running preg_match with a $
1482 # anchor, which can be slow, do the match on the reversed
1483 # string starting at the desired offset.
1484 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1485 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1489 if ( $numSepChars ) {
1490 $trail = substr( $url, -$numSepChars ) . $trail;
1491 $url = substr( $url, 0, -$numSepChars );
1494 $url = Sanitizer
::cleanUrl( $url );
1496 # Is this an external image?
1497 $text = $this->maybeMakeExternalImage( $url );
1498 if ( $text === false ) {
1499 # Not an image, make a link
1500 $text = Linker
::makeExternalLink( $url,
1501 $this->getConverterLanguage()->markNoConversion( $url, true ),
1503 $this->getExternalLinkAttribs( $url ) );
1504 # Register it in the output object...
1505 # Replace unnecessary URL escape codes with their equivalent characters
1506 $pasteurized = self
::normalizeLinkUrl( $url );
1507 $this->mOutput
->addExternalLink( $pasteurized );
1509 return $text . $trail;
1513 * Parse headers and return html
1517 * @param string $text
1521 public function doHeadings( $text ) {
1522 for ( $i = 6; $i >= 1; --$i ) {
1523 $h = str_repeat( '=', $i );
1524 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1530 * Replace single quotes with HTML markup
1533 * @param string $text
1535 * @return string The altered text
1537 public function doAllQuotes( $text ) {
1539 $lines = StringUtils
::explode( "\n", $text );
1540 foreach ( $lines as $line ) {
1541 $outtext .= $this->doQuotes( $line ) . "\n";
1543 $outtext = substr( $outtext, 0, -1 );
1548 * Helper function for doAllQuotes()
1550 * @param string $text
1554 public function doQuotes( $text ) {
1555 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1556 $countarr = count( $arr );
1557 if ( $countarr == 1 ) {
1561 // First, do some preliminary work. This may shift some apostrophes from
1562 // being mark-up to being text. It also counts the number of occurrences
1563 // of bold and italics mark-ups.
1566 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1567 $thislen = strlen( $arr[$i] );
1568 // If there are ever four apostrophes, assume the first is supposed to
1569 // be text, and the remaining three constitute mark-up for bold text.
1570 // (bug 13227: ''''foo'''' turns into ' ''' foo ' ''')
1571 if ( $thislen == 4 ) {
1572 $arr[$i - 1] .= "'";
1575 } elseif ( $thislen > 5 ) {
1576 // If there are more than 5 apostrophes in a row, assume they're all
1577 // text except for the last 5.
1578 // (bug 13227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1579 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1583 // Count the number of occurrences of bold and italics mark-ups.
1584 if ( $thislen == 2 ) {
1586 } elseif ( $thislen == 3 ) {
1588 } elseif ( $thislen == 5 ) {
1594 // If there is an odd number of both bold and italics, it is likely
1595 // that one of the bold ones was meant to be an apostrophe followed
1596 // by italics. Which one we cannot know for certain, but it is more
1597 // likely to be one that has a single-letter word before it.
1598 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1599 $firstsingleletterword = -1;
1600 $firstmultiletterword = -1;
1602 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1603 if ( strlen( $arr[$i] ) == 3 ) {
1604 $x1 = substr( $arr[$i - 1], -1 );
1605 $x2 = substr( $arr[$i - 1], -2, 1 );
1606 if ( $x1 === ' ' ) {
1607 if ( $firstspace == -1 ) {
1610 } elseif ( $x2 === ' ' ) {
1611 if ( $firstsingleletterword == -1 ) {
1612 $firstsingleletterword = $i;
1613 // if $firstsingleletterword is set, we don't
1614 // look at the other options, so we can bail early.
1618 if ( $firstmultiletterword == -1 ) {
1619 $firstmultiletterword = $i;
1625 // If there is a single-letter word, use it!
1626 if ( $firstsingleletterword > -1 ) {
1627 $arr[$firstsingleletterword] = "''";
1628 $arr[$firstsingleletterword - 1] .= "'";
1629 } elseif ( $firstmultiletterword > -1 ) {
1630 // If not, but there's a multi-letter word, use that one.
1631 $arr[$firstmultiletterword] = "''";
1632 $arr[$firstmultiletterword - 1] .= "'";
1633 } elseif ( $firstspace > -1 ) {
1634 // ... otherwise use the first one that has neither.
1635 // (notice that it is possible for all three to be -1 if, for example,
1636 // there is only one pentuple-apostrophe in the line)
1637 $arr[$firstspace] = "''";
1638 $arr[$firstspace - 1] .= "'";
1642 // Now let's actually convert our apostrophic mush to HTML!
1647 foreach ( $arr as $r ) {
1648 if ( ( $i %
2 ) == 0 ) {
1649 if ( $state === 'both' ) {
1655 $thislen = strlen( $r );
1656 if ( $thislen == 2 ) {
1657 if ( $state === 'i' ) {
1660 } elseif ( $state === 'bi' ) {
1663 } elseif ( $state === 'ib' ) {
1664 $output .= '</b></i><b>';
1666 } elseif ( $state === 'both' ) {
1667 $output .= '<b><i>' . $buffer . '</i>';
1669 } else { // $state can be 'b' or ''
1673 } elseif ( $thislen == 3 ) {
1674 if ( $state === 'b' ) {
1677 } elseif ( $state === 'bi' ) {
1678 $output .= '</i></b><i>';
1680 } elseif ( $state === 'ib' ) {
1683 } elseif ( $state === 'both' ) {
1684 $output .= '<i><b>' . $buffer . '</b>';
1686 } else { // $state can be 'i' or ''
1690 } elseif ( $thislen == 5 ) {
1691 if ( $state === 'b' ) {
1692 $output .= '</b><i>';
1694 } elseif ( $state === 'i' ) {
1695 $output .= '</i><b>';
1697 } elseif ( $state === 'bi' ) {
1698 $output .= '</i></b>';
1700 } elseif ( $state === 'ib' ) {
1701 $output .= '</b></i>';
1703 } elseif ( $state === 'both' ) {
1704 $output .= '<i><b>' . $buffer . '</b></i>';
1706 } else { // ($state == '')
1714 // Now close all remaining tags. Notice that the order is important.
1715 if ( $state === 'b' ||
$state === 'ib' ) {
1718 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1721 if ( $state === 'bi' ) {
1724 // There might be lonely ''''', so make sure we have a buffer
1725 if ( $state === 'both' && $buffer ) {
1726 $output .= '<b><i>' . $buffer . '</i></b>';
1732 * Replace external links (REL)
1734 * Note: this is all very hackish and the order of execution matters a lot.
1735 * Make sure to run tests/parserTests.php if you change this code.
1739 * @param string $text
1741 * @throws MWException
1744 public function replaceExternalLinks( $text ) {
1746 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1747 if ( $bits === false ) {
1748 throw new MWException( "PCRE needs to be compiled with "
1749 . "--enable-unicode-properties in order for MediaWiki to function" );
1751 $s = array_shift( $bits );
1754 while ( $i < count( $bits ) ) {
1757 $text = $bits[$i++
];
1758 $trail = $bits[$i++
];
1760 # The characters '<' and '>' (which were escaped by
1761 # removeHTMLtags()) should not be included in
1762 # URLs, per RFC 2396.
1764 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1765 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1766 $url = substr( $url, 0, $m2[0][1] );
1769 # If the link text is an image URL, replace it with an <img> tag
1770 # This happened by accident in the original parser, but some people used it extensively
1771 $img = $this->maybeMakeExternalImage( $text );
1772 if ( $img !== false ) {
1778 # Set linktype for CSS - if URL==text, link is essentially free
1779 $linktype = ( $text === $url ) ?
'free' : 'text';
1781 # No link text, e.g. [http://domain.tld/some.link]
1782 if ( $text == '' ) {
1784 $langObj = $this->getTargetLanguage();
1785 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1786 $linktype = 'autonumber';
1788 # Have link text, e.g. [http://domain.tld/some.link text]s
1790 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1793 $text = $this->getConverterLanguage()->markNoConversion( $text );
1795 $url = Sanitizer
::cleanUrl( $url );
1797 # Use the encoded URL
1798 # This means that users can paste URLs directly into the text
1799 # Funny characters like ö aren't valid in URLs anyway
1800 # This was changed in August 2004
1801 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1802 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1804 # Register link in the output object.
1805 # Replace unnecessary URL escape codes with the referenced character
1806 # This prevents spammers from hiding links from the filters
1807 $pasteurized = self
::normalizeLinkUrl( $url );
1808 $this->mOutput
->addExternalLink( $pasteurized );
1815 * Get the rel attribute for a particular external link.
1818 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1819 * nofollow if appropriate
1820 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1821 * @return string|null Rel attribute for $url
1823 public static function getExternalLinkRel( $url = false, $title = null ) {
1824 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1825 $ns = $title ?
$title->getNamespace() : false;
1826 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1827 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1835 * Get an associative array of additional HTML attributes appropriate for a
1836 * particular external link. This currently may include rel => nofollow
1837 * (depending on configuration, namespace, and the URL's domain) and/or a
1838 * target attribute (depending on configuration).
1840 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1841 * nofollow if appropriate
1842 * @return array Associative array of HTML attributes
1844 public function getExternalLinkAttribs( $url = false ) {
1846 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1848 if ( $this->mOptions
->getExternalLinkTarget() ) {
1849 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1855 * Replace unusual escape codes in a URL with their equivalent characters
1857 * @deprecated since 1.24, use normalizeLinkUrl
1858 * @param string $url
1861 public static function replaceUnusualEscapes( $url ) {
1862 wfDeprecated( __METHOD__
, '1.24' );
1863 return self
::normalizeLinkUrl( $url );
1867 * Replace unusual escape codes in a URL with their equivalent characters
1869 * This generally follows the syntax defined in RFC 3986, with special
1870 * consideration for HTTP query strings.
1872 * @param string $url
1875 public static function normalizeLinkUrl( $url ) {
1876 # First, make sure unsafe characters are encoded
1877 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
1879 return rawurlencode( $m[0] );
1885 $end = strlen( $url );
1887 # Fragment part - 'fragment'
1888 $start = strpos( $url, '#' );
1889 if ( $start !== false && $start < $end ) {
1890 $ret = self
::normalizeUrlComponent(
1891 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
1895 # Query part - 'query' minus &=+;
1896 $start = strpos( $url, '?' );
1897 if ( $start !== false && $start < $end ) {
1898 $ret = self
::normalizeUrlComponent(
1899 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
1903 # Scheme and path part - 'pchar'
1904 # (we assume no userinfo or encoded colons in the host)
1905 $ret = self
::normalizeUrlComponent(
1906 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
1911 private static function normalizeUrlComponent( $component, $unsafe ) {
1912 $callback = function ( $matches ) use ( $unsafe ) {
1913 $char = urldecode( $matches[0] );
1914 $ord = ord( $char );
1915 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
1919 # Leave it escaped, but use uppercase for a-f
1920 return strtoupper( $matches[0] );
1923 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
1927 * make an image if it's allowed, either through the global
1928 * option, through the exception, or through the on-wiki whitelist
1930 * @param string $url
1934 private function maybeMakeExternalImage( $url ) {
1935 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1936 $imagesexception = !empty( $imagesfrom );
1938 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1939 if ( $imagesexception && is_array( $imagesfrom ) ) {
1940 $imagematch = false;
1941 foreach ( $imagesfrom as $match ) {
1942 if ( strpos( $url, $match ) === 0 ) {
1947 } elseif ( $imagesexception ) {
1948 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1950 $imagematch = false;
1953 if ( $this->mOptions
->getAllowExternalImages()
1954 ||
( $imagesexception && $imagematch )
1956 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1958 $text = Linker
::makeExternalImage( $url );
1961 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1962 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
1964 $whitelist = explode(
1966 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
1969 foreach ( $whitelist as $entry ) {
1970 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1971 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1974 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1975 # Image matches a whitelist entry
1976 $text = Linker
::makeExternalImage( $url );
1985 * Process [[ ]] wikilinks
1989 * @return string Processed text
1993 public function replaceInternalLinks( $s ) {
1994 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1999 * Process [[ ]] wikilinks (RIL)
2001 * @throws MWException
2002 * @return LinkHolderArray
2006 public function replaceInternalLinks2( &$s ) {
2007 global $wgExtraInterlanguageLinkPrefixes;
2009 static $tc = false, $e1, $e1_img;
2010 # the % is needed to support urlencoded titles as well
2012 $tc = Title
::legalChars() . '#%';
2013 # Match a link having the form [[namespace:link|alternate]]trail
2014 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2015 # Match cases where there is no "]]", which might still be images
2016 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2019 $holders = new LinkHolderArray( $this );
2021 # split the entire text string on occurrences of [[
2022 $a = StringUtils
::explode( '[[', ' ' . $s );
2023 # get the first element (all text up to first [[), and remove the space we added
2026 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2027 $s = substr( $s, 1 );
2029 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2031 if ( $useLinkPrefixExtension ) {
2032 # Match the end of a line for a word that's not followed by whitespace,
2033 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2035 $charset = $wgContLang->linkPrefixCharset();
2036 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2039 if ( is_null( $this->mTitle
) ) {
2040 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
2042 $nottalk = !$this->mTitle
->isTalkPage();
2044 if ( $useLinkPrefixExtension ) {
2046 if ( preg_match( $e2, $s, $m ) ) {
2047 $first_prefix = $m[2];
2049 $first_prefix = false;
2055 $useSubpages = $this->areSubpagesAllowed();
2057 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
2058 # Loop for each link
2059 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2060 // @codingStandardsIgnoreStart
2062 # Check for excessive memory usage
2063 if ( $holders->isBig() ) {
2065 # Do the existence check, replace the link holders and clear the array
2066 $holders->replace( $s );
2070 if ( $useLinkPrefixExtension ) {
2071 if ( preg_match( $e2, $s, $m ) ) {
2078 if ( $first_prefix ) {
2079 $prefix = $first_prefix;
2080 $first_prefix = false;
2084 $might_be_img = false;
2086 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2088 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2089 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2090 # the real problem is with the $e1 regex
2093 # Still some problems for cases where the ] is meant to be outside punctuation,
2094 # and no image is in sight. See bug 2095.
2097 && substr( $m[3], 0, 1 ) === ']'
2098 && strpos( $text, '[' ) !== false
2100 $text .= ']'; # so that replaceExternalLinks($text) works later
2101 $m[3] = substr( $m[3], 1 );
2103 # fix up urlencoded title texts
2104 if ( strpos( $m[1], '%' ) !== false ) {
2105 # Should anchors '#' also be rejected?
2106 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) );
2109 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2110 # Invalid, but might be an image with a link in its caption
2111 $might_be_img = true;
2113 if ( strpos( $m[1], '%' ) !== false ) {
2114 $m[1] = rawurldecode( $m[1] );
2117 } else { # Invalid form; output directly
2118 $s .= $prefix . '[[' . $line;
2124 # Don't allow internal links to pages containing
2125 # PROTO: where PROTO is a valid URL protocol; these
2126 # should be external links.
2127 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2128 $s .= $prefix . '[[' . $line;
2132 # Make subpage if necessary
2133 if ( $useSubpages ) {
2134 $link = $this->maybeDoSubpageLink( $origLink, $text );
2139 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2141 # Strip off leading ':'
2142 $link = substr( $link, 1 );
2145 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
2146 if ( $nt === null ) {
2147 $s .= $prefix . '[[' . $line;
2151 $ns = $nt->getNamespace();
2152 $iw = $nt->getInterwiki();
2154 if ( $might_be_img ) { # if this is actually an invalid link
2155 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2158 # look at the next 'line' to see if we can close it there
2160 $next_line = $a->current();
2161 if ( $next_line === false ||
$next_line === null ) {
2164 $m = explode( ']]', $next_line, 3 );
2165 if ( count( $m ) == 3 ) {
2166 # the first ]] closes the inner link, the second the image
2168 $text .= "[[{$m[0]}]]{$m[1]}";
2171 } elseif ( count( $m ) == 2 ) {
2172 # if there's exactly one ]] that's fine, we'll keep looking
2173 $text .= "[[{$m[0]}]]{$m[1]}";
2175 # if $next_line is invalid too, we need look no further
2176 $text .= '[[' . $next_line;
2181 # we couldn't find the end of this imageLink, so output it raw
2182 # but don't ignore what might be perfectly normal links in the text we've examined
2183 $holders->merge( $this->replaceInternalLinks2( $text ) );
2184 $s .= "{$prefix}[[$link|$text";
2185 # note: no $trail, because without an end, there *is* no trail
2188 } else { # it's not an image, so output it raw
2189 $s .= "{$prefix}[[$link|$text";
2190 # note: no $trail, because without an end, there *is* no trail
2195 $wasblank = ( $text == '' );
2199 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
2200 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2201 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2202 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2203 $text = $this->doQuotes( $text );
2206 # Link not escaped by : , create the various objects
2207 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2210 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2211 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2212 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2215 # Bug 24502: filter duplicates
2216 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2217 $this->mLangLinkLanguages
[$iw] = true;
2218 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2221 $s = rtrim( $s . $prefix );
2222 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2226 if ( $ns == NS_FILE
) {
2227 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2229 # if no parameters were passed, $text
2230 # becomes something like "File:Foo.png",
2231 # which we don't want to pass on to the
2235 # recursively parse links inside the image caption
2236 # actually, this will parse them in any other parameters, too,
2237 # but it might be hard to fix that, and it doesn't matter ATM
2238 $text = $this->replaceExternalLinks( $text );
2239 $holders->merge( $this->replaceInternalLinks2( $text ) );
2241 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2242 $s .= $prefix . $this->armorLinks(
2243 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2245 $s .= $prefix . $trail;
2250 if ( $ns == NS_CATEGORY
) {
2251 $s = rtrim( $s . "\n" ); # bug 87
2254 $sortkey = $this->getDefaultSort();
2258 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2259 $sortkey = str_replace( "\n", '', $sortkey );
2260 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2261 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2264 * Strip the whitespace Category links produce, see bug 87
2266 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2272 # Self-link checking. For some languages, variants of the title are checked in
2273 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2274 # for linking to a different variant.
2275 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2276 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2280 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2281 # @todo FIXME: Should do batch file existence checks, see comment below
2282 if ( $ns == NS_MEDIA
) {
2283 # Give extensions a chance to select the file revision for us
2286 Hooks
::run( 'BeforeParserFetchFileAndTitle',
2287 array( $this, $nt, &$options, &$descQuery ) );
2288 # Fetch and register the file (file title may be different via hooks)
2289 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2290 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2291 $s .= $prefix . $this->armorLinks(
2292 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2296 # Some titles, such as valid special pages or files in foreign repos, should
2297 # be shown as bluelinks even though they're not included in the page table
2299 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2300 # batch file existence checks for NS_FILE and NS_MEDIA
2301 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2302 $this->mOutput
->addLink( $nt );
2303 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2305 # Links will be added to the output link list after checking
2306 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2313 * Render a forced-blue link inline; protect against double expansion of
2314 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2315 * Since this little disaster has to split off the trail text to avoid
2316 * breaking URLs in the following text without breaking trails on the
2317 * wiki links, it's been made into a horrible function.
2320 * @param string $text
2321 * @param array|string $query
2322 * @param string $trail
2323 * @param string $prefix
2324 * @return string HTML-wikitext mix oh yuck
2326 public function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2327 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2329 if ( is_string( $query ) ) {
2330 $query = wfCgiToArray( $query );
2332 if ( $text == '' ) {
2333 $text = htmlspecialchars( $nt->getPrefixedText() );
2336 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2338 return $this->armorLinks( $link ) . $trail;
2342 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2343 * going to go through further parsing steps before inline URL expansion.
2345 * Not needed quite as much as it used to be since free links are a bit
2346 * more sensible these days. But bracketed links are still an issue.
2348 * @param string $text More-or-less HTML
2349 * @return string Less-or-more HTML with NOPARSE bits
2351 public function armorLinks( $text ) {
2352 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2353 "{$this->mUniqPrefix}NOPARSE$1", $text );
2357 * Return true if subpage links should be expanded on this page.
2360 public function areSubpagesAllowed() {
2361 # Some namespaces don't allow subpages
2362 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2366 * Handle link to subpage if necessary
2368 * @param string $target The source of the link
2369 * @param string &$text The link text, modified as necessary
2370 * @return string The full name of the link
2373 public function maybeDoSubpageLink( $target, &$text ) {
2374 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2378 * Used by doBlockLevels()
2383 public function closeParagraph() {
2385 if ( $this->mLastSection
!= '' ) {
2386 $result = '</' . $this->mLastSection
. ">\n";
2388 $this->mInPre
= false;
2389 $this->mLastSection
= '';
2394 * getCommon() returns the length of the longest common substring
2395 * of both arguments, starting at the beginning of both.
2398 * @param string $st1
2399 * @param string $st2
2403 public function getCommon( $st1, $st2 ) {
2404 $fl = strlen( $st1 );
2405 $shorter = strlen( $st2 );
2406 if ( $fl < $shorter ) {
2410 for ( $i = 0; $i < $shorter; ++
$i ) {
2411 if ( $st1[$i] != $st2[$i] ) {
2419 * These next three functions open, continue, and close the list
2420 * element appropriate to the prefix character passed into them.
2423 * @param string $char
2427 public function openList( $char ) {
2428 $result = $this->closeParagraph();
2430 if ( '*' === $char ) {
2431 $result .= "<ul><li>";
2432 } elseif ( '#' === $char ) {
2433 $result .= "<ol><li>";
2434 } elseif ( ':' === $char ) {
2435 $result .= "<dl><dd>";
2436 } elseif ( ';' === $char ) {
2437 $result .= "<dl><dt>";
2438 $this->mDTopen
= true;
2440 $result = '<!-- ERR 1 -->';
2448 * @param string $char
2453 public function nextItem( $char ) {
2454 if ( '*' === $char ||
'#' === $char ) {
2455 return "</li>\n<li>";
2456 } elseif ( ':' === $char ||
';' === $char ) {
2458 if ( $this->mDTopen
) {
2461 if ( ';' === $char ) {
2462 $this->mDTopen
= true;
2463 return $close . '<dt>';
2465 $this->mDTopen
= false;
2466 return $close . '<dd>';
2469 return '<!-- ERR 2 -->';
2474 * @param string $char
2479 public function closeList( $char ) {
2480 if ( '*' === $char ) {
2481 $text = "</li></ul>";
2482 } elseif ( '#' === $char ) {
2483 $text = "</li></ol>";
2484 } elseif ( ':' === $char ) {
2485 if ( $this->mDTopen
) {
2486 $this->mDTopen
= false;
2487 $text = "</dt></dl>";
2489 $text = "</dd></dl>";
2492 return '<!-- ERR 3 -->';
2499 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2501 * @param string $text
2502 * @param bool $linestart Whether or not this is at the start of a line.
2504 * @return string The lists rendered as HTML
2506 public function doBlockLevels( $text, $linestart ) {
2508 # Parsing through the text line by line. The main thing
2509 # happening here is handling of block-level elements p, pre,
2510 # and making lists from lines starting with * # : etc.
2512 $textLines = StringUtils
::explode( "\n", $text );
2514 $lastPrefix = $output = '';
2515 $this->mDTopen
= $inBlockElem = false;
2517 $paragraphStack = false;
2518 $inBlockquote = false;
2520 foreach ( $textLines as $oLine ) {
2522 if ( !$linestart ) {
2532 $lastPrefixLength = strlen( $lastPrefix );
2533 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2534 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2535 # If not in a <pre> element, scan for and figure out what prefixes are there.
2536 if ( !$this->mInPre
) {
2537 # Multiple prefixes may abut each other for nested lists.
2538 $prefixLength = strspn( $oLine, '*#:;' );
2539 $prefix = substr( $oLine, 0, $prefixLength );
2542 # ; and : are both from definition-lists, so they're equivalent
2543 # for the purposes of determining whether or not we need to open/close
2545 $prefix2 = str_replace( ';', ':', $prefix );
2546 $t = substr( $oLine, $prefixLength );
2547 $this->mInPre
= (bool)$preOpenMatch;
2549 # Don't interpret any other prefixes in preformatted text
2551 $prefix = $prefix2 = '';
2556 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2557 # Same as the last item, so no need to deal with nesting or opening stuff
2558 $output .= $this->nextItem( substr( $prefix, -1 ) );
2559 $paragraphStack = false;
2561 if ( substr( $prefix, -1 ) === ';' ) {
2562 # The one nasty exception: definition lists work like this:
2563 # ; title : definition text
2564 # So we check for : in the remainder text to split up the
2565 # title and definition, without b0rking links.
2567 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2569 $output .= $term . $this->nextItem( ':' );
2572 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2573 # We need to open or close prefixes, or both.
2575 # Either open or close a level...
2576 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2577 $paragraphStack = false;
2579 # Close all the prefixes which aren't shared.
2580 while ( $commonPrefixLength < $lastPrefixLength ) {
2581 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2582 --$lastPrefixLength;
2585 # Continue the current prefix if appropriate.
2586 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2587 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2590 # Open prefixes where appropriate.
2591 if ( $lastPrefix && $prefixLength > $commonPrefixLength ) {
2594 while ( $prefixLength > $commonPrefixLength ) {
2595 $char = substr( $prefix, $commonPrefixLength, 1 );
2596 $output .= $this->openList( $char );
2598 if ( ';' === $char ) {
2599 # @todo FIXME: This is dupe of code above
2600 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2602 $output .= $term . $this->nextItem( ':' );
2605 ++
$commonPrefixLength;
2607 if ( !$prefixLength && $lastPrefix ) {
2610 $lastPrefix = $prefix2;
2613 # If we have no prefixes, go to paragraph mode.
2614 if ( 0 == $prefixLength ) {
2615 # No prefix (not in list)--go to paragraph mode
2616 # XXX: use a stack for nestable elements like span, table and div
2617 $openmatch = preg_match(
2618 '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|'
2619 . '<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS',
2622 $closematch = preg_match(
2623 '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'
2624 . '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|<\\/mw:|'
2625 . $this->mUniqPrefix
2626 . '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS',
2630 if ( $openmatch ||
$closematch ) {
2631 $paragraphStack = false;
2632 # @todo bug 5718: paragraph closed
2633 $output .= $this->closeParagraph();
2634 if ( $preOpenMatch && !$preCloseMatch ) {
2635 $this->mInPre
= true;
2638 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t, $bqMatch, PREG_OFFSET_CAPTURE
, $bqOffset ) ) {
2639 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
2640 $bqOffset = $bqMatch[0][1] +
strlen( $bqMatch[0][0] );
2642 $inBlockElem = !$closematch;
2643 } elseif ( !$inBlockElem && !$this->mInPre
) {
2644 if ( ' ' == substr( $t, 0, 1 )
2645 && ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' )
2649 if ( $this->mLastSection
!== 'pre' ) {
2650 $paragraphStack = false;
2651 $output .= $this->closeParagraph() . '<pre>';
2652 $this->mLastSection
= 'pre';
2654 $t = substr( $t, 1 );
2657 if ( trim( $t ) === '' ) {
2658 if ( $paragraphStack ) {
2659 $output .= $paragraphStack . '<br />';
2660 $paragraphStack = false;
2661 $this->mLastSection
= 'p';
2663 if ( $this->mLastSection
!== 'p' ) {
2664 $output .= $this->closeParagraph();
2665 $this->mLastSection
= '';
2666 $paragraphStack = '<p>';
2668 $paragraphStack = '</p><p>';
2672 if ( $paragraphStack ) {
2673 $output .= $paragraphStack;
2674 $paragraphStack = false;
2675 $this->mLastSection
= 'p';
2676 } elseif ( $this->mLastSection
!== 'p' ) {
2677 $output .= $this->closeParagraph() . '<p>';
2678 $this->mLastSection
= 'p';
2684 # somewhere above we forget to get out of pre block (bug 785)
2685 if ( $preCloseMatch && $this->mInPre
) {
2686 $this->mInPre
= false;
2688 if ( $paragraphStack === false ) {
2690 if ( $prefixLength === 0 ) {
2695 while ( $prefixLength ) {
2696 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2698 if ( !$prefixLength ) {
2702 if ( $this->mLastSection
!= '' ) {
2703 $output .= '</' . $this->mLastSection
. '>';
2704 $this->mLastSection
= '';
2711 * Split up a string on ':', ignoring any occurrences inside tags
2712 * to prevent illegal overlapping.
2714 * @param string $str The string to split
2715 * @param string &$before Set to everything before the ':'
2716 * @param string &$after Set to everything after the ':'
2717 * @throws MWException
2718 * @return string The position of the ':', or false if none found
2720 public function findColonNoLinks( $str, &$before, &$after ) {
2722 $pos = strpos( $str, ':' );
2723 if ( $pos === false ) {
2728 $lt = strpos( $str, '<' );
2729 if ( $lt === false ||
$lt > $pos ) {
2730 # Easy; no tag nesting to worry about
2731 $before = substr( $str, 0, $pos );
2732 $after = substr( $str, $pos +
1 );
2736 # Ugly state machine to walk through avoiding tags.
2737 $state = self
::COLON_STATE_TEXT
;
2739 $len = strlen( $str );
2740 for ( $i = 0; $i < $len; $i++
) {
2744 # (Using the number is a performance hack for common cases)
2745 case 0: # self::COLON_STATE_TEXT:
2748 # Could be either a <start> tag or an </end> tag
2749 $state = self
::COLON_STATE_TAGSTART
;
2752 if ( $stack == 0 ) {
2754 $before = substr( $str, 0, $i );
2755 $after = substr( $str, $i +
1 );
2758 # Embedded in a tag; don't break it.
2761 # Skip ahead looking for something interesting
2762 $colon = strpos( $str, ':', $i );
2763 if ( $colon === false ) {
2764 # Nothing else interesting
2767 $lt = strpos( $str, '<', $i );
2768 if ( $stack === 0 ) {
2769 if ( $lt === false ||
$colon < $lt ) {
2771 $before = substr( $str, 0, $colon );
2772 $after = substr( $str, $colon +
1 );
2776 if ( $lt === false ) {
2777 # Nothing else interesting to find; abort!
2778 # We're nested, but there's no close tags left. Abort!
2781 # Skip ahead to next tag start
2783 $state = self
::COLON_STATE_TAGSTART
;
2786 case 1: # self::COLON_STATE_TAG:
2791 $state = self
::COLON_STATE_TEXT
;
2794 # Slash may be followed by >?
2795 $state = self
::COLON_STATE_TAGSLASH
;
2801 case 2: # self::COLON_STATE_TAGSTART:
2804 $state = self
::COLON_STATE_CLOSETAG
;
2807 $state = self
::COLON_STATE_COMMENT
;
2810 # Illegal early close? This shouldn't happen D:
2811 $state = self
::COLON_STATE_TEXT
;
2814 $state = self
::COLON_STATE_TAG
;
2817 case 3: # self::COLON_STATE_CLOSETAG:
2822 wfDebug( __METHOD__
. ": Invalid input; too many close tags\n" );
2825 $state = self
::COLON_STATE_TEXT
;
2828 case self
::COLON_STATE_TAGSLASH
:
2830 # Yes, a self-closed tag <blah/>
2831 $state = self
::COLON_STATE_TEXT
;
2833 # Probably we're jumping the gun, and this is an attribute
2834 $state = self
::COLON_STATE_TAG
;
2837 case 5: # self::COLON_STATE_COMMENT:
2839 $state = self
::COLON_STATE_COMMENTDASH
;
2842 case self
::COLON_STATE_COMMENTDASH
:
2844 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2846 $state = self
::COLON_STATE_COMMENT
;
2849 case self
::COLON_STATE_COMMENTDASHDASH
:
2851 $state = self
::COLON_STATE_TEXT
;
2853 $state = self
::COLON_STATE_COMMENT
;
2857 throw new MWException( "State machine error in " . __METHOD__
);
2861 wfDebug( __METHOD__
. ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2868 * Return value of a magic variable (like PAGENAME)
2873 * @param bool|PPFrame $frame
2875 * @throws MWException
2878 public function getVariableValue( $index, $frame = false ) {
2879 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2880 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2882 if ( is_null( $this->mTitle
) ) {
2883 // If no title set, bad things are going to happen
2884 // later. Title should always be set since this
2885 // should only be called in the middle of a parse
2886 // operation (but the unit-tests do funky stuff)
2887 throw new MWException( __METHOD__
. ' Should only be '
2888 . ' called while parsing (no title set)' );
2892 * Some of these require message or data lookups and can be
2893 * expensive to check many times.
2895 if ( Hooks
::run( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2896 if ( isset( $this->mVarCache
[$index] ) ) {
2897 return $this->mVarCache
[$index];
2901 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2902 Hooks
::run( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2904 $pageLang = $this->getFunctionLang();
2910 case 'currentmonth':
2911 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ) );
2913 case 'currentmonth1':
2914 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2916 case 'currentmonthname':
2917 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2919 case 'currentmonthnamegen':
2920 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2922 case 'currentmonthabbrev':
2923 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2926 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ) );
2929 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ) );
2932 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ) );
2935 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2937 case 'localmonthname':
2938 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2940 case 'localmonthnamegen':
2941 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2943 case 'localmonthabbrev':
2944 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2947 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ) );
2950 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ) );
2953 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2956 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2958 case 'fullpagename':
2959 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2961 case 'fullpagenamee':
2962 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2965 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2967 case 'subpagenamee':
2968 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2970 case 'rootpagename':
2971 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2973 case 'rootpagenamee':
2974 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
2977 $this->mTitle
->getRootText()
2980 case 'basepagename':
2981 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2983 case 'basepagenamee':
2984 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
2987 $this->mTitle
->getBaseText()
2990 case 'talkpagename':
2991 if ( $this->mTitle
->canTalk() ) {
2992 $talkPage = $this->mTitle
->getTalkPage();
2993 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2998 case 'talkpagenamee':
2999 if ( $this->mTitle
->canTalk() ) {
3000 $talkPage = $this->mTitle
->getTalkPage();
3001 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
3006 case 'subjectpagename':
3007 $subjPage = $this->mTitle
->getSubjectPage();
3008 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
3010 case 'subjectpagenamee':
3011 $subjPage = $this->mTitle
->getSubjectPage();
3012 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
3014 case 'pageid': // requested in bug 23427
3015 $pageid = $this->getTitle()->getArticleID();
3016 if ( $pageid == 0 ) {
3017 # 0 means the page doesn't exist in the database,
3018 # which means the user is previewing a new page.
3019 # The vary-revision flag must be set, because the magic word
3020 # will have a different value once the page is saved.
3021 $this->mOutput
->setFlag( 'vary-revision' );
3022 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
3024 $value = $pageid ?
$pageid : null;
3027 # Let the edit saving system know we should parse the page
3028 # *after* a revision ID has been assigned.
3029 $this->mOutput
->setFlag( 'vary-revision' );
3030 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
3031 $value = $this->mRevisionId
;
3034 # Let the edit saving system know we should parse the page
3035 # *after* a revision ID has been assigned. This is for null edits.
3036 $this->mOutput
->setFlag( 'vary-revision' );
3037 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
3038 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
3040 case 'revisionday2':
3041 # Let the edit saving system know we should parse the page
3042 # *after* a revision ID has been assigned. This is for null edits.
3043 $this->mOutput
->setFlag( 'vary-revision' );
3044 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
3045 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
3047 case 'revisionmonth':
3048 # Let the edit saving system know we should parse the page
3049 # *after* a revision ID has been assigned. This is for null edits.
3050 $this->mOutput
->setFlag( 'vary-revision' );
3051 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
3052 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
3054 case 'revisionmonth1':
3055 # Let the edit saving system know we should parse the page
3056 # *after* a revision ID has been assigned. This is for null edits.
3057 $this->mOutput
->setFlag( 'vary-revision' );
3058 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
3059 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
3061 case 'revisionyear':
3062 # Let the edit saving system know we should parse the page
3063 # *after* a revision ID has been assigned. This is for null edits.
3064 $this->mOutput
->setFlag( 'vary-revision' );
3065 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
3066 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
3068 case 'revisiontimestamp':
3069 # Let the edit saving system know we should parse the page
3070 # *after* a revision ID has been assigned. This is for null edits.
3071 $this->mOutput
->setFlag( 'vary-revision' );
3072 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
3073 $value = $this->getRevisionTimestamp();
3075 case 'revisionuser':
3076 # Let the edit saving system know we should parse the page
3077 # *after* a revision ID has been assigned. This is for null edits.
3078 $this->mOutput
->setFlag( 'vary-revision' );
3079 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
3080 $value = $this->getRevisionUser();
3082 case 'revisionsize':
3083 # Let the edit saving system know we should parse the page
3084 # *after* a revision ID has been assigned. This is for null edits.
3085 $this->mOutput
->setFlag( 'vary-revision' );
3086 wfDebug( __METHOD__
. ": {{REVISIONSIZE}} used, setting vary-revision...\n" );
3087 $value = $this->getRevisionSize();
3090 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3093 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3095 case 'namespacenumber':
3096 $value = $this->mTitle
->getNamespace();
3099 $value = $this->mTitle
->canTalk()
3100 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
3104 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
3106 case 'subjectspace':
3107 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
3109 case 'subjectspacee':
3110 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
3112 case 'currentdayname':
3113 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
3116 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
3119 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
3122 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
3125 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3126 # int to remove the padding
3127 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
3130 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
3132 case 'localdayname':
3133 $value = $pageLang->getWeekdayName(
3134 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
3138 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
3141 $value = $pageLang->time(
3142 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
3148 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
3151 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3152 # int to remove the padding
3153 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
3156 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
3158 case 'numberofarticles':
3159 $value = $pageLang->formatNum( SiteStats
::articles() );
3161 case 'numberoffiles':
3162 $value = $pageLang->formatNum( SiteStats
::images() );
3164 case 'numberofusers':
3165 $value = $pageLang->formatNum( SiteStats
::users() );
3167 case 'numberofactiveusers':
3168 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
3170 case 'numberofpages':
3171 $value = $pageLang->formatNum( SiteStats
::pages() );
3173 case 'numberofadmins':
3174 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
3176 case 'numberofedits':
3177 $value = $pageLang->formatNum( SiteStats
::edits() );
3179 case 'currenttimestamp':
3180 $value = wfTimestamp( TS_MW
, $ts );
3182 case 'localtimestamp':
3183 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
3185 case 'currentversion':
3186 $value = SpecialVersion
::getVersion();
3189 return $wgArticlePath;
3195 return $wgServerName;
3197 return $wgScriptPath;
3199 return $wgStylePath;
3200 case 'directionmark':
3201 return $pageLang->getDirMark();
3202 case 'contentlanguage':
3203 global $wgLanguageCode;
3204 return $wgLanguageCode;
3205 case 'cascadingsources':
3206 $value = CoreParserFunctions
::cascadingsources( $this );
3211 'ParserGetVariableValueSwitch',
3212 array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame )
3219 $this->mVarCache
[$index] = $value;
3226 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3230 public function initialiseVariables() {
3231 $variableIDs = MagicWord
::getVariableIDs();
3232 $substIDs = MagicWord
::getSubstIDs();
3234 $this->mVariables
= new MagicWordArray( $variableIDs );
3235 $this->mSubstWords
= new MagicWordArray( $substIDs );
3239 * Preprocess some wikitext and return the document tree.
3240 * This is the ghost of replace_variables().
3242 * @param string $text The text to parse
3243 * @param int $flags Bitwise combination of:
3244 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
3245 * included. Default is to assume a direct page view.
3247 * The generated DOM tree must depend only on the input text and the flags.
3248 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3250 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3251 * change in the DOM tree for a given text, must be passed through the section identifier
3252 * in the section edit link and thus back to extractSections().
3254 * The output of this function is currently only cached in process memory, but a persistent
3255 * cache may be implemented at a later date which takes further advantage of these strict
3256 * dependency requirements.
3260 public function preprocessToDom( $text, $flags = 0 ) {
3261 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3266 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3272 public static function splitWhitespace( $s ) {
3273 $ltrimmed = ltrim( $s );
3274 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3275 $trimmed = rtrim( $ltrimmed );
3276 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3278 $w2 = substr( $ltrimmed, -$diff );
3282 return array( $w1, $trimmed, $w2 );
3286 * Replace magic variables, templates, and template arguments
3287 * with the appropriate text. Templates are substituted recursively,
3288 * taking care to avoid infinite loops.
3290 * Note that the substitution depends on value of $mOutputType:
3291 * self::OT_WIKI: only {{subst:}} templates
3292 * self::OT_PREPROCESS: templates but not extension tags
3293 * self::OT_HTML: all templates and extension tags
3295 * @param string $text The text to transform
3296 * @param bool|PPFrame $frame Object describing the arguments passed to the
3297 * template. Arguments may also be provided as an associative array, as
3298 * was the usual case before MW1.12. Providing arguments this way may be
3299 * useful for extensions wishing to perform variable replacement
3301 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3302 * double-brace expansion.
3305 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3306 # Is there any text? Also, Prevent too big inclusions!
3307 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3311 if ( $frame === false ) {
3312 $frame = $this->getPreprocessor()->newFrame();
3313 } elseif ( !( $frame instanceof PPFrame
) ) {
3314 wfDebug( __METHOD__
. " called using plain parameters instead of "
3315 . "a PPFrame instance. Creating custom frame.\n" );
3316 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3319 $dom = $this->preprocessToDom( $text );
3320 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3321 $text = $frame->expand( $dom, $flags );
3327 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3329 * @param array $args
3333 public static function createAssocArgs( $args ) {
3334 $assocArgs = array();
3336 foreach ( $args as $arg ) {
3337 $eqpos = strpos( $arg, '=' );
3338 if ( $eqpos === false ) {
3339 $assocArgs[$index++
] = $arg;
3341 $name = trim( substr( $arg, 0, $eqpos ) );
3342 $value = trim( substr( $arg, $eqpos +
1 ) );
3343 if ( $value === false ) {
3346 if ( $name !== false ) {
3347 $assocArgs[$name] = $value;
3356 * Warn the user when a parser limitation is reached
3357 * Will warn at most once the user per limitation type
3359 * @param string $limitationType Should be one of:
3360 * 'expensive-parserfunction' (corresponding messages:
3361 * 'expensive-parserfunction-warning',
3362 * 'expensive-parserfunction-category')
3363 * 'post-expand-template-argument' (corresponding messages:
3364 * 'post-expand-template-argument-warning',
3365 * 'post-expand-template-argument-category')
3366 * 'post-expand-template-inclusion' (corresponding messages:
3367 * 'post-expand-template-inclusion-warning',
3368 * 'post-expand-template-inclusion-category')
3369 * 'node-count-exceeded' (corresponding messages:
3370 * 'node-count-exceeded-warning',
3371 * 'node-count-exceeded-category')
3372 * 'expansion-depth-exceeded' (corresponding messages:
3373 * 'expansion-depth-exceeded-warning',
3374 * 'expansion-depth-exceeded-category')
3375 * @param string|int|null $current Current value
3376 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3377 * exceeded, provide the values (optional)
3379 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3380 # does no harm if $current and $max are present but are unnecessary for the message
3381 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3382 ->inLanguage( $this->mOptions
->getUserLangObj() )->text();
3383 $this->mOutput
->addWarning( $warning );
3384 $this->addTrackingCategory( "$limitationType-category" );
3388 * Return the text of a template, after recursively
3389 * replacing any variables or templates within the template.
3391 * @param array $piece The parts of the template
3392 * $piece['title']: the title, i.e. the part before the |
3393 * $piece['parts']: the parameter array
3394 * $piece['lineStart']: whether the brace was at the start of a line
3395 * @param PPFrame $frame The current frame, contains template arguments
3397 * @return string The text of the template
3399 public function braceSubstitution( $piece, $frame ) {
3403 // $text has been filled
3405 // wiki markup in $text should be escaped
3407 // $text is HTML, armour it against wikitext transformation
3409 // Force interwiki transclusion to be done in raw mode not rendered
3410 $forceRawInterwiki = false;
3411 // $text is a DOM node needing expansion in a child frame
3412 $isChildObj = false;
3413 // $text is a DOM node needing expansion in the current frame
3414 $isLocalObj = false;
3416 # Title object, where $text came from
3419 # $part1 is the bit before the first |, and must contain only title characters.
3420 # Various prefixes will be stripped from it later.
3421 $titleWithSpaces = $frame->expand( $piece['title'] );
3422 $part1 = trim( $titleWithSpaces );
3425 # Original title text preserved for various purposes
3426 $originalTitle = $part1;
3428 # $args is a list of argument nodes, starting from index 0, not including $part1
3429 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3430 # below won't work b/c this $args isn't an object
3431 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3433 $profileSection = null; // profile templates
3438 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3440 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3441 # Decide whether to expand template or keep wikitext as-is.
3442 if ( $this->ot
['wiki'] ) {
3443 if ( $substMatch === false ) {
3444 $literal = true; # literal when in PST with no prefix
3446 $literal = false; # expand when in PST with subst: or safesubst:
3449 if ( $substMatch == 'subst' ) {
3450 $literal = true; # literal when not in PST with plain subst:
3452 $literal = false; # expand when not in PST with safesubst: or no prefix
3456 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3463 if ( !$found && $args->getLength() == 0 ) {
3464 $id = $this->mVariables
->matchStartToEnd( $part1 );
3465 if ( $id !== false ) {
3466 $text = $this->getVariableValue( $id, $frame );
3467 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3468 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3474 # MSG, MSGNW and RAW
3477 $mwMsgnw = MagicWord
::get( 'msgnw' );
3478 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3481 # Remove obsolete MSG:
3482 $mwMsg = MagicWord
::get( 'msg' );
3483 $mwMsg->matchStartAndRemove( $part1 );
3487 $mwRaw = MagicWord
::get( 'raw' );
3488 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3489 $forceRawInterwiki = true;
3496 $colonPos = strpos( $part1, ':' );
3497 if ( $colonPos !== false ) {
3498 $func = substr( $part1, 0, $colonPos );
3499 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3500 for ( $i = 0; $i < $args->getLength(); $i++
) {
3501 $funcArgs[] = $args->item( $i );
3504 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3505 } catch ( Exception
$ex ) {
3509 # The interface for parser functions allows for extracting
3510 # flags into the local scope. Extract any forwarded flags
3516 # Finish mangling title and then check for loops.
3517 # Set $title to a Title object and $titleText to the PDBK
3520 # Split the title into page and subpage
3522 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3523 if ( $part1 !== $relative ) {
3525 $ns = $this->mTitle
->getNamespace();
3527 $title = Title
::newFromText( $part1, $ns );
3529 $titleText = $title->getPrefixedText();
3530 # Check for language variants if the template is not found
3531 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3532 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3534 # Do recursion depth check
3535 $limit = $this->mOptions
->getMaxTemplateDepth();
3536 if ( $frame->depth
>= $limit ) {
3538 $text = '<span class="error">'
3539 . wfMessage( 'parser-template-recursion-depth-warning' )
3540 ->numParams( $limit )->inContentLanguage()->text()
3546 # Load from database
3547 if ( !$found && $title ) {
3548 $profileSection = $this->mProfiler
->scopedProfileIn( $title->getPrefixedDBkey() );
3549 if ( !$title->isExternal() ) {
3550 if ( $title->isSpecialPage()
3551 && $this->mOptions
->getAllowSpecialInclusion()
3552 && $this->ot
['html']
3554 // Pass the template arguments as URL parameters.
3555 // "uselang" will have no effect since the Language object
3556 // is forced to the one defined in ParserOptions.
3557 $pageArgs = array();
3558 $argsLength = $args->getLength();
3559 for ( $i = 0; $i < $argsLength; $i++
) {
3560 $bits = $args->item( $i )->splitArg();
3561 if ( strval( $bits['index'] ) === '' ) {
3562 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3563 $value = trim( $frame->expand( $bits['value'] ) );
3564 $pageArgs[$name] = $value;
3568 // Create a new context to execute the special page
3569 $context = new RequestContext
;
3570 $context->setTitle( $title );
3571 $context->setRequest( new FauxRequest( $pageArgs ) );
3572 $context->setUser( $this->getUser() );
3573 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3574 $ret = SpecialPageFactory
::capturePath( $title, $context );
3576 $text = $context->getOutput()->getHTML();
3577 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3580 $this->disableCache();
3582 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3583 $found = false; # access denied
3584 wfDebug( __METHOD__
. ": template inclusion denied for " .
3585 $title->getPrefixedDBkey() . "\n" );
3587 list( $text, $title ) = $this->getTemplateDom( $title );
3588 if ( $text !== false ) {
3594 # If the title is valid but undisplayable, make a link to it
3595 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3596 $text = "[[:$titleText]]";
3599 } elseif ( $title->isTrans() ) {
3600 # Interwiki transclusion
3601 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3602 $text = $this->interwikiTransclude( $title, 'render' );
3605 $text = $this->interwikiTransclude( $title, 'raw' );
3606 # Preprocess it like a template
3607 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3613 # Do infinite loop check
3614 # This has to be done after redirect resolution to avoid infinite loops via redirects
3615 if ( !$frame->loopCheck( $title ) ) {
3617 $text = '<span class="error">'
3618 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3620 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3624 # If we haven't found text to substitute by now, we're done
3625 # Recover the source wikitext and return it
3627 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3628 if ( $profileSection ) {
3629 $this->mProfiler
->scopedProfileOut( $profileSection );
3631 return array( 'object' => $text );
3634 # Expand DOM-style return values in a child frame
3635 if ( $isChildObj ) {
3636 # Clean up argument array
3637 $newFrame = $frame->newChild( $args, $title );
3640 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3641 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3642 # Expansion is eligible for the empty-frame cache
3643 $text = $newFrame->cachedExpand( $titleText, $text );
3645 # Uncached expansion
3646 $text = $newFrame->expand( $text );
3649 if ( $isLocalObj && $nowiki ) {
3650 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3651 $isLocalObj = false;
3654 if ( $profileSection ) {
3655 $this->mProfiler
->scopedProfileOut( $profileSection );
3658 # Replace raw HTML by a placeholder
3660 $text = $this->insertStripItem( $text );
3661 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3662 # Escape nowiki-style return values
3663 $text = wfEscapeWikiText( $text );
3664 } elseif ( is_string( $text )
3665 && !$piece['lineStart']
3666 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3668 # Bug 529: if the template begins with a table or block-level
3669 # element, it should be treated as beginning a new line.
3670 # This behavior is somewhat controversial.
3671 $text = "\n" . $text;
3674 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3675 # Error, oversize inclusion
3676 if ( $titleText !== false ) {
3677 # Make a working, properly escaped link if possible (bug 23588)
3678 $text = "[[:$titleText]]";
3680 # This will probably not be a working link, but at least it may
3681 # provide some hint of where the problem is
3682 preg_replace( '/^:/', '', $originalTitle );
3683 $text = "[[:$originalTitle]]";
3685 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3686 . 'post-expand include size too large -->' );
3687 $this->limitationWarn( 'post-expand-template-inclusion' );
3690 if ( $isLocalObj ) {
3691 $ret = array( 'object' => $text );
3693 $ret = array( 'text' => $text );
3700 * Call a parser function and return an array with text and flags.
3702 * The returned array will always contain a boolean 'found', indicating
3703 * whether the parser function was found or not. It may also contain the
3705 * text: string|object, resulting wikitext or PP DOM object
3706 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3707 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3708 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3709 * nowiki: bool, wiki markup in $text should be escaped
3712 * @param PPFrame $frame The current frame, contains template arguments
3713 * @param string $function Function name
3714 * @param array $args Arguments to the function
3715 * @throws MWException
3718 public function callParserFunction( $frame, $function, array $args = array() ) {
3722 # Case sensitive functions
3723 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3724 $function = $this->mFunctionSynonyms
[1][$function];
3726 # Case insensitive functions
3727 $function = $wgContLang->lc( $function );
3728 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3729 $function = $this->mFunctionSynonyms
[0][$function];
3731 return array( 'found' => false );
3735 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3737 # Workaround for PHP bug 35229 and similar
3738 if ( !is_callable( $callback ) ) {
3739 throw new MWException( "Tag hook for $function is not callable\n" );
3742 $allArgs = array( &$this );
3743 if ( $flags & self
::SFH_OBJECT_ARGS
) {
3744 # Convert arguments to PPNodes and collect for appending to $allArgs
3745 $funcArgs = array();
3746 foreach ( $args as $k => $v ) {
3747 if ( $v instanceof PPNode ||
$k === 0 ) {
3750 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( array( $k => $v ) )->item( 0 );
3754 # Add a frame parameter, and pass the arguments as an array
3755 $allArgs[] = $frame;
3756 $allArgs[] = $funcArgs;
3758 # Convert arguments to plain text and append to $allArgs
3759 foreach ( $args as $k => $v ) {
3760 if ( $v instanceof PPNode
) {
3761 $allArgs[] = trim( $frame->expand( $v ) );
3762 } elseif ( is_int( $k ) && $k >= 0 ) {
3763 $allArgs[] = trim( $v );
3765 $allArgs[] = trim( "$k=$v" );
3770 $result = call_user_func_array( $callback, $allArgs );
3772 # The interface for function hooks allows them to return a wikitext
3773 # string or an array containing the string and any flags. This mungs
3774 # things around to match what this method should return.
3775 if ( !is_array( $result ) ) {
3781 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3782 $result['text'] = $result[0];
3784 unset( $result[0] );
3791 $preprocessFlags = 0;
3792 if ( isset( $result['noparse'] ) ) {
3793 $noparse = $result['noparse'];
3795 if ( isset( $result['preprocessFlags'] ) ) {
3796 $preprocessFlags = $result['preprocessFlags'];
3800 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3801 $result['isChildObj'] = true;
3808 * Get the semi-parsed DOM representation of a template with a given title,
3809 * and its redirect destination title. Cached.
3811 * @param Title $title
3815 public function getTemplateDom( $title ) {
3816 $cacheTitle = $title;
3817 $titleText = $title->getPrefixedDBkey();
3819 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3820 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3821 $title = Title
::makeTitle( $ns, $dbk );
3822 $titleText = $title->getPrefixedDBkey();
3824 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3825 return array( $this->mTplDomCache
[$titleText], $title );
3828 # Cache miss, go to the database
3829 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3831 if ( $text === false ) {
3832 $this->mTplDomCache
[$titleText] = false;
3833 return array( false, $title );
3836 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3837 $this->mTplDomCache
[$titleText] = $dom;
3839 if ( !$title->equals( $cacheTitle ) ) {
3840 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3841 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3844 return array( $dom, $title );
3848 * Fetch the current revision of a given title. Note that the revision
3849 * (and even the title) may not exist in the database, so everything
3850 * contributing to the output of the parser should use this method
3851 * where possible, rather than getting the revisions themselves. This
3852 * method also caches its results, so using it benefits performance.
3855 * @param Title $title
3858 public function fetchCurrentRevisionOfTitle( $title ) {
3859 $cacheKey = $title->getPrefixedDBkey();
3860 if ( !$this->currentRevisionCache
) {
3861 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3863 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3864 $this->currentRevisionCache
->set( $cacheKey,
3865 // Defaults to Parser::statelessFetchRevision()
3866 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3869 return $this->currentRevisionCache
->get( $cacheKey );
3873 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3874 * without passing them on to it.
3877 * @param Title $title
3878 * @param Parser|bool $parser
3881 public static function statelessFetchRevision( $title, $parser = false ) {
3882 return Revision
::newFromTitle( $title );
3886 * Fetch the unparsed text of a template and register a reference to it.
3887 * @param Title $title
3888 * @return array ( string or false, Title )
3890 public function fetchTemplateAndTitle( $title ) {
3891 // Defaults to Parser::statelessFetchTemplate()
3892 $templateCb = $this->mOptions
->getTemplateCallback();
3893 $stuff = call_user_func( $templateCb, $title, $this );
3894 $text = $stuff['text'];
3895 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3896 if ( isset( $stuff['deps'] ) ) {
3897 foreach ( $stuff['deps'] as $dep ) {
3898 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3899 if ( $dep['title']->equals( $this->getTitle() ) ) {
3900 // If we transclude ourselves, the final result
3901 // will change based on the new version of the page
3902 $this->mOutput
->setFlag( 'vary-revision' );
3906 return array( $text, $finalTitle );
3910 * Fetch the unparsed text of a template and register a reference to it.
3911 * @param Title $title
3912 * @return string|bool
3914 public function fetchTemplate( $title ) {
3915 $rv = $this->fetchTemplateAndTitle( $title );
3920 * Static function to get a template
3921 * Can be overridden via ParserOptions::setTemplateCallback().
3923 * @param Title $title
3924 * @param bool|Parser $parser
3928 public static function statelessFetchTemplate( $title, $parser = false ) {
3929 $text = $skip = false;
3930 $finalTitle = $title;
3933 # Loop to fetch the article, with up to 1 redirect
3934 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3935 # Give extensions a chance to select the revision instead
3936 $id = false; # Assume current
3937 Hooks
::run( 'BeforeParserFetchTemplateAndtitle',
3938 array( $parser, $title, &$skip, &$id ) );
3944 'page_id' => $title->getArticleID(),
3951 $rev = Revision
::newFromId( $id );
3952 } elseif ( $parser ) {
3953 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3955 $rev = Revision
::newFromTitle( $title );
3957 $rev_id = $rev ?
$rev->getId() : 0;
3958 # If there is no current revision, there is no page
3959 if ( $id === false && !$rev ) {
3960 $linkCache = LinkCache
::singleton();
3961 $linkCache->addBadLinkObj( $title );
3966 'page_id' => $title->getArticleID(),
3967 'rev_id' => $rev_id );
3968 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3969 # We fetched a rev from a different title; register it too...
3971 'title' => $rev->getTitle(),
3972 'page_id' => $rev->getPage(),
3973 'rev_id' => $rev_id );
3977 $content = $rev->getContent();
3978 $text = $content ?
$content->getWikitextForTransclusion() : null;
3980 if ( $text === false ||
$text === null ) {
3984 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3986 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3987 if ( !$message->exists() ) {
3991 $content = $message->content();
3992 $text = $message->plain();
4000 $finalTitle = $title;
4001 $title = $content->getRedirectTarget();
4005 'finalTitle' => $finalTitle,
4010 * Fetch a file and its title and register a reference to it.
4011 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4012 * @param Title $title
4013 * @param array $options Array of options to RepoGroup::findFile
4016 public function fetchFile( $title, $options = array() ) {
4017 $res = $this->fetchFileAndTitle( $title, $options );
4022 * Fetch a file and its title and register a reference to it.
4023 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4024 * @param Title $title
4025 * @param array $options Array of options to RepoGroup::findFile
4026 * @return array ( File or false, Title of file )
4028 public function fetchFileAndTitle( $title, $options = array() ) {
4029 $file = $this->fetchFileNoRegister( $title, $options );
4031 $time = $file ?
$file->getTimestamp() : false;
4032 $sha1 = $file ?
$file->getSha1() : false;
4033 # Register the file as a dependency...
4034 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4035 if ( $file && !$title->equals( $file->getTitle() ) ) {
4036 # Update fetched file title
4037 $title = $file->getTitle();
4038 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4040 return array( $file, $title );
4044 * Helper function for fetchFileAndTitle.
4046 * Also useful if you need to fetch a file but not use it yet,
4047 * for example to get the file's handler.
4049 * @param Title $title
4050 * @param array $options Array of options to RepoGroup::findFile
4053 protected function fetchFileNoRegister( $title, $options = array() ) {
4054 if ( isset( $options['broken'] ) ) {
4055 $file = false; // broken thumbnail forced by hook
4056 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
4057 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
4058 } else { // get by (name,timestamp)
4059 $file = wfFindFile( $title, $options );
4065 * Transclude an interwiki link.
4067 * @param Title $title
4068 * @param string $action
4072 public function interwikiTransclude( $title, $action ) {
4073 global $wgEnableScaryTranscluding;
4075 if ( !$wgEnableScaryTranscluding ) {
4076 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
4079 $url = $title->getFullURL( array( 'action' => $action ) );
4081 if ( strlen( $url ) > 255 ) {
4082 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
4084 return $this->fetchScaryTemplateMaybeFromCache( $url );
4088 * @param string $url
4089 * @return mixed|string
4091 public function fetchScaryTemplateMaybeFromCache( $url ) {
4092 global $wgTranscludeCacheExpiry;
4093 $dbr = wfGetDB( DB_SLAVE
);
4094 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
4095 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
4096 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
4098 return $obj->tc_contents
;
4101 $req = MWHttpRequest
::factory( $url );
4102 $status = $req->execute(); // Status object
4103 if ( $status->isOK() ) {
4104 $text = $req->getContent();
4105 } elseif ( $req->getStatus() != 200 ) {
4106 // Though we failed to fetch the content, this status is useless.
4107 return wfMessage( 'scarytranscludefailed-httpstatus' )
4108 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
4110 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
4113 $dbw = wfGetDB( DB_MASTER
);
4114 $dbw->replace( 'transcache', array( 'tc_url' ), array(
4116 'tc_time' => $dbw->timestamp( time() ),
4117 'tc_contents' => $text
4123 * Triple brace replacement -- used for template arguments
4126 * @param array $piece
4127 * @param PPFrame $frame
4131 public function argSubstitution( $piece, $frame ) {
4134 $parts = $piece['parts'];
4135 $nameWithSpaces = $frame->expand( $piece['title'] );
4136 $argName = trim( $nameWithSpaces );
4138 $text = $frame->getArgument( $argName );
4139 if ( $text === false && $parts->getLength() > 0
4140 && ( $this->ot
['html']
4142 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
4145 # No match in frame, use the supplied default
4146 $object = $parts->item( 0 )->getChildren();
4148 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
4149 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
4150 $this->limitationWarn( 'post-expand-template-argument' );
4153 if ( $text === false && $object === false ) {
4155 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
4157 if ( $error !== false ) {
4160 if ( $object !== false ) {
4161 $ret = array( 'object' => $object );
4163 $ret = array( 'text' => $text );
4170 * Return the text to be used for a given extension tag.
4171 * This is the ghost of strip().
4173 * @param array $params Associative array of parameters:
4174 * name PPNode for the tag name
4175 * attr PPNode for unparsed text where tag attributes are thought to be
4176 * attributes Optional associative array of parsed attributes
4177 * inner Contents of extension element
4178 * noClose Original text did not have a close tag
4179 * @param PPFrame $frame
4181 * @throws MWException
4184 public function extensionSubstitution( $params, $frame ) {
4185 $name = $frame->expand( $params['name'] );
4186 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
4187 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
4188 $marker = "{$this->mUniqPrefix}-$name-"
4189 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
4191 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
4192 ( $this->ot
['html'] ||
$this->ot
['pre'] );
4193 if ( $isFunctionTag ) {
4194 $markerType = 'none';
4196 $markerType = 'general';
4198 if ( $this->ot
['html'] ||
$isFunctionTag ) {
4199 $name = strtolower( $name );
4200 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
4201 if ( isset( $params['attributes'] ) ) {
4202 $attributes = $attributes +
$params['attributes'];
4205 if ( isset( $this->mTagHooks
[$name] ) ) {
4206 # Workaround for PHP bug 35229 and similar
4207 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
4208 throw new MWException( "Tag hook for $name is not callable\n" );
4210 $output = call_user_func_array( $this->mTagHooks
[$name],
4211 array( $content, $attributes, $this, $frame ) );
4212 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
4213 list( $callback, ) = $this->mFunctionTagHooks
[$name];
4214 if ( !is_callable( $callback ) ) {
4215 throw new MWException( "Tag hook for $name is not callable\n" );
4218 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
4220 $output = '<span class="error">Invalid tag extension name: ' .
4221 htmlspecialchars( $name ) . '</span>';
4224 if ( is_array( $output ) ) {
4225 # Extract flags to local scope (to override $markerType)
4227 $output = $flags[0];
4232 if ( is_null( $attrText ) ) {
4235 if ( isset( $params['attributes'] ) ) {
4236 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4237 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4238 htmlspecialchars( $attrValue ) . '"';
4241 if ( $content === null ) {
4242 $output = "<$name$attrText/>";
4244 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4245 $output = "<$name$attrText>$content$close";
4249 if ( $markerType === 'none' ) {
4251 } elseif ( $markerType === 'nowiki' ) {
4252 $this->mStripState
->addNoWiki( $marker, $output );
4253 } elseif ( $markerType === 'general' ) {
4254 $this->mStripState
->addGeneral( $marker, $output );
4256 throw new MWException( __METHOD__
. ': invalid marker type' );
4262 * Increment an include size counter
4264 * @param string $type The type of expansion
4265 * @param int $size The size of the text
4266 * @return bool False if this inclusion would take it over the maximum, true otherwise
4268 public function incrementIncludeSize( $type, $size ) {
4269 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4272 $this->mIncludeSizes
[$type] +
= $size;
4278 * Increment the expensive function count
4280 * @return bool False if the limit has been exceeded
4282 public function incrementExpensiveFunctionCount() {
4283 $this->mExpensiveFunctionCount++
;
4284 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4288 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4289 * Fills $this->mDoubleUnderscores, returns the modified text
4291 * @param string $text
4295 public function doDoubleUnderscore( $text ) {
4297 # The position of __TOC__ needs to be recorded
4298 $mw = MagicWord
::get( 'toc' );
4299 if ( $mw->match( $text ) ) {
4300 $this->mShowToc
= true;
4301 $this->mForceTocPosition
= true;
4303 # Set a placeholder. At the end we'll fill it in with the TOC.
4304 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4306 # Only keep the first one.
4307 $text = $mw->replace( '', $text );
4310 # Now match and remove the rest of them
4311 $mwa = MagicWord
::getDoubleUnderscoreArray();
4312 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4314 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4315 $this->mOutput
->mNoGallery
= true;
4317 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4318 $this->mShowToc
= false;
4320 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4321 && $this->mTitle
->getNamespace() == NS_CATEGORY
4323 $this->addTrackingCategory( 'hidden-category-category' );
4325 # (bug 8068) Allow control over whether robots index a page.
4327 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4328 # is not desirable, the last one on the page should win.
4329 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4330 $this->mOutput
->setIndexPolicy( 'noindex' );
4331 $this->addTrackingCategory( 'noindex-category' );
4333 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4334 $this->mOutput
->setIndexPolicy( 'index' );
4335 $this->addTrackingCategory( 'index-category' );
4338 # Cache all double underscores in the database
4339 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4340 $this->mOutput
->setProperty( $key, '' );
4347 * @see ParserOutput::addTrackingCategory()
4348 * @param string $msg Message key
4349 * @return bool Whether the addition was successful
4351 public function addTrackingCategory( $msg ) {
4352 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4356 * This function accomplishes several tasks:
4357 * 1) Auto-number headings if that option is enabled
4358 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4359 * 3) Add a Table of contents on the top for users who have enabled the option
4360 * 4) Auto-anchor headings
4362 * It loops through all headlines, collects the necessary data, then splits up the
4363 * string and re-inserts the newly formatted headlines.
4365 * @param string $text
4366 * @param string $origText Original, untouched wikitext
4367 * @param bool $isMain
4368 * @return mixed|string
4371 public function formatHeadings( $text, $origText, $isMain = true ) {
4372 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4374 # Inhibit editsection links if requested in the page
4375 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4376 $maybeShowEditLink = $showEditLink = false;
4378 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4379 $showEditLink = $this->mOptions
->getEditSection();
4381 if ( $showEditLink ) {
4382 $this->mOutput
->setEditSectionTokens( true );
4385 # Get all headlines for numbering them and adding funky stuff like [edit]
4386 # links - this is for later, but we need the number of headlines right now
4388 $numMatches = preg_match_all(
4389 '/<H(?P<level>[1-6])(?P<attrib>.*?' . '>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i',
4394 # if there are fewer than 4 headlines in the article, do not show TOC
4395 # unless it's been explicitly enabled.
4396 $enoughToc = $this->mShowToc
&&
4397 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4399 # Allow user to stipulate that a page should have a "new section"
4400 # link added via __NEWSECTIONLINK__
4401 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4402 $this->mOutput
->setNewSection( true );
4405 # Allow user to remove the "new section"
4406 # link via __NONEWSECTIONLINK__
4407 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4408 $this->mOutput
->hideNewSection( true );
4411 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4412 # override above conditions and always show TOC above first header
4413 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4414 $this->mShowToc
= true;
4422 # Ugh .. the TOC should have neat indentation levels which can be
4423 # passed to the skin functions. These are determined here
4427 $sublevelCount = array();
4428 $levelCount = array();
4433 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4434 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4435 $oldType = $this->mOutputType
;
4436 $this->setOutputType( self
::OT_WIKI
);
4437 $frame = $this->getPreprocessor()->newFrame();
4438 $root = $this->preprocessToDom( $origText );
4439 $node = $root->getFirstChild();
4444 foreach ( $matches[3] as $headline ) {
4445 $isTemplate = false;
4447 $sectionIndex = false;
4449 $markerMatches = array();
4450 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4451 $serial = $markerMatches[1];
4452 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4453 $isTemplate = ( $titleText != $baseTitleText );
4454 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4458 $prevlevel = $level;
4460 $level = $matches[1][$headlineCount];
4462 if ( $level > $prevlevel ) {
4463 # Increase TOC level
4465 $sublevelCount[$toclevel] = 0;
4466 if ( $toclevel < $wgMaxTocLevel ) {
4467 $prevtoclevel = $toclevel;
4468 $toc .= Linker
::tocIndent();
4471 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4472 # Decrease TOC level, find level to jump to
4474 for ( $i = $toclevel; $i > 0; $i-- ) {
4475 if ( $levelCount[$i] == $level ) {
4476 # Found last matching level
4479 } elseif ( $levelCount[$i] < $level ) {
4480 # Found first matching level below current level
4488 if ( $toclevel < $wgMaxTocLevel ) {
4489 if ( $prevtoclevel < $wgMaxTocLevel ) {
4490 # Unindent only if the previous toc level was shown :p
4491 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4492 $prevtoclevel = $toclevel;
4494 $toc .= Linker
::tocLineEnd();
4498 # No change in level, end TOC line
4499 if ( $toclevel < $wgMaxTocLevel ) {
4500 $toc .= Linker
::tocLineEnd();
4504 $levelCount[$toclevel] = $level;
4506 # count number of headlines for each level
4507 $sublevelCount[$toclevel]++
;
4509 for ( $i = 1; $i <= $toclevel; $i++
) {
4510 if ( !empty( $sublevelCount[$i] ) ) {
4514 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4519 # The safe header is a version of the header text safe to use for links
4521 # Remove link placeholders by the link text.
4522 # <!--LINK number-->
4524 # link text with suffix
4525 # Do this before unstrip since link text can contain strip markers
4526 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4528 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4529 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4531 # Strip out HTML (first regex removes any tag not allowed)
4533 # * <sup> and <sub> (bug 8393)
4536 # * <bdi> (bug 72884)
4537 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4539 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4540 # to allow setting directionality in toc items.
4541 $tocline = preg_replace(
4543 '#<(?!/?(span|sup|sub|bdi|i|b)(?: [^>]*)?>).*?' . '>#',
4544 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b))(?: .*?)?' . '>#'
4546 array( '', '<$1>' ),
4549 $tocline = trim( $tocline );
4551 # For the anchor, strip out HTML-y stuff period
4552 $safeHeadline = preg_replace( '/<.*?' . '>/', '', $safeHeadline );
4553 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4555 # Save headline for section edit hint before it's escaped
4556 $headlineHint = $safeHeadline;
4558 if ( $wgExperimentalHtmlIds ) {
4559 # For reverse compatibility, provide an id that's
4560 # HTML4-compatible, like we used to.
4562 # It may be worth noting, academically, that it's possible for
4563 # the legacy anchor to conflict with a non-legacy headline
4564 # anchor on the page. In this case likely the "correct" thing
4565 # would be to either drop the legacy anchors or make sure
4566 # they're numbered first. However, this would require people
4567 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4568 # manually, so let's not bother worrying about it.
4569 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4570 array( 'noninitial', 'legacy' ) );
4571 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4573 if ( $legacyHeadline == $safeHeadline ) {
4574 # No reason to have both (in fact, we can't)
4575 $legacyHeadline = false;
4578 $legacyHeadline = false;
4579 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4583 # HTML names must be case-insensitively unique (bug 10721).
4584 # This does not apply to Unicode characters per
4585 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4586 # @todo FIXME: We may be changing them depending on the current locale.
4587 $arrayKey = strtolower( $safeHeadline );
4588 if ( $legacyHeadline === false ) {
4589 $legacyArrayKey = false;
4591 $legacyArrayKey = strtolower( $legacyHeadline );
4594 # count how many in assoc. array so we can track dupes in anchors
4595 if ( isset( $refers[$arrayKey] ) ) {
4596 $refers[$arrayKey]++
;
4598 $refers[$arrayKey] = 1;
4600 if ( isset( $refers[$legacyArrayKey] ) ) {
4601 $refers[$legacyArrayKey]++
;
4603 $refers[$legacyArrayKey] = 1;
4606 # Don't number the heading if it is the only one (looks silly)
4607 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4608 # the two are different if the line contains a link
4609 $headline = Html
::element(
4611 array( 'class' => 'mw-headline-number' ),
4613 ) . ' ' . $headline;
4616 # Create the anchor for linking from the TOC to the section
4617 $anchor = $safeHeadline;
4618 $legacyAnchor = $legacyHeadline;
4619 if ( $refers[$arrayKey] > 1 ) {
4620 $anchor .= '_' . $refers[$arrayKey];
4622 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4623 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4625 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4626 $toc .= Linker
::tocLine( $anchor, $tocline,
4627 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4630 # Add the section to the section tree
4631 # Find the DOM node for this header
4632 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4633 while ( $node && !$noOffset ) {
4634 if ( $node->getName() === 'h' ) {
4635 $bits = $node->splitHeading();
4636 if ( $bits['i'] == $sectionIndex ) {
4640 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4641 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4642 $node = $node->getNextSibling();
4645 'toclevel' => $toclevel,
4648 'number' => $numbering,
4649 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4650 'fromtitle' => $titleText,
4651 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4652 'anchor' => $anchor,
4655 # give headline the correct <h#> tag
4656 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4657 // Output edit section links as markers with styles that can be customized by skins
4658 if ( $isTemplate ) {
4659 # Put a T flag in the section identifier, to indicate to extractSections()
4660 # that sections inside <includeonly> should be counted.
4661 $editsectionPage = $titleText;
4662 $editsectionSection = "T-$sectionIndex";
4663 $editsectionContent = null;
4665 $editsectionPage = $this->mTitle
->getPrefixedText();
4666 $editsectionSection = $sectionIndex;
4667 $editsectionContent = $headlineHint;
4669 // We use a bit of pesudo-xml for editsection markers. The
4670 // language converter is run later on. Using a UNIQ style marker
4671 // leads to the converter screwing up the tokens when it
4672 // converts stuff. And trying to insert strip tags fails too. At
4673 // this point all real inputted tags have already been escaped,
4674 // so we don't have to worry about a user trying to input one of
4675 // these markers directly. We use a page and section attribute
4676 // to stop the language converter from converting these
4677 // important bits of data, but put the headline hint inside a
4678 // content block because the language converter is supposed to
4679 // be able to convert that piece of data.
4680 // Gets replaced with html in ParserOutput::getText
4681 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4682 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4683 if ( $editsectionContent !== null ) {
4684 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4691 $head[$headlineCount] = Linker
::makeHeadline( $level,
4692 $matches['attrib'][$headlineCount], $anchor, $headline,
4693 $editlink, $legacyAnchor );
4698 $this->setOutputType( $oldType );
4700 # Never ever show TOC if no headers
4701 if ( $numVisible < 1 ) {
4706 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4707 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4709 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4710 $this->mOutput
->setTOCHTML( $toc );
4711 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4712 $this->mOutput
->addModules( 'mediawiki.toc' );
4716 $this->mOutput
->setSections( $tocraw );
4719 # split up and insert constructed headlines
4720 $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text );
4723 // build an array of document sections
4724 $sections = array();
4725 foreach ( $blocks as $block ) {
4726 // $head is zero-based, sections aren't.
4727 if ( empty( $head[$i - 1] ) ) {
4728 $sections[$i] = $block;
4730 $sections[$i] = $head[$i - 1] . $block;
4734 * Send a hook, one per section.
4735 * The idea here is to be able to make section-level DIVs, but to do so in a
4736 * lower-impact, more correct way than r50769
4739 * $section : the section number
4740 * &$sectionContent : ref to the content of the section
4741 * $showEditLinks : boolean describing whether this section has an edit link
4743 Hooks
::run( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4748 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4749 // append the TOC at the beginning
4750 // Top anchor now in skin
4751 $sections[0] = $sections[0] . $toc . "\n";
4754 $full .= join( '', $sections );
4756 if ( $this->mForceTocPosition
) {
4757 return str_replace( '<!--MWTOC-->', $toc, $full );
4764 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4765 * conversion, substituting signatures, {{subst:}} templates, etc.
4767 * @param string $text The text to transform
4768 * @param Title $title The Title object for the current article
4769 * @param User $user The User object describing the current user
4770 * @param ParserOptions $options Parsing options
4771 * @param bool $clearState Whether to clear the parser state first
4772 * @return string The altered wiki markup
4774 public function preSaveTransform( $text, Title
$title, User
$user,
4775 ParserOptions
$options, $clearState = true
4777 if ( $clearState ) {
4778 $magicScopeVariable = $this->lock();
4780 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4781 $this->setUser( $user );
4787 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4788 if ( $options->getPreSaveTransform() ) {
4789 $text = $this->pstPass2( $text, $user );
4791 $text = $this->mStripState
->unstripBoth( $text );
4793 $this->setUser( null ); #Reset
4799 * Pre-save transform helper function
4801 * @param string $text
4806 private function pstPass2( $text, $user ) {
4809 # Note: This is the timestamp saved as hardcoded wikitext to
4810 # the database, we use $wgContLang here in order to give
4811 # everyone the same signature and use the default one rather
4812 # than the one selected in each user's preferences.
4813 # (see also bug 12815)
4814 $ts = $this->mOptions
->getTimestamp();
4815 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4816 $ts = $timestamp->format( 'YmdHis' );
4817 $tzMsg = $timestamp->format( 'T' ); # might vary on DST changeover!
4819 # Allow translation of timezones through wiki. format() can return
4820 # whatever crap the system uses, localised or not, so we cannot
4821 # ship premade translations.
4822 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4823 $msg = wfMessage( $key )->inContentLanguage();
4824 if ( $msg->exists() ) {
4825 $tzMsg = $msg->text();
4828 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4830 # Variable replacement
4831 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4832 $text = $this->replaceVariables( $text );
4834 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4835 # which may corrupt this parser instance via its wfMessage()->text() call-
4838 $sigText = $this->getUserSig( $user );
4839 $text = strtr( $text, array(
4841 '~~~~' => "$sigText $d",
4845 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4846 $tc = '[' . Title
::legalChars() . ']';
4847 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4849 // [[ns:page (context)|]]
4850 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4851 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4852 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4853 // [[ns:page (context), context|]] (using either single or double-width comma)
4854 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4855 // [[|page]] (reverse pipe trick: add context from page title)
4856 $p2 = "/\[\[\\|($tc+)]]/";
4858 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4859 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4860 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4861 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4863 $t = $this->mTitle
->getText();
4865 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4866 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4867 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4868 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4870 # if there's no context, don't bother duplicating the title
4871 $text = preg_replace( $p2, '[[\\1]]', $text );
4874 # Trim trailing whitespace
4875 $text = rtrim( $text );
4881 * Fetch the user's signature text, if any, and normalize to
4882 * validated, ready-to-insert wikitext.
4883 * If you have pre-fetched the nickname or the fancySig option, you can
4884 * specify them here to save a database query.
4885 * Do not reuse this parser instance after calling getUserSig(),
4886 * as it may have changed if it's the $wgParser.
4889 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4890 * @param bool|null $fancySig whether the nicknname is the complete signature
4891 * or null to use default value
4894 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4895 global $wgMaxSigChars;
4897 $username = $user->getName();
4899 # If not given, retrieve from the user object.
4900 if ( $nickname === false ) {
4901 $nickname = $user->getOption( 'nickname' );
4904 if ( is_null( $fancySig ) ) {
4905 $fancySig = $user->getBoolOption( 'fancysig' );
4908 $nickname = $nickname == null ?
$username : $nickname;
4910 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4911 $nickname = $username;
4912 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4913 } elseif ( $fancySig !== false ) {
4914 # Sig. might contain markup; validate this
4915 if ( $this->validateSig( $nickname ) !== false ) {
4916 # Validated; clean up (if needed) and return it
4917 return $this->cleanSig( $nickname, true );
4919 # Failed to validate; fall back to the default
4920 $nickname = $username;
4921 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4925 # Make sure nickname doesnt get a sig in a sig
4926 $nickname = self
::cleanSigInSig( $nickname );
4928 # If we're still here, make it a link to the user page
4929 $userText = wfEscapeWikiText( $username );
4930 $nickText = wfEscapeWikiText( $nickname );
4931 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4933 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4934 ->title( $this->getTitle() )->text();
4938 * Check that the user's signature contains no bad XML
4940 * @param string $text
4941 * @return string|bool An expanded string, or false if invalid.
4943 public function validateSig( $text ) {
4944 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4948 * Clean up signature text
4950 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4951 * 2) Substitute all transclusions
4953 * @param string $text
4954 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4955 * @return string Signature text
4957 public function cleanSig( $text, $parsing = false ) {
4960 $magicScopeVariable = $this->lock();
4961 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4964 # Option to disable this feature
4965 if ( !$this->mOptions
->getCleanSignatures() ) {
4969 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4970 # => Move this logic to braceSubstitution()
4971 $substWord = MagicWord
::get( 'subst' );
4972 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4973 $substText = '{{' . $substWord->getSynonym( 0 );
4975 $text = preg_replace( $substRegex, $substText, $text );
4976 $text = self
::cleanSigInSig( $text );
4977 $dom = $this->preprocessToDom( $text );
4978 $frame = $this->getPreprocessor()->newFrame();
4979 $text = $frame->expand( $dom );
4982 $text = $this->mStripState
->unstripBoth( $text );
4989 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4991 * @param string $text
4992 * @return string Signature text with /~{3,5}/ removed
4994 public static function cleanSigInSig( $text ) {
4995 $text = preg_replace( '/~{3,5}/', '', $text );
5000 * Set up some variables which are usually set up in parse()
5001 * so that an external function can call some class members with confidence
5003 * @param Title|null $title
5004 * @param ParserOptions $options
5005 * @param int $outputType
5006 * @param bool $clearState
5008 public function startExternalParse( Title
$title = null, ParserOptions
$options,
5009 $outputType, $clearState = true
5011 $this->startParse( $title, $options, $outputType, $clearState );
5015 * @param Title|null $title
5016 * @param ParserOptions $options
5017 * @param int $outputType
5018 * @param bool $clearState
5020 private function startParse( Title
$title = null, ParserOptions
$options,
5021 $outputType, $clearState = true
5023 $this->setTitle( $title );
5024 $this->mOptions
= $options;
5025 $this->setOutputType( $outputType );
5026 if ( $clearState ) {
5027 $this->clearState();
5032 * Wrapper for preprocess()
5034 * @param string $text The text to preprocess
5035 * @param ParserOptions $options Options
5036 * @param Title|null $title Title object or null to use $wgTitle
5039 public function transformMsg( $text, $options, $title = null ) {
5040 static $executing = false;
5042 # Guard against infinite recursion
5053 $text = $this->preprocess( $text, $title, $options );
5060 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
5061 * The callback should have the following form:
5062 * function myParserHook( $text, $params, $parser, $frame ) { ... }
5064 * Transform and return $text. Use $parser for any required context, e.g. use
5065 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
5067 * Hooks may return extended information by returning an array, of which the
5068 * first numbered element (index 0) must be the return string, and all other
5069 * entries are extracted into local variables within an internal function
5070 * in the Parser class.
5072 * This interface (introduced r61913) appears to be undocumented, but
5073 * 'markerName' is used by some core tag hooks to override which strip
5074 * array their results are placed in. **Use great caution if attempting
5075 * this interface, as it is not documented and injudicious use could smash
5076 * private variables.**
5078 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5079 * @param callable $callback The callback function (and object) to use for the tag
5080 * @throws MWException
5081 * @return callable|null The old value of the mTagHooks array associated with the hook
5083 public function setHook( $tag, $callback ) {
5084 $tag = strtolower( $tag );
5085 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5086 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
5088 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
5089 $this->mTagHooks
[$tag] = $callback;
5090 if ( !in_array( $tag, $this->mStripList
) ) {
5091 $this->mStripList
[] = $tag;
5098 * As setHook(), but letting the contents be parsed.
5100 * Transparent tag hooks are like regular XML-style tag hooks, except they
5101 * operate late in the transformation sequence, on HTML instead of wikitext.
5103 * This is probably obsoleted by things dealing with parser frames?
5104 * The only extension currently using it is geoserver.
5107 * @todo better document or deprecate this
5109 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5110 * @param callable $callback The callback function (and object) to use for the tag
5111 * @throws MWException
5112 * @return callable|null The old value of the mTagHooks array associated with the hook
5114 public function setTransparentTagHook( $tag, $callback ) {
5115 $tag = strtolower( $tag );
5116 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5117 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
5119 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
5120 $this->mTransparentTagHooks
[$tag] = $callback;
5126 * Remove all tag hooks
5128 public function clearTagHooks() {
5129 $this->mTagHooks
= array();
5130 $this->mFunctionTagHooks
= array();
5131 $this->mStripList
= $this->mDefaultStripList
;
5135 * Create a function, e.g. {{sum:1|2|3}}
5136 * The callback function should have the form:
5137 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
5139 * Or with Parser::SFH_OBJECT_ARGS:
5140 * function myParserFunction( $parser, $frame, $args ) { ... }
5142 * The callback may either return the text result of the function, or an array with the text
5143 * in element 0, and a number of flags in the other elements. The names of the flags are
5144 * specified in the keys. Valid flags are:
5145 * found The text returned is valid, stop processing the template. This
5147 * nowiki Wiki markup in the return value should be escaped
5148 * isHTML The returned text is HTML, armour it against wikitext transformation
5150 * @param string $id The magic word ID
5151 * @param callable $callback The callback function (and object) to use
5152 * @param int $flags A combination of the following flags:
5153 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
5155 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
5156 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
5157 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
5158 * the arguments, and to control the way they are expanded.
5160 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
5161 * arguments, for instance:
5162 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
5164 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
5165 * future versions. Please call $frame->expand() on it anyway so that your code keeps
5166 * working if/when this is changed.
5168 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
5171 * Please read the documentation in includes/parser/Preprocessor.php for more information
5172 * about the methods available in PPFrame and PPNode.
5174 * @throws MWException
5175 * @return string|callable The old callback function for this name, if any
5177 public function setFunctionHook( $id, $callback, $flags = 0 ) {
5180 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
5181 $this->mFunctionHooks
[$id] = array( $callback, $flags );
5183 # Add to function cache
5184 $mw = MagicWord
::get( $id );
5186 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
5189 $synonyms = $mw->getSynonyms();
5190 $sensitive = intval( $mw->isCaseSensitive() );
5192 foreach ( $synonyms as $syn ) {
5194 if ( !$sensitive ) {
5195 $syn = $wgContLang->lc( $syn );
5198 if ( !( $flags & self
::SFH_NO_HASH
) ) {
5201 # Remove trailing colon
5202 if ( substr( $syn, -1, 1 ) === ':' ) {
5203 $syn = substr( $syn, 0, -1 );
5205 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
5211 * Get all registered function hook identifiers
5215 public function getFunctionHooks() {
5216 return array_keys( $this->mFunctionHooks
);
5220 * Create a tag function, e.g. "<test>some stuff</test>".
5221 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5222 * Unlike parser functions, their content is not preprocessed.
5223 * @param string $tag
5224 * @param callable $callback
5226 * @throws MWException
5229 public function setFunctionTagHook( $tag, $callback, $flags ) {
5230 $tag = strtolower( $tag );
5231 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5232 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5234 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
5235 $this->mFunctionTagHooks
[$tag] : null;
5236 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
5238 if ( !in_array( $tag, $this->mStripList
) ) {
5239 $this->mStripList
[] = $tag;
5246 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
5247 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5248 * Placeholders created in Skin::makeLinkObj()
5250 * @param string $text
5251 * @param int $options
5253 public function replaceLinkHolders( &$text, $options = 0 ) {
5254 $this->mLinkHolders
->replace( $text );
5258 * Replace "<!--LINK-->" link placeholders with plain text of links
5259 * (not HTML-formatted).
5261 * @param string $text
5264 public function replaceLinkHoldersText( $text ) {
5265 return $this->mLinkHolders
->replaceText( $text );
5269 * Renders an image gallery from a text with one line per image.
5270 * text labels may be given by using |-style alternative text. E.g.
5271 * Image:one.jpg|The number "1"
5272 * Image:tree.jpg|A tree
5273 * given as text will return the HTML of a gallery with two images,
5274 * labeled 'The number "1"' and
5277 * @param string $text
5278 * @param array $params
5279 * @return string HTML
5281 public function renderImageGallery( $text, $params ) {
5284 if ( isset( $params['mode'] ) ) {
5285 $mode = $params['mode'];
5289 $ig = ImageGalleryBase
::factory( $mode );
5290 } catch ( MWException
$e ) {
5291 // If invalid type set, fallback to default.
5292 $ig = ImageGalleryBase
::factory( false );
5295 $ig->setContextTitle( $this->mTitle
);
5296 $ig->setShowBytes( false );
5297 $ig->setShowFilename( false );
5298 $ig->setParser( $this );
5299 $ig->setHideBadImages();
5300 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
5302 if ( isset( $params['showfilename'] ) ) {
5303 $ig->setShowFilename( true );
5305 $ig->setShowFilename( false );
5307 if ( isset( $params['caption'] ) ) {
5308 $caption = $params['caption'];
5309 $caption = htmlspecialchars( $caption );
5310 $caption = $this->replaceInternalLinks( $caption );
5311 $ig->setCaptionHtml( $caption );
5313 if ( isset( $params['perrow'] ) ) {
5314 $ig->setPerRow( $params['perrow'] );
5316 if ( isset( $params['widths'] ) ) {
5317 $ig->setWidths( $params['widths'] );
5319 if ( isset( $params['heights'] ) ) {
5320 $ig->setHeights( $params['heights'] );
5322 $ig->setAdditionalOptions( $params );
5324 Hooks
::run( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5326 $lines = StringUtils
::explode( "\n", $text );
5327 foreach ( $lines as $line ) {
5328 # match lines like these:
5329 # Image:someimage.jpg|This is some image
5331 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5333 if ( count( $matches ) == 0 ) {
5337 if ( strpos( $matches[0], '%' ) !== false ) {
5338 $matches[1] = rawurldecode( $matches[1] );
5340 $title = Title
::newFromText( $matches[1], NS_FILE
);
5341 if ( is_null( $title ) ) {
5342 # Bogus title. Ignore these so we don't bomb out later.
5346 # We need to get what handler the file uses, to figure out parameters.
5347 # Note, a hook can overide the file name, and chose an entirely different
5348 # file (which potentially could be of a different type and have different handler).
5351 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5352 array( $this, $title, &$options, &$descQuery ) );
5353 # Don't register it now, as ImageGallery does that later.
5354 $file = $this->fetchFileNoRegister( $title, $options );
5355 $handler = $file ?
$file->getHandler() : false;
5358 'img_alt' => 'gallery-internal-alt',
5359 'img_link' => 'gallery-internal-link',
5362 $paramMap = $paramMap +
$handler->getParamMap();
5363 // We don't want people to specify per-image widths.
5364 // Additionally the width parameter would need special casing anyhow.
5365 unset( $paramMap['img_width'] );
5368 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5373 $handlerOptions = array();
5374 if ( isset( $matches[3] ) ) {
5375 // look for an |alt= definition while trying not to break existing
5376 // captions with multiple pipes (|) in it, until a more sensible grammar
5377 // is defined for images in galleries
5379 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5380 // splitting on '|' is a bit odd, and different from makeImage.
5381 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5382 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
5384 foreach ( $parameterMatches as $parameterMatch ) {
5385 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5387 $paramName = $paramMap[$magicName];
5389 switch ( $paramName ) {
5390 case 'gallery-internal-alt':
5391 $alt = $this->stripAltText( $match, false );
5393 case 'gallery-internal-link':
5394 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5395 $chars = self
::EXT_LINK_URL_CLASS
;
5396 $prots = $this->mUrlProtocols
;
5397 //check to see if link matches an absolute url, if not then it must be a wiki link.
5398 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5401 $localLinkTitle = Title
::newFromText( $linkValue );
5402 if ( $localLinkTitle !== null ) {
5403 $link = $localLinkTitle->getLinkURL();
5408 // Must be a handler specific parameter.
5409 if ( $handler->validateParam( $paramName, $match ) ) {
5410 $handlerOptions[$paramName] = $match;
5412 // Guess not. Append it to the caption.
5413 wfDebug( "$parameterMatch failed parameter validation\n" );
5414 $label .= '|' . $parameterMatch;
5419 // concatenate all other pipes
5420 $label .= '|' . $parameterMatch;
5423 // remove the first pipe
5424 $label = substr( $label, 1 );
5427 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5429 $html = $ig->toHTML();
5430 Hooks
::run( 'AfterParserFetchFileAndTitle', array( $this, $ig, &$html ) );
5435 * @param string $handler
5438 public function getImageParams( $handler ) {
5440 $handlerClass = get_class( $handler );
5444 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5445 # Initialise static lists
5446 static $internalParamNames = array(
5447 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5448 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5449 'bottom', 'text-bottom' ),
5450 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5451 'upright', 'border', 'link', 'alt', 'class' ),
5453 static $internalParamMap;
5454 if ( !$internalParamMap ) {
5455 $internalParamMap = array();
5456 foreach ( $internalParamNames as $type => $names ) {
5457 foreach ( $names as $name ) {
5458 $magicName = str_replace( '-', '_', "img_$name" );
5459 $internalParamMap[$magicName] = array( $type, $name );
5464 # Add handler params
5465 $paramMap = $internalParamMap;
5467 $handlerParamMap = $handler->getParamMap();
5468 foreach ( $handlerParamMap as $magic => $paramName ) {
5469 $paramMap[$magic] = array( 'handler', $paramName );
5472 $this->mImageParams
[$handlerClass] = $paramMap;
5473 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5475 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5479 * Parse image options text and use it to make an image
5481 * @param Title $title
5482 * @param string $options
5483 * @param LinkHolderArray|bool $holders
5484 * @return string HTML
5486 public function makeImage( $title, $options, $holders = false ) {
5487 # Check if the options text is of the form "options|alt text"
5489 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5490 # * left no resizing, just left align. label is used for alt= only
5491 # * right same, but right aligned
5492 # * none same, but not aligned
5493 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5494 # * center center the image
5495 # * frame Keep original image size, no magnify-button.
5496 # * framed Same as "frame"
5497 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5498 # * upright reduce width for upright images, rounded to full __0 px
5499 # * border draw a 1px border around the image
5500 # * alt Text for HTML alt attribute (defaults to empty)
5501 # * class Set a class for img node
5502 # * link Set the target of the image link. Can be external, interwiki, or local
5503 # vertical-align values (no % or length right now):
5513 $parts = StringUtils
::explode( "|", $options );
5515 # Give extensions a chance to select the file revision for us
5518 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5519 array( $this, $title, &$options, &$descQuery ) );
5520 # Fetch and register the file (file title may be different via hooks)
5521 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5524 $handler = $file ?
$file->getHandler() : false;
5526 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5529 $this->addTrackingCategory( 'broken-file-category' );
5532 # Process the input parameters
5534 $params = array( 'frame' => array(), 'handler' => array(),
5535 'horizAlign' => array(), 'vertAlign' => array() );
5536 $seenformat = false;
5537 foreach ( $parts as $part ) {
5538 $part = trim( $part );
5539 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5541 if ( isset( $paramMap[$magicName] ) ) {
5542 list( $type, $paramName ) = $paramMap[$magicName];
5544 # Special case; width and height come in one variable together
5545 if ( $type === 'handler' && $paramName === 'width' ) {
5546 $parsedWidthParam = $this->parseWidthParam( $value );
5547 if ( isset( $parsedWidthParam['width'] ) ) {
5548 $width = $parsedWidthParam['width'];
5549 if ( $handler->validateParam( 'width', $width ) ) {
5550 $params[$type]['width'] = $width;
5554 if ( isset( $parsedWidthParam['height'] ) ) {
5555 $height = $parsedWidthParam['height'];
5556 if ( $handler->validateParam( 'height', $height ) ) {
5557 $params[$type]['height'] = $height;
5561 # else no validation -- bug 13436
5563 if ( $type === 'handler' ) {
5564 # Validate handler parameter
5565 $validated = $handler->validateParam( $paramName, $value );
5567 # Validate internal parameters
5568 switch ( $paramName ) {
5572 # @todo FIXME: Possibly check validity here for
5573 # manualthumb? downstream behavior seems odd with
5574 # missing manual thumbs.
5576 $value = $this->stripAltText( $value, $holders );
5579 $chars = self
::EXT_LINK_URL_CLASS
;
5580 $prots = $this->mUrlProtocols
;
5581 if ( $value === '' ) {
5582 $paramName = 'no-link';
5585 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5586 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5587 $paramName = 'link-url';
5588 $this->mOutput
->addExternalLink( $value );
5589 if ( $this->mOptions
->getExternalLinkTarget() ) {
5590 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5595 $linkTitle = Title
::newFromText( $value );
5597 $paramName = 'link-title';
5598 $value = $linkTitle;
5599 $this->mOutput
->addLink( $linkTitle );
5607 // use first appearing option, discard others.
5608 $validated = ! $seenformat;
5612 # Most other things appear to be empty or numeric...
5613 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5618 $params[$type][$paramName] = $value;
5622 if ( !$validated ) {
5627 # Process alignment parameters
5628 if ( $params['horizAlign'] ) {
5629 $params['frame']['align'] = key( $params['horizAlign'] );
5631 if ( $params['vertAlign'] ) {
5632 $params['frame']['valign'] = key( $params['vertAlign'] );
5635 $params['frame']['caption'] = $caption;
5637 # Will the image be presented in a frame, with the caption below?
5638 $imageIsFramed = isset( $params['frame']['frame'] )
5639 ||
isset( $params['frame']['framed'] )
5640 ||
isset( $params['frame']['thumbnail'] )
5641 ||
isset( $params['frame']['manualthumb'] );
5643 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5644 # came to also set the caption, ordinary text after the image -- which
5645 # makes no sense, because that just repeats the text multiple times in
5646 # screen readers. It *also* came to set the title attribute.
5648 # Now that we have an alt attribute, we should not set the alt text to
5649 # equal the caption: that's worse than useless, it just repeats the
5650 # text. This is the framed/thumbnail case. If there's no caption, we
5651 # use the unnamed parameter for alt text as well, just for the time be-
5652 # ing, if the unnamed param is set and the alt param is not.
5654 # For the future, we need to figure out if we want to tweak this more,
5655 # e.g., introducing a title= parameter for the title; ignoring the un-
5656 # named parameter entirely for images without a caption; adding an ex-
5657 # plicit caption= parameter and preserving the old magic unnamed para-
5659 if ( $imageIsFramed ) { # Framed image
5660 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5661 # No caption or alt text, add the filename as the alt text so
5662 # that screen readers at least get some description of the image
5663 $params['frame']['alt'] = $title->getText();
5665 # Do not set $params['frame']['title'] because tooltips don't make sense
5667 } else { # Inline image
5668 if ( !isset( $params['frame']['alt'] ) ) {
5669 # No alt text, use the "caption" for the alt text
5670 if ( $caption !== '' ) {
5671 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5673 # No caption, fall back to using the filename for the
5675 $params['frame']['alt'] = $title->getText();
5678 # Use the "caption" for the tooltip text
5679 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5682 Hooks
::run( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5684 # Linker does the rest
5685 $time = isset( $options['time'] ) ?
$options['time'] : false;
5686 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5687 $time, $descQuery, $this->mOptions
->getThumbSize() );
5689 # Give the handler a chance to modify the parser object
5691 $handler->parserTransformHook( $this, $file );
5698 * @param string $caption
5699 * @param LinkHolderArray|bool $holders
5700 * @return mixed|string
5702 protected function stripAltText( $caption, $holders ) {
5703 # Strip bad stuff out of the title (tooltip). We can't just use
5704 # replaceLinkHoldersText() here, because if this function is called
5705 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5707 $tooltip = $holders->replaceText( $caption );
5709 $tooltip = $this->replaceLinkHoldersText( $caption );
5712 # make sure there are no placeholders in thumbnail attributes
5713 # that are later expanded to html- so expand them now and
5715 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5716 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5722 * Set a flag in the output object indicating that the content is dynamic and
5723 * shouldn't be cached.
5725 public function disableCache() {
5726 wfDebug( "Parser output marked as uncacheable.\n" );
5727 if ( !$this->mOutput
) {
5728 throw new MWException( __METHOD__
.
5729 " can only be called when actually parsing something" );
5731 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5732 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5736 * Callback from the Sanitizer for expanding items found in HTML attribute
5737 * values, so they can be safely tested and escaped.
5739 * @param string $text
5740 * @param bool|PPFrame $frame
5743 public function attributeStripCallback( &$text, $frame = false ) {
5744 $text = $this->replaceVariables( $text, $frame );
5745 $text = $this->mStripState
->unstripBoth( $text );
5754 public function getTags() {
5756 array_keys( $this->mTransparentTagHooks
),
5757 array_keys( $this->mTagHooks
),
5758 array_keys( $this->mFunctionTagHooks
)
5763 * Replace transparent tags in $text with the values given by the callbacks.
5765 * Transparent tag hooks are like regular XML-style tag hooks, except they
5766 * operate late in the transformation sequence, on HTML instead of wikitext.
5768 * @param string $text
5772 public function replaceTransparentTags( $text ) {
5774 $elements = array_keys( $this->mTransparentTagHooks
);
5775 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5776 $replacements = array();
5778 foreach ( $matches as $marker => $data ) {
5779 list( $element, $content, $params, $tag ) = $data;
5780 $tagName = strtolower( $element );
5781 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5782 $output = call_user_func_array(
5783 $this->mTransparentTagHooks
[$tagName],
5784 array( $content, $params, $this )
5789 $replacements[$marker] = $output;
5791 return strtr( $text, $replacements );
5795 * Break wikitext input into sections, and either pull or replace
5796 * some particular section's text.
5798 * External callers should use the getSection and replaceSection methods.
5800 * @param string $text Page wikitext
5801 * @param string|number $sectionId A section identifier string of the form:
5802 * "<flag1> - <flag2> - ... - <section number>"
5804 * Currently the only recognised flag is "T", which means the target section number
5805 * was derived during a template inclusion parse, in other words this is a template
5806 * section edit link. If no flags are given, it was an ordinary section edit link.
5807 * This flag is required to avoid a section numbering mismatch when a section is
5808 * enclosed by "<includeonly>" (bug 6563).
5810 * The section number 0 pulls the text before the first heading; other numbers will
5811 * pull the given section along with its lower-level subsections. If the section is
5812 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5814 * Section 0 is always considered to exist, even if it only contains the empty
5815 * string. If $text is the empty string and section 0 is replaced, $newText is
5818 * @param string $mode One of "get" or "replace"
5819 * @param string $newText Replacement text for section data.
5820 * @return string For "get", the extracted section text.
5821 * for "replace", the whole page with the section replaced.
5823 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5824 global $wgTitle; # not generally used but removes an ugly failure mode
5826 $magicScopeVariable = $this->lock();
5827 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5829 $frame = $this->getPreprocessor()->newFrame();
5831 # Process section extraction flags
5833 $sectionParts = explode( '-', $sectionId );
5834 $sectionIndex = array_pop( $sectionParts );
5835 foreach ( $sectionParts as $part ) {
5836 if ( $part === 'T' ) {
5837 $flags |
= self
::PTD_FOR_INCLUSION
;
5841 # Check for empty input
5842 if ( strval( $text ) === '' ) {
5843 # Only sections 0 and T-0 exist in an empty document
5844 if ( $sectionIndex == 0 ) {
5845 if ( $mode === 'get' ) {
5851 if ( $mode === 'get' ) {
5859 # Preprocess the text
5860 $root = $this->preprocessToDom( $text, $flags );
5862 # <h> nodes indicate section breaks
5863 # They can only occur at the top level, so we can find them by iterating the root's children
5864 $node = $root->getFirstChild();
5866 # Find the target section
5867 if ( $sectionIndex == 0 ) {
5868 # Section zero doesn't nest, level=big
5869 $targetLevel = 1000;
5872 if ( $node->getName() === 'h' ) {
5873 $bits = $node->splitHeading();
5874 if ( $bits['i'] == $sectionIndex ) {
5875 $targetLevel = $bits['level'];
5879 if ( $mode === 'replace' ) {
5880 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5882 $node = $node->getNextSibling();
5888 if ( $mode === 'get' ) {
5895 # Find the end of the section, including nested sections
5897 if ( $node->getName() === 'h' ) {
5898 $bits = $node->splitHeading();
5899 $curLevel = $bits['level'];
5900 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5904 if ( $mode === 'get' ) {
5905 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5907 $node = $node->getNextSibling();
5910 # Write out the remainder (in replace mode only)
5911 if ( $mode === 'replace' ) {
5912 # Output the replacement text
5913 # Add two newlines on -- trailing whitespace in $newText is conventionally
5914 # stripped by the editor, so we need both newlines to restore the paragraph gap
5915 # Only add trailing whitespace if there is newText
5916 if ( $newText != "" ) {
5917 $outText .= $newText . "\n\n";
5921 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5922 $node = $node->getNextSibling();
5926 if ( is_string( $outText ) ) {
5927 # Re-insert stripped tags
5928 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5935 * This function returns the text of a section, specified by a number ($section).
5936 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5937 * the first section before any such heading (section 0).
5939 * If a section contains subsections, these are also returned.
5941 * @param string $text Text to look in
5942 * @param string|number $sectionId Section identifier as a number or string
5943 * (e.g. 0, 1 or 'T-1').
5944 * @param string $defaultText Default to return if section is not found
5946 * @return string Text of the requested section
5948 public function getSection( $text, $sectionId, $defaultText = '' ) {
5949 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5953 * This function returns $oldtext after the content of the section
5954 * specified by $section has been replaced with $text. If the target
5955 * section does not exist, $oldtext is returned unchanged.
5957 * @param string $oldText Former text of the article
5958 * @param string|number $sectionId Section identifier as a number or string
5959 * (e.g. 0, 1 or 'T-1').
5960 * @param string $newText Replacing text
5962 * @return string Modified text
5964 public function replaceSection( $oldText, $sectionId, $newText ) {
5965 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5969 * Get the ID of the revision we are parsing
5973 public function getRevisionId() {
5974 return $this->mRevisionId
;
5978 * Get the revision object for $this->mRevisionId
5980 * @return Revision|null Either a Revision object or null
5981 * @since 1.23 (public since 1.23)
5983 public function getRevisionObject() {
5984 if ( !is_null( $this->mRevisionObject
) ) {
5985 return $this->mRevisionObject
;
5987 if ( is_null( $this->mRevisionId
) ) {
5991 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5992 return $this->mRevisionObject
;
5996 * Get the timestamp associated with the current revision, adjusted for
5997 * the default server-local timestamp
6000 public function getRevisionTimestamp() {
6001 if ( is_null( $this->mRevisionTimestamp
) ) {
6005 $revObject = $this->getRevisionObject();
6006 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
6008 # The cryptic '' timezone parameter tells to use the site-default
6009 # timezone offset instead of the user settings.
6011 # Since this value will be saved into the parser cache, served
6012 # to other users, and potentially even used inside links and such,
6013 # it needs to be consistent for all visitors.
6014 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
6017 return $this->mRevisionTimestamp
;
6021 * Get the name of the user that edited the last revision
6023 * @return string User name
6025 public function getRevisionUser() {
6026 if ( is_null( $this->mRevisionUser
) ) {
6027 $revObject = $this->getRevisionObject();
6029 # if this template is subst: the revision id will be blank,
6030 # so just use the current user's name
6032 $this->mRevisionUser
= $revObject->getUserText();
6033 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6034 $this->mRevisionUser
= $this->getUser()->getName();
6037 return $this->mRevisionUser
;
6041 * Get the size of the revision
6043 * @return int|null Revision size
6045 public function getRevisionSize() {
6046 if ( is_null( $this->mRevisionSize
) ) {
6047 $revObject = $this->getRevisionObject();
6049 # if this variable is subst: the revision id will be blank,
6050 # so just use the parser input size, because the own substituation
6051 # will change the size.
6053 $this->mRevisionSize
= $revObject->getSize();
6054 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6055 $this->mRevisionSize
= $this->mInputSize
;
6058 return $this->mRevisionSize
;
6062 * Mutator for $mDefaultSort
6064 * @param string $sort New value
6066 public function setDefaultSort( $sort ) {
6067 $this->mDefaultSort
= $sort;
6068 $this->mOutput
->setProperty( 'defaultsort', $sort );
6072 * Accessor for $mDefaultSort
6073 * Will use the empty string if none is set.
6075 * This value is treated as a prefix, so the
6076 * empty string is equivalent to sorting by
6081 public function getDefaultSort() {
6082 if ( $this->mDefaultSort
!== false ) {
6083 return $this->mDefaultSort
;
6090 * Accessor for $mDefaultSort
6091 * Unlike getDefaultSort(), will return false if none is set
6093 * @return string|bool
6095 public function getCustomDefaultSort() {
6096 return $this->mDefaultSort
;
6100 * Try to guess the section anchor name based on a wikitext fragment
6101 * presumably extracted from a heading, for example "Header" from
6104 * @param string $text
6108 public function guessSectionNameFromWikiText( $text ) {
6109 # Strip out wikitext links(they break the anchor)
6110 $text = $this->stripSectionName( $text );
6111 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6112 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
6116 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6117 * instead. For use in redirects, since IE6 interprets Redirect: headers
6118 * as something other than UTF-8 (apparently?), resulting in breakage.
6120 * @param string $text The section name
6121 * @return string An anchor
6123 public function guessLegacySectionNameFromWikiText( $text ) {
6124 # Strip out wikitext links(they break the anchor)
6125 $text = $this->stripSectionName( $text );
6126 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6127 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
6131 * Strips a text string of wikitext for use in a section anchor
6133 * Accepts a text string and then removes all wikitext from the
6134 * string and leaves only the resultant text (i.e. the result of
6135 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6136 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6137 * to create valid section anchors by mimicing the output of the
6138 * parser when headings are parsed.
6140 * @param string $text Text string to be stripped of wikitext
6141 * for use in a Section anchor
6142 * @return string Filtered text string
6144 public function stripSectionName( $text ) {
6145 # Strip internal link markup
6146 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6147 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6149 # Strip external link markup
6150 # @todo FIXME: Not tolerant to blank link text
6151 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6152 # on how many empty links there are on the page - need to figure that out.
6153 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6155 # Parse wikitext quotes (italics & bold)
6156 $text = $this->doQuotes( $text );
6159 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
6164 * strip/replaceVariables/unstrip for preprocessor regression testing
6166 * @param string $text
6167 * @param Title $title
6168 * @param ParserOptions $options
6169 * @param int $outputType
6173 public function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
6174 $magicScopeVariable = $this->lock();
6175 $this->startParse( $title, $options, $outputType, true );
6177 $text = $this->replaceVariables( $text );
6178 $text = $this->mStripState
->unstripBoth( $text );
6179 $text = Sanitizer
::removeHTMLtags( $text );
6184 * @param string $text
6185 * @param Title $title
6186 * @param ParserOptions $options
6189 public function testPst( $text, Title
$title, ParserOptions
$options ) {
6190 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6194 * @param string $text
6195 * @param Title $title
6196 * @param ParserOptions $options
6199 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
6200 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
6204 * Call a callback function on all regions of the given text that are not
6205 * inside strip markers, and replace those regions with the return value
6206 * of the callback. For example, with input:
6210 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6211 * two strings will be replaced with the value returned by the callback in
6215 * @param callable $callback
6219 public function markerSkipCallback( $s, $callback ) {
6222 while ( $i < strlen( $s ) ) {
6223 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
6224 if ( $markerStart === false ) {
6225 $out .= call_user_func( $callback, substr( $s, $i ) );
6228 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6229 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6230 if ( $markerEnd === false ) {
6231 $out .= substr( $s, $markerStart );
6234 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6235 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6244 * Remove any strip markers found in the given text.
6246 * @param string $text Input string
6249 public function killMarkers( $text ) {
6250 return $this->mStripState
->killMarkers( $text );
6254 * Save the parser state required to convert the given half-parsed text to
6255 * HTML. "Half-parsed" in this context means the output of
6256 * recursiveTagParse() or internalParse(). This output has strip markers
6257 * from replaceVariables (extensionSubstitution() etc.), and link
6258 * placeholders from replaceLinkHolders().
6260 * Returns an array which can be serialized and stored persistently. This
6261 * array can later be loaded into another parser instance with
6262 * unserializeHalfParsedText(). The text can then be safely incorporated into
6263 * the return value of a parser hook.
6265 * @param string $text
6269 public function serializeHalfParsedText( $text ) {
6272 'version' => self
::HALF_PARSED_VERSION
,
6273 'stripState' => $this->mStripState
->getSubState( $text ),
6274 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6280 * Load the parser state given in the $data array, which is assumed to
6281 * have been generated by serializeHalfParsedText(). The text contents is
6282 * extracted from the array, and its markers are transformed into markers
6283 * appropriate for the current Parser instance. This transformed text is
6284 * returned, and can be safely included in the return value of a parser
6287 * If the $data array has been stored persistently, the caller should first
6288 * check whether it is still valid, by calling isValidHalfParsedText().
6290 * @param array $data Serialized data
6291 * @throws MWException
6294 public function unserializeHalfParsedText( $data ) {
6295 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6296 throw new MWException( __METHOD__
. ': invalid version' );
6299 # First, extract the strip state.
6300 $texts = array( $data['text'] );
6301 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6303 # Now renumber links
6304 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6306 # Should be good to go.
6311 * Returns true if the given array, presumed to be generated by
6312 * serializeHalfParsedText(), is compatible with the current version of the
6315 * @param array $data
6319 public function isValidHalfParsedText( $data ) {
6320 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6324 * Parsed a width param of imagelink like 300px or 200x300px
6326 * @param string $value
6331 public function parseWidthParam( $value ) {
6332 $parsedWidthParam = array();
6333 if ( $value === '' ) {
6334 return $parsedWidthParam;
6337 # (bug 13500) In both cases (width/height and width only),
6338 # permit trailing "px" for backward compatibility.
6339 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6340 $width = intval( $m[1] );
6341 $height = intval( $m[2] );
6342 $parsedWidthParam['width'] = $width;
6343 $parsedWidthParam['height'] = $height;
6344 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6345 $width = intval( $value );
6346 $parsedWidthParam['width'] = $width;
6348 return $parsedWidthParam;
6352 * Lock the current instance of the parser.
6354 * This is meant to stop someone from calling the parser
6355 * recursively and messing up all the strip state.
6357 * @throws MWException If parser is in a parse
6358 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6360 protected function lock() {
6361 if ( $this->mInParse
) {
6362 throw new MWException( "Parser state cleared while parsing. "
6363 . "Did you call Parser::parse recursively?" );
6365 $this->mInParse
= true;
6368 $recursiveCheck = new ScopedCallback( function() use ( $that ) {
6369 $that->mInParse
= false;
6372 return $recursiveCheck;
6376 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6378 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6379 * or if there is more than one <p/> tag in the input HTML.
6381 * @param string $html
6385 public static function stripOuterParagraph( $html ) {
6387 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6388 if ( strpos( $m[1], '</p>' ) === false ) {
6397 * Return this parser if it is not doing anything, otherwise
6398 * get a fresh parser. You can use this method by doing
6399 * $myParser = $wgParser->getFreshParser(), or more simply
6400 * $wgParser->getFreshParser()->parse( ... );
6401 * if you're unsure if $wgParser is safe to use.
6404 * @return Parser A parser object that is not parsing anything
6406 public function getFreshParser() {
6407 global $wgParserConf;
6408 if ( $this->mInParse
) {
6409 return new $wgParserConf['class']( $wgParserConf );