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;
302 CoreParserFunctions
::register( $this );
303 CoreTagHooks
::register( $this );
304 $this->initialiseVariables();
306 Hooks
::run( 'ParserFirstCallInit', array( &$this ) );
314 public function clearState() {
315 if ( $this->mFirstCall
) {
316 $this->firstCallInit();
318 $this->mOutput
= new ParserOutput
;
319 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
320 $this->mAutonumber
= 0;
321 $this->mLastSection
= '';
322 $this->mDTopen
= false;
323 $this->mIncludeCount
= array();
324 $this->mArgStack
= false;
325 $this->mInPre
= false;
326 $this->mLinkHolders
= new LinkHolderArray( $this );
328 $this->mRevisionObject
= $this->mRevisionTimestamp
=
329 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
330 $this->mVarCache
= array();
332 $this->mLangLinkLanguages
= array();
333 $this->currentRevisionCache
= null;
336 * Prefix for temporary replacement strings for the multipass parser.
337 * \x07 should never appear in input as it's disallowed in XML.
338 * Using it at the front also gives us a little extra robustness
339 * since it shouldn't match when butted up against identifier-like
342 * Must not consist of all title characters, or else it will change
343 * the behavior of <nowiki> in a link.
345 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
346 $this->mStripState
= new StripState( $this->mUniqPrefix
);
348 # Clear these on every parse, bug 4549
349 $this->mTplRedirCache
= $this->mTplDomCache
= array();
351 $this->mShowToc
= true;
352 $this->mForceTocPosition
= false;
353 $this->mIncludeSizes
= array(
357 $this->mPPNodeCount
= 0;
358 $this->mGeneratedPPNodeCount
= 0;
359 $this->mHighestExpansionDepth
= 0;
360 $this->mDefaultSort
= false;
361 $this->mHeadings
= array();
362 $this->mDoubleUnderscores
= array();
363 $this->mExpensiveFunctionCount
= 0;
366 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
367 $this->mPreprocessor
= null;
370 $this->mProfiler
= new SectionProfiler();
372 Hooks
::run( 'ParserClearState', array( &$this ) );
376 * Convert wikitext to HTML
377 * Do not call this function recursively.
379 * @param string $text Text we want to parse
380 * @param Title $title
381 * @param ParserOptions $options
382 * @param bool $linestart
383 * @param bool $clearState
384 * @param int $revid Number to pass in {{REVISIONID}}
385 * @return ParserOutput A ParserOutput
387 public function parse( $text, Title
$title, ParserOptions
$options,
388 $linestart = true, $clearState = true, $revid = null
391 * First pass--just handle <nowiki> sections, pass the rest off
392 * to internalParse() which does all the real work.
395 global $wgShowHostnames;
396 $fname = __METHOD__
. '-' . wfGetCaller();
399 $magicScopeVariable = $this->lock();
402 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
404 $this->currentRevisionCache
= null;
405 $this->mInputSize
= strlen( $text );
406 if ( $this->mOptions
->getEnableLimitReport() ) {
407 $this->mOutput
->resetParseStartTime();
410 # Remove the strip marker tag prefix from the input, if present.
412 $text = str_replace( $this->mUniqPrefix
, '', $text );
415 $oldRevisionId = $this->mRevisionId
;
416 $oldRevisionObject = $this->mRevisionObject
;
417 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
418 $oldRevisionUser = $this->mRevisionUser
;
419 $oldRevisionSize = $this->mRevisionSize
;
420 if ( $revid !== null ) {
421 $this->mRevisionId
= $revid;
422 $this->mRevisionObject
= null;
423 $this->mRevisionTimestamp
= null;
424 $this->mRevisionUser
= null;
425 $this->mRevisionSize
= null;
428 Hooks
::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
430 Hooks
::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
431 $text = $this->internalParse( $text );
432 Hooks
::run( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
434 $text = $this->internalParseHalfParsed( $text, true, $linestart );
437 * A converted title will be provided in the output object if title and
438 * content conversion are enabled, the article text does not contain
439 * a conversion-suppressing double-underscore tag, and no
440 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
441 * automatic link conversion.
443 if ( !( $options->getDisableTitleConversion()
444 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
445 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
446 ||
$this->mOutput
->getDisplayTitle() !== false )
448 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
449 if ( $convruletitle ) {
450 $this->mOutput
->setTitleText( $convruletitle );
452 $titleText = $this->getConverterLanguage()->convertTitle( $title );
453 $this->mOutput
->setTitleText( $titleText );
457 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
458 $this->limitationWarn( 'expensive-parserfunction',
459 $this->mExpensiveFunctionCount
,
460 $this->mOptions
->getExpensiveParserFunctionLimit()
464 # Information on include size limits, for the benefit of users who try to skirt them
465 if ( $this->mOptions
->getEnableLimitReport() ) {
466 $max = $this->mOptions
->getMaxIncludeSize();
468 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
469 if ( $cpuTime !== null ) {
470 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
471 sprintf( "%.3f", $cpuTime )
475 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
476 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
477 sprintf( "%.3f", $wallTime )
480 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
481 array( $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() )
483 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
484 array( $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() )
486 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
487 array( $this->mIncludeSizes
['post-expand'], $max )
489 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
490 array( $this->mIncludeSizes
['arg'], $max )
492 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
493 array( $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() )
495 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
496 array( $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() )
498 Hooks
::run( 'ParserLimitReportPrepare', array( $this, $this->mOutput
) );
500 $limitReport = "NewPP limit report\n";
501 if ( $wgShowHostnames ) {
502 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
504 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
505 if ( Hooks
::run( 'ParserLimitReportFormat',
506 array( $key, &$value, &$limitReport, false, false )
508 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
509 $valueMsg = wfMessage( array( "$key-value-text", "$key-value" ) )
510 ->inLanguage( 'en' )->useDatabase( false );
511 if ( !$valueMsg->exists() ) {
512 $valueMsg = new RawMessage( '$1' );
514 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
515 $valueMsg->params( $value );
516 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
520 // Since we're not really outputting HTML, decode the entities and
521 // then re-encode the things that need hiding inside HTML comments.
522 $limitReport = htmlspecialchars_decode( $limitReport );
523 Hooks
::run( 'ParserLimitReport', array( $this, &$limitReport ) );
525 // Sanitize for comment. Note '‐' in the replacement is U+2010,
526 // which looks much like the problematic '-'.
527 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&' ), $limitReport );
528 $text .= "\n<!-- \n$limitReport-->\n";
530 // Add on template profiling data
531 $dataByFunc = $this->mProfiler
->getFunctionStats();
532 uasort( $dataByFunc, function ( $a, $b ) {
533 return $a['real'] < $b['real']; // descending order
535 $profileReport = "Transclusion expansion time report (%,ms,calls,template)\n";
536 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
537 $profileReport .= sprintf( "%6.2f%% %8.3f %6d - %s\n",
538 $item['%real'], $item['real'], $item['calls'],
539 htmlspecialchars( $item['name'] ) );
541 $text .= "\n<!-- \n$profileReport-->\n";
543 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
544 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
545 $this->mTitle
->getPrefixedDBkey() );
548 $this->mOutput
->setText( $text );
550 $this->mRevisionId
= $oldRevisionId;
551 $this->mRevisionObject
= $oldRevisionObject;
552 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
553 $this->mRevisionUser
= $oldRevisionUser;
554 $this->mRevisionSize
= $oldRevisionSize;
555 $this->mInputSize
= false;
556 $this->currentRevisionCache
= null;
558 return $this->mOutput
;
562 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
563 * can be called from an extension tag hook.
565 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
566 * instead, which means that lists and links have not been fully parsed yet,
567 * and strip markers are still present.
569 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
571 * Use this function if you're a parser tag hook and you want to parse
572 * wikitext before or after applying additional transformations, and you
573 * intend to *return the result as hook output*, which will cause it to go
574 * through the rest of parsing process automatically.
576 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
577 * $text are not expanded
579 * @param string $text Text extension wants to have parsed
580 * @param bool|PPFrame $frame The frame to use for expanding any template variables
581 * @return string UNSAFE half-parsed HTML
583 public function recursiveTagParse( $text, $frame = false ) {
584 Hooks
::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
585 Hooks
::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
586 $text = $this->internalParse( $text, false, $frame );
591 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
592 * point can be called from an extension tag hook.
594 * The output of this function is fully-parsed HTML that is safe for output.
595 * If you're a parser tag hook, you might want to use recursiveTagParse()
598 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
599 * $text are not expanded
603 * @param string $text Text extension wants to have parsed
604 * @param bool|PPFrame $frame The frame to use for expanding any template variables
605 * @return string Fully parsed HTML
607 public function recursiveTagParseFully( $text, $frame = false ) {
608 $text = $this->recursiveTagParse( $text, $frame );
609 $text = $this->internalParseHalfParsed( $text, false );
614 * Expand templates and variables in the text, producing valid, static wikitext.
615 * Also removes comments.
616 * Do not call this function recursively.
617 * @param string $text
618 * @param Title $title
619 * @param ParserOptions $options
620 * @param int|null $revid
621 * @param bool|PPFrame $frame
622 * @return mixed|string
624 public function preprocess( $text, Title
$title = null,
625 ParserOptions
$options, $revid = null, $frame = false
627 $magicScopeVariable = $this->lock();
628 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
629 if ( $revid !== null ) {
630 $this->mRevisionId
= $revid;
632 Hooks
::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
633 Hooks
::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
634 $text = $this->replaceVariables( $text, $frame );
635 $text = $this->mStripState
->unstripBoth( $text );
640 * Recursive parser entry point that can be called from an extension tag
643 * @param string $text Text to be expanded
644 * @param bool|PPFrame $frame The frame to use for expanding any template variables
648 public function recursivePreprocess( $text, $frame = false ) {
649 $text = $this->replaceVariables( $text, $frame );
650 $text = $this->mStripState
->unstripBoth( $text );
655 * Process the wikitext for the "?preload=" feature. (bug 5210)
657 * "<noinclude>", "<includeonly>" etc. are parsed as for template
658 * transclusion, comments, templates, arguments, tags hooks and parser
659 * functions are untouched.
661 * @param string $text
662 * @param Title $title
663 * @param ParserOptions $options
664 * @param array $params
667 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = array() ) {
668 $msg = new RawMessage( $text );
669 $text = $msg->params( $params )->plain();
671 # Parser (re)initialisation
672 $magicScopeVariable = $this->lock();
673 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
675 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
676 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
677 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
678 $text = $this->mStripState
->unstripBoth( $text );
683 * Get a random string
687 public static function getRandomString() {
688 return wfRandomString( 16 );
692 * Set the current user.
693 * Should only be used when doing pre-save transform.
695 * @param User|null $user User object or null (to reset)
697 public function setUser( $user ) {
698 $this->mUser
= $user;
702 * Accessor for mUniqPrefix.
706 public function uniqPrefix() {
707 if ( !isset( $this->mUniqPrefix
) ) {
708 # @todo FIXME: This is probably *horribly wrong*
709 # LanguageConverter seems to want $wgParser's uniqPrefix, however
710 # if this is called for a parser cache hit, the parser may not
711 # have ever been initialized in the first place.
712 # Not really sure what the heck is supposed to be going on here.
714 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
716 return $this->mUniqPrefix
;
720 * Set the context title
724 public function setTitle( $t ) {
726 $t = Title
::newFromText( 'NO TITLE' );
729 if ( $t->hasFragment() ) {
730 # Strip the fragment to avoid various odd effects
731 $this->mTitle
= clone $t;
732 $this->mTitle
->setFragment( '' );
739 * Accessor for the Title object
743 public function getTitle() {
744 return $this->mTitle
;
748 * Accessor/mutator for the Title object
750 * @param Title $x Title object or null to just get the current one
753 public function Title( $x = null ) {
754 return wfSetVar( $this->mTitle
, $x );
758 * Set the output type
760 * @param int $ot New value
762 public function setOutputType( $ot ) {
763 $this->mOutputType
= $ot;
766 'html' => $ot == self
::OT_HTML
,
767 'wiki' => $ot == self
::OT_WIKI
,
768 'pre' => $ot == self
::OT_PREPROCESS
,
769 'plain' => $ot == self
::OT_PLAIN
,
774 * Accessor/mutator for the output type
776 * @param int|null $x New value or null to just get the current one
779 public function OutputType( $x = null ) {
780 return wfSetVar( $this->mOutputType
, $x );
784 * Get the ParserOutput object
786 * @return ParserOutput
788 public function getOutput() {
789 return $this->mOutput
;
793 * Get the ParserOptions object
795 * @return ParserOptions
797 public function getOptions() {
798 return $this->mOptions
;
802 * Accessor/mutator for the ParserOptions object
804 * @param ParserOptions $x New value or null to just get the current one
805 * @return ParserOptions Current ParserOptions object
807 public function Options( $x = null ) {
808 return wfSetVar( $this->mOptions
, $x );
814 public function nextLinkID() {
815 return $this->mLinkID++
;
821 public function setLinkID( $id ) {
822 $this->mLinkID
= $id;
826 * Get a language object for use in parser functions such as {{FORMATNUM:}}
829 public function getFunctionLang() {
830 return $this->getTargetLanguage();
834 * Get the target language for the content being parsed. This is usually the
835 * language that the content is in.
839 * @throws MWException
842 public function getTargetLanguage() {
843 $target = $this->mOptions
->getTargetLanguage();
845 if ( $target !== null ) {
847 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
848 return $this->mOptions
->getUserLangObj();
849 } elseif ( is_null( $this->mTitle
) ) {
850 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
853 return $this->mTitle
->getPageLanguage();
857 * Get the language object for language conversion
858 * @return Language|null
860 public function getConverterLanguage() {
861 return $this->getTargetLanguage();
865 * Get a User object either from $this->mUser, if set, or from the
866 * ParserOptions object otherwise
870 public function getUser() {
871 if ( !is_null( $this->mUser
) ) {
874 return $this->mOptions
->getUser();
878 * Get a preprocessor object
880 * @return Preprocessor
882 public function getPreprocessor() {
883 if ( !isset( $this->mPreprocessor
) ) {
884 $class = $this->mPreprocessorClass
;
885 $this->mPreprocessor
= new $class( $this );
887 return $this->mPreprocessor
;
891 * Replaces all occurrences of HTML-style comments and the given tags
892 * in the text with a random marker and returns the next text. The output
893 * parameter $matches will be an associative array filled with data in
897 * 'UNIQ-xxxxx' => array(
900 * array( 'param' => 'x' ),
901 * '<element param="x">tag content</element>' ) )
904 * @param array $elements List of element names. Comments are always extracted.
905 * @param string $text Source text string.
906 * @param array $matches Out parameter, Array: extracted tags
907 * @param string $uniq_prefix
908 * @return string Stripped text
910 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
915 $taglist = implode( '|', $elements );
916 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
918 while ( $text != '' ) {
919 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
921 if ( count( $p ) < 5 ) {
924 if ( count( $p ) > 5 ) {
938 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
939 $stripped .= $marker;
941 if ( $close === '/>' ) {
942 # Empty element tag, <tag />
947 if ( $element === '!--' ) {
950 $end = "/(<\\/$element\\s*>)/i";
952 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
954 if ( count( $q ) < 3 ) {
955 # No end tag -- let it run out to the end of the text.
964 $matches[$marker] = array( $element,
966 Sanitizer
::decodeTagAttributes( $attributes ),
967 "<$element$attributes$close$content$tail" );
973 * Get a list of strippable XML-like elements
977 public function getStripList() {
978 return $this->mStripList
;
982 * Add an item to the strip state
983 * Returns the unique tag which must be inserted into the stripped text
984 * The tag will be replaced with the original text in unstrip()
986 * @param string $text
990 public function insertStripItem( $text ) {
991 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
992 $this->mMarkerIndex++
;
993 $this->mStripState
->addGeneral( $rnd, $text );
998 * parse the wiki syntax used to render tables
1001 * @param string $text
1004 public function doTableStuff( $text ) {
1006 $lines = StringUtils
::explode( "\n", $text );
1008 $td_history = array(); # Is currently a td tag open?
1009 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
1010 $tr_history = array(); # Is currently a tr tag open?
1011 $tr_attributes = array(); # history of tr attributes
1012 $has_opened_tr = array(); # Did this table open a <tr> element?
1013 $indent_level = 0; # indent level of the table
1015 foreach ( $lines as $outLine ) {
1016 $line = trim( $outLine );
1018 if ( $line === '' ) { # empty line, go to next line
1019 $out .= $outLine . "\n";
1023 $first_character = $line[0];
1026 if ( preg_match( '/^(:*)\{\|(.*)$/', $line, $matches ) ) {
1027 # First check if we are starting a new table
1028 $indent_level = strlen( $matches[1] );
1030 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1031 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1033 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1034 array_push( $td_history, false );
1035 array_push( $last_tag_history, '' );
1036 array_push( $tr_history, false );
1037 array_push( $tr_attributes, '' );
1038 array_push( $has_opened_tr, false );
1039 } elseif ( count( $td_history ) == 0 ) {
1040 # Don't do any of the following
1041 $out .= $outLine . "\n";
1043 } elseif ( substr( $line, 0, 2 ) === '|}' ) {
1044 # We are ending a table
1045 $line = '</table>' . substr( $line, 2 );
1046 $last_tag = array_pop( $last_tag_history );
1048 if ( !array_pop( $has_opened_tr ) ) {
1049 $line = "<tr><td></td></tr>{$line}";
1052 if ( array_pop( $tr_history ) ) {
1053 $line = "</tr>{$line}";
1056 if ( array_pop( $td_history ) ) {
1057 $line = "</{$last_tag}>{$line}";
1059 array_pop( $tr_attributes );
1060 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
1061 } elseif ( substr( $line, 0, 2 ) === '|-' ) {
1062 # Now we have a table row
1063 $line = preg_replace( '#^\|-+#', '', $line );
1065 # Whats after the tag is now only attributes
1066 $attributes = $this->mStripState
->unstripBoth( $line );
1067 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1068 array_pop( $tr_attributes );
1069 array_push( $tr_attributes, $attributes );
1072 $last_tag = array_pop( $last_tag_history );
1073 array_pop( $has_opened_tr );
1074 array_push( $has_opened_tr, true );
1076 if ( array_pop( $tr_history ) ) {
1080 if ( array_pop( $td_history ) ) {
1081 $line = "</{$last_tag}>{$line}";
1085 array_push( $tr_history, false );
1086 array_push( $td_history, false );
1087 array_push( $last_tag_history, '' );
1088 } elseif ( $first_character === '|'
1089 ||
$first_character === '!'
1090 ||
substr( $line, 0, 2 ) === '|+'
1092 # This might be cell elements, td, th or captions
1093 if ( substr( $line, 0, 2 ) === '|+' ) {
1094 $first_character = '+';
1095 $line = substr( $line, 1 );
1098 $line = substr( $line, 1 );
1100 if ( $first_character === '!' ) {
1101 $line = str_replace( '!!', '||', $line );
1104 # Split up multiple cells on the same line.
1105 # FIXME : This can result in improper nesting of tags processed
1106 # by earlier parser steps, but should avoid splitting up eg
1107 # attribute values containing literal "||".
1108 $cells = StringUtils
::explodeMarkup( '||', $line );
1112 # Loop through each table cell
1113 foreach ( $cells as $cell ) {
1115 if ( $first_character !== '+' ) {
1116 $tr_after = array_pop( $tr_attributes );
1117 if ( !array_pop( $tr_history ) ) {
1118 $previous = "<tr{$tr_after}>\n";
1120 array_push( $tr_history, true );
1121 array_push( $tr_attributes, '' );
1122 array_pop( $has_opened_tr );
1123 array_push( $has_opened_tr, true );
1126 $last_tag = array_pop( $last_tag_history );
1128 if ( array_pop( $td_history ) ) {
1129 $previous = "</{$last_tag}>\n{$previous}";
1132 if ( $first_character === '|' ) {
1134 } elseif ( $first_character === '!' ) {
1136 } elseif ( $first_character === '+' ) {
1137 $last_tag = 'caption';
1142 array_push( $last_tag_history, $last_tag );
1144 # A cell could contain both parameters and data
1145 $cell_data = explode( '|', $cell, 2 );
1147 # Bug 553: Note that a '|' inside an invalid link should not
1148 # be mistaken as delimiting cell parameters
1149 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1150 $cell = "{$previous}<{$last_tag}>{$cell}";
1151 } elseif ( count( $cell_data ) == 1 ) {
1152 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1154 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1155 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1156 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1160 array_push( $td_history, true );
1163 $out .= $outLine . "\n";
1166 # Closing open td, tr && table
1167 while ( count( $td_history ) > 0 ) {
1168 if ( array_pop( $td_history ) ) {
1171 if ( array_pop( $tr_history ) ) {
1174 if ( !array_pop( $has_opened_tr ) ) {
1175 $out .= "<tr><td></td></tr>\n";
1178 $out .= "</table>\n";
1181 # Remove trailing line-ending (b/c)
1182 if ( substr( $out, -1 ) === "\n" ) {
1183 $out = substr( $out, 0, -1 );
1186 # special case: don't return empty table
1187 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1195 * Helper function for parse() that transforms wiki markup into half-parsed
1196 * HTML. Only called for $mOutputType == self::OT_HTML.
1200 * @param string $text
1201 * @param bool $isMain
1202 * @param bool $frame
1206 public function internalParse( $text, $isMain = true, $frame = false ) {
1210 # Hook to suspend the parser in this state
1211 if ( !Hooks
::run( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1215 # if $frame is provided, then use $frame for replacing any variables
1217 # use frame depth to infer how include/noinclude tags should be handled
1218 # depth=0 means this is the top-level document; otherwise it's an included document
1219 if ( !$frame->depth
) {
1222 $flag = Parser
::PTD_FOR_INCLUSION
;
1224 $dom = $this->preprocessToDom( $text, $flag );
1225 $text = $frame->expand( $dom );
1227 # if $frame is not provided, then use old-style replaceVariables
1228 $text = $this->replaceVariables( $text );
1231 Hooks
::run( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1232 $text = Sanitizer
::removeHTMLtags(
1234 array( &$this, 'attributeStripCallback' ),
1236 array_keys( $this->mTransparentTagHooks
)
1238 Hooks
::run( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1240 # Tables need to come after variable replacement for things to work
1241 # properly; putting them before other transformations should keep
1242 # exciting things like link expansions from showing up in surprising
1244 $text = $this->doTableStuff( $text );
1246 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1248 $text = $this->doDoubleUnderscore( $text );
1250 $text = $this->doHeadings( $text );
1251 $text = $this->replaceInternalLinks( $text );
1252 $text = $this->doAllQuotes( $text );
1253 $text = $this->replaceExternalLinks( $text );
1255 # replaceInternalLinks may sometimes leave behind
1256 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1257 $text = str_replace( $this->mUniqPrefix
. 'NOPARSE', '', $text );
1259 $text = $this->doMagicLinks( $text );
1260 $text = $this->formatHeadings( $text, $origText, $isMain );
1266 * Helper function for parse() that transforms half-parsed HTML into fully
1269 * @param string $text
1270 * @param bool $isMain
1271 * @param bool $linestart
1274 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1275 global $wgUseTidy, $wgAlwaysUseTidy;
1277 $text = $this->mStripState
->unstripGeneral( $text );
1279 # Clean up special characters, only run once, next-to-last before doBlockLevels
1281 # french spaces, last one Guillemet-left
1282 # only if there is something before the space
1283 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
1284 # french spaces, Guillemet-right
1285 '/(\\302\\253) /' => '\\1 ',
1286 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
1288 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
1290 $text = $this->doBlockLevels( $text, $linestart );
1292 $this->replaceLinkHolders( $text );
1295 * The input doesn't get language converted if
1297 * b) Content isn't converted
1298 * c) It's a conversion table
1299 * d) it is an interface message (which is in the user language)
1301 if ( !( $this->mOptions
->getDisableContentConversion()
1302 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
1304 if ( !$this->mOptions
->getInterfaceMessage() ) {
1305 # The position of the convert() call should not be changed. it
1306 # assumes that the links are all replaced and the only thing left
1307 # is the <nowiki> mark.
1308 $text = $this->getConverterLanguage()->convert( $text );
1312 $text = $this->mStripState
->unstripNoWiki( $text );
1315 Hooks
::run( 'ParserBeforeTidy', array( &$this, &$text ) );
1318 $text = $this->replaceTransparentTags( $text );
1319 $text = $this->mStripState
->unstripGeneral( $text );
1321 $text = Sanitizer
::normalizeCharReferences( $text );
1323 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
1324 $text = MWTidy
::tidy( $text );
1326 # attempt to sanitize at least some nesting problems
1327 # (bug #2702 and quite a few others)
1329 # ''Something [http://www.cool.com cool''] -->
1330 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1331 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1332 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1333 # fix up an anchor inside another anchor, only
1334 # at least for a single single nested link (bug 3695)
1335 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1336 '\\1\\2</a>\\3</a>\\1\\4</a>',
1337 # fix div inside inline elements- doBlockLevels won't wrap a line which
1338 # contains a div, so fix it up here; replace
1339 # div with escaped text
1340 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1341 '\\1\\3<div\\5>\\6</div>\\8\\9',
1342 # remove empty italic or bold tag pairs, some
1343 # introduced by rules above
1344 '/<([bi])><\/\\1>/' => '',
1347 $text = preg_replace(
1348 array_keys( $tidyregs ),
1349 array_values( $tidyregs ),
1354 Hooks
::run( 'ParserAfterTidy', array( &$this, &$text ) );
1361 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1362 * magic external links.
1367 * @param string $text
1371 public function doMagicLinks( $text ) {
1372 $prots = wfUrlProtocolsWithoutProtRel();
1373 $urlChar = self
::EXT_LINK_URL_CLASS
;
1374 $space = self
::SPACE_NOT_NL
; # non-newline space
1375 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1376 $spaces = "$space++"; # possessive match of 1 or more spaces
1377 $text = preg_replace_callback(
1379 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1380 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1381 (\b(?i:$prots)$urlChar+) | # m[3]: Free external links
1382 \b(?:RFC|PMID) $spaces # m[4]: RFC or PMID, capture number
1384 \bISBN $spaces ( # m[5]: ISBN, capture number
1385 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1386 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1387 [0-9Xx] # check digit
1389 )!xu", array( &$this, 'magicLinkCallback' ), $text );
1394 * @throws MWException
1396 * @return HTML|string
1398 public function magicLinkCallback( $m ) {
1399 if ( isset( $m[1] ) && $m[1] !== '' ) {
1402 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1405 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1406 # Free external link
1407 return $this->makeFreeExternalLink( $m[0] );
1408 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1410 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1413 $cssClass = 'mw-magiclink-rfc';
1415 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1417 $urlmsg = 'pubmedurl';
1418 $cssClass = 'mw-magiclink-pmid';
1421 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1422 substr( $m[0], 0, 20 ) . '"' );
1424 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1425 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass );
1426 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1429 $space = self
::SPACE_NOT_NL
; # non-newline space
1430 $isbn = preg_replace( "/$space/", ' ', $isbn );
1431 $num = strtr( $isbn, array(
1436 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1437 return '<a href="' .
1438 htmlspecialchars( $titleObj->getLocalURL() ) .
1439 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1446 * Make a free external link, given a user-supplied URL
1448 * @param string $url
1450 * @return string HTML
1453 public function makeFreeExternalLink( $url ) {
1457 # The characters '<' and '>' (which were escaped by
1458 # removeHTMLtags()) should not be included in
1459 # URLs, per RFC 2396.
1461 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1462 $trail = substr( $url, $m2[0][1] ) . $trail;
1463 $url = substr( $url, 0, $m2[0][1] );
1466 # Move trailing punctuation to $trail
1468 # If there is no left bracket, then consider right brackets fair game too
1469 if ( strpos( $url, '(' ) === false ) {
1473 $urlRev = strrev( $url );
1474 $numSepChars = strspn( $urlRev, $sep );
1475 # Don't break a trailing HTML entity by moving the ; into $trail
1476 # This is in hot code, so use substr_compare to avoid having to
1477 # create a new string object for the comparison
1478 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0) {
1479 # more optimization: instead of running preg_match with a $
1480 # anchor, which can be slow, do the match on the reversed
1481 # string starting at the desired offset.
1482 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1483 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1487 if ( $numSepChars ) {
1488 $trail = substr( $url, -$numSepChars ) . $trail;
1489 $url = substr( $url, 0, -$numSepChars );
1492 $url = Sanitizer
::cleanUrl( $url );
1494 # Is this an external image?
1495 $text = $this->maybeMakeExternalImage( $url );
1496 if ( $text === false ) {
1497 # Not an image, make a link
1498 $text = Linker
::makeExternalLink( $url,
1499 $this->getConverterLanguage()->markNoConversion( $url, true ),
1501 $this->getExternalLinkAttribs( $url ) );
1502 # Register it in the output object...
1503 # Replace unnecessary URL escape codes with their equivalent characters
1504 $pasteurized = self
::normalizeLinkUrl( $url );
1505 $this->mOutput
->addExternalLink( $pasteurized );
1507 return $text . $trail;
1511 * Parse headers and return html
1515 * @param string $text
1519 public function doHeadings( $text ) {
1520 for ( $i = 6; $i >= 1; --$i ) {
1521 $h = str_repeat( '=', $i );
1522 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1528 * Replace single quotes with HTML markup
1531 * @param string $text
1533 * @return string The altered text
1535 public function doAllQuotes( $text ) {
1537 $lines = StringUtils
::explode( "\n", $text );
1538 foreach ( $lines as $line ) {
1539 $outtext .= $this->doQuotes( $line ) . "\n";
1541 $outtext = substr( $outtext, 0, -1 );
1546 * Helper function for doAllQuotes()
1548 * @param string $text
1552 public function doQuotes( $text ) {
1553 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1554 $countarr = count( $arr );
1555 if ( $countarr == 1 ) {
1559 // First, do some preliminary work. This may shift some apostrophes from
1560 // being mark-up to being text. It also counts the number of occurrences
1561 // of bold and italics mark-ups.
1564 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1565 $thislen = strlen( $arr[$i] );
1566 // If there are ever four apostrophes, assume the first is supposed to
1567 // be text, and the remaining three constitute mark-up for bold text.
1568 // (bug 13227: ''''foo'''' turns into ' ''' foo ' ''')
1569 if ( $thislen == 4 ) {
1570 $arr[$i - 1] .= "'";
1573 } elseif ( $thislen > 5 ) {
1574 // If there are more than 5 apostrophes in a row, assume they're all
1575 // text except for the last 5.
1576 // (bug 13227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1577 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1581 // Count the number of occurrences of bold and italics mark-ups.
1582 if ( $thislen == 2 ) {
1584 } elseif ( $thislen == 3 ) {
1586 } elseif ( $thislen == 5 ) {
1592 // If there is an odd number of both bold and italics, it is likely
1593 // that one of the bold ones was meant to be an apostrophe followed
1594 // by italics. Which one we cannot know for certain, but it is more
1595 // likely to be one that has a single-letter word before it.
1596 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1597 $firstsingleletterword = -1;
1598 $firstmultiletterword = -1;
1600 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1601 if ( strlen( $arr[$i] ) == 3 ) {
1602 $x1 = substr( $arr[$i - 1], -1 );
1603 $x2 = substr( $arr[$i - 1], -2, 1 );
1604 if ( $x1 === ' ' ) {
1605 if ( $firstspace == -1 ) {
1608 } elseif ( $x2 === ' ' ) {
1609 if ( $firstsingleletterword == -1 ) {
1610 $firstsingleletterword = $i;
1611 // if $firstsingleletterword is set, we don't
1612 // look at the other options, so we can bail early.
1616 if ( $firstmultiletterword == -1 ) {
1617 $firstmultiletterword = $i;
1623 // If there is a single-letter word, use it!
1624 if ( $firstsingleletterword > -1 ) {
1625 $arr[$firstsingleletterword] = "''";
1626 $arr[$firstsingleletterword - 1] .= "'";
1627 } elseif ( $firstmultiletterword > -1 ) {
1628 // If not, but there's a multi-letter word, use that one.
1629 $arr[$firstmultiletterword] = "''";
1630 $arr[$firstmultiletterword - 1] .= "'";
1631 } elseif ( $firstspace > -1 ) {
1632 // ... otherwise use the first one that has neither.
1633 // (notice that it is possible for all three to be -1 if, for example,
1634 // there is only one pentuple-apostrophe in the line)
1635 $arr[$firstspace] = "''";
1636 $arr[$firstspace - 1] .= "'";
1640 // Now let's actually convert our apostrophic mush to HTML!
1645 foreach ( $arr as $r ) {
1646 if ( ( $i %
2 ) == 0 ) {
1647 if ( $state === 'both' ) {
1653 $thislen = strlen( $r );
1654 if ( $thislen == 2 ) {
1655 if ( $state === 'i' ) {
1658 } elseif ( $state === 'bi' ) {
1661 } elseif ( $state === 'ib' ) {
1662 $output .= '</b></i><b>';
1664 } elseif ( $state === 'both' ) {
1665 $output .= '<b><i>' . $buffer . '</i>';
1667 } else { // $state can be 'b' or ''
1671 } elseif ( $thislen == 3 ) {
1672 if ( $state === 'b' ) {
1675 } elseif ( $state === 'bi' ) {
1676 $output .= '</i></b><i>';
1678 } elseif ( $state === 'ib' ) {
1681 } elseif ( $state === 'both' ) {
1682 $output .= '<i><b>' . $buffer . '</b>';
1684 } else { // $state can be 'i' or ''
1688 } elseif ( $thislen == 5 ) {
1689 if ( $state === 'b' ) {
1690 $output .= '</b><i>';
1692 } elseif ( $state === 'i' ) {
1693 $output .= '</i><b>';
1695 } elseif ( $state === 'bi' ) {
1696 $output .= '</i></b>';
1698 } elseif ( $state === 'ib' ) {
1699 $output .= '</b></i>';
1701 } elseif ( $state === 'both' ) {
1702 $output .= '<i><b>' . $buffer . '</b></i>';
1704 } else { // ($state == '')
1712 // Now close all remaining tags. Notice that the order is important.
1713 if ( $state === 'b' ||
$state === 'ib' ) {
1716 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1719 if ( $state === 'bi' ) {
1722 // There might be lonely ''''', so make sure we have a buffer
1723 if ( $state === 'both' && $buffer ) {
1724 $output .= '<b><i>' . $buffer . '</i></b>';
1730 * Replace external links (REL)
1732 * Note: this is all very hackish and the order of execution matters a lot.
1733 * Make sure to run tests/parserTests.php if you change this code.
1737 * @param string $text
1739 * @throws MWException
1742 public function replaceExternalLinks( $text ) {
1744 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1745 if ( $bits === false ) {
1746 throw new MWException( "PCRE needs to be compiled with "
1747 . "--enable-unicode-properties in order for MediaWiki to function" );
1749 $s = array_shift( $bits );
1752 while ( $i < count( $bits ) ) {
1755 $text = $bits[$i++
];
1756 $trail = $bits[$i++
];
1758 # The characters '<' and '>' (which were escaped by
1759 # removeHTMLtags()) should not be included in
1760 # URLs, per RFC 2396.
1762 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1763 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1764 $url = substr( $url, 0, $m2[0][1] );
1767 # If the link text is an image URL, replace it with an <img> tag
1768 # This happened by accident in the original parser, but some people used it extensively
1769 $img = $this->maybeMakeExternalImage( $text );
1770 if ( $img !== false ) {
1776 # Set linktype for CSS - if URL==text, link is essentially free
1777 $linktype = ( $text === $url ) ?
'free' : 'text';
1779 # No link text, e.g. [http://domain.tld/some.link]
1780 if ( $text == '' ) {
1782 $langObj = $this->getTargetLanguage();
1783 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1784 $linktype = 'autonumber';
1786 # Have link text, e.g. [http://domain.tld/some.link text]s
1788 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1791 $text = $this->getConverterLanguage()->markNoConversion( $text );
1793 $url = Sanitizer
::cleanUrl( $url );
1795 # Use the encoded URL
1796 # This means that users can paste URLs directly into the text
1797 # Funny characters like ö aren't valid in URLs anyway
1798 # This was changed in August 2004
1799 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1800 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1802 # Register link in the output object.
1803 # Replace unnecessary URL escape codes with the referenced character
1804 # This prevents spammers from hiding links from the filters
1805 $pasteurized = self
::normalizeLinkUrl( $url );
1806 $this->mOutput
->addExternalLink( $pasteurized );
1813 * Get the rel attribute for a particular external link.
1816 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1817 * nofollow if appropriate
1818 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1819 * @return string|null Rel attribute for $url
1821 public static function getExternalLinkRel( $url = false, $title = null ) {
1822 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1823 $ns = $title ?
$title->getNamespace() : false;
1824 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1825 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1833 * Get an associative array of additional HTML attributes appropriate for a
1834 * particular external link. This currently may include rel => nofollow
1835 * (depending on configuration, namespace, and the URL's domain) and/or a
1836 * target attribute (depending on configuration).
1838 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1839 * nofollow if appropriate
1840 * @return array Associative array of HTML attributes
1842 public function getExternalLinkAttribs( $url = false ) {
1844 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1846 if ( $this->mOptions
->getExternalLinkTarget() ) {
1847 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1853 * Replace unusual escape codes in a URL with their equivalent characters
1855 * @deprecated since 1.24, use normalizeLinkUrl
1856 * @param string $url
1859 public static function replaceUnusualEscapes( $url ) {
1860 wfDeprecated( __METHOD__
, '1.24' );
1861 return self
::normalizeLinkUrl( $url );
1865 * Replace unusual escape codes in a URL with their equivalent characters
1867 * This generally follows the syntax defined in RFC 3986, with special
1868 * consideration for HTTP query strings.
1870 * @param string $url
1873 public static function normalizeLinkUrl( $url ) {
1874 # First, make sure unsafe characters are encoded
1875 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
1877 return rawurlencode( $m[0] );
1883 $end = strlen( $url );
1885 # Fragment part - 'fragment'
1886 $start = strpos( $url, '#' );
1887 if ( $start !== false && $start < $end ) {
1888 $ret = self
::normalizeUrlComponent(
1889 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
1893 # Query part - 'query' minus &=+;
1894 $start = strpos( $url, '?' );
1895 if ( $start !== false && $start < $end ) {
1896 $ret = self
::normalizeUrlComponent(
1897 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
1901 # Scheme and path part - 'pchar'
1902 # (we assume no userinfo or encoded colons in the host)
1903 $ret = self
::normalizeUrlComponent(
1904 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
1909 private static function normalizeUrlComponent( $component, $unsafe ) {
1910 $callback = function ( $matches ) use ( $unsafe ) {
1911 $char = urldecode( $matches[0] );
1912 $ord = ord( $char );
1913 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
1917 # Leave it escaped, but use uppercase for a-f
1918 return strtoupper( $matches[0] );
1921 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
1925 * make an image if it's allowed, either through the global
1926 * option, through the exception, or through the on-wiki whitelist
1928 * @param string $url
1932 private function maybeMakeExternalImage( $url ) {
1933 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1934 $imagesexception = !empty( $imagesfrom );
1936 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1937 if ( $imagesexception && is_array( $imagesfrom ) ) {
1938 $imagematch = false;
1939 foreach ( $imagesfrom as $match ) {
1940 if ( strpos( $url, $match ) === 0 ) {
1945 } elseif ( $imagesexception ) {
1946 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1948 $imagematch = false;
1951 if ( $this->mOptions
->getAllowExternalImages()
1952 ||
( $imagesexception && $imagematch )
1954 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1956 $text = Linker
::makeExternalImage( $url );
1959 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1960 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
1962 $whitelist = explode(
1964 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
1967 foreach ( $whitelist as $entry ) {
1968 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1969 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1972 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1973 # Image matches a whitelist entry
1974 $text = Linker
::makeExternalImage( $url );
1983 * Process [[ ]] wikilinks
1987 * @return string Processed text
1991 public function replaceInternalLinks( $s ) {
1992 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1997 * Process [[ ]] wikilinks (RIL)
1999 * @throws MWException
2000 * @return LinkHolderArray
2004 public function replaceInternalLinks2( &$s ) {
2005 global $wgExtraInterlanguageLinkPrefixes;
2007 static $tc = false, $e1, $e1_img;
2008 # the % is needed to support urlencoded titles as well
2010 $tc = Title
::legalChars() . '#%';
2011 # Match a link having the form [[namespace:link|alternate]]trail
2012 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2013 # Match cases where there is no "]]", which might still be images
2014 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2017 $holders = new LinkHolderArray( $this );
2019 # split the entire text string on occurrences of [[
2020 $a = StringUtils
::explode( '[[', ' ' . $s );
2021 # get the first element (all text up to first [[), and remove the space we added
2024 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2025 $s = substr( $s, 1 );
2027 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2029 if ( $useLinkPrefixExtension ) {
2030 # Match the end of a line for a word that's not followed by whitespace,
2031 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2033 $charset = $wgContLang->linkPrefixCharset();
2034 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2037 if ( is_null( $this->mTitle
) ) {
2038 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
2040 $nottalk = !$this->mTitle
->isTalkPage();
2042 if ( $useLinkPrefixExtension ) {
2044 if ( preg_match( $e2, $s, $m ) ) {
2045 $first_prefix = $m[2];
2047 $first_prefix = false;
2053 $useSubpages = $this->areSubpagesAllowed();
2055 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
2056 # Loop for each link
2057 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2058 // @codingStandardsIgnoreStart
2060 # Check for excessive memory usage
2061 if ( $holders->isBig() ) {
2063 # Do the existence check, replace the link holders and clear the array
2064 $holders->replace( $s );
2068 if ( $useLinkPrefixExtension ) {
2069 if ( preg_match( $e2, $s, $m ) ) {
2076 if ( $first_prefix ) {
2077 $prefix = $first_prefix;
2078 $first_prefix = false;
2082 $might_be_img = false;
2084 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2086 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2087 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2088 # the real problem is with the $e1 regex
2091 # Still some problems for cases where the ] is meant to be outside punctuation,
2092 # and no image is in sight. See bug 2095.
2095 && substr( $m[3], 0, 1 ) === ']'
2096 && strpos( $text, '[' ) !== false
2098 $text .= ']'; # so that replaceExternalLinks($text) works later
2099 $m[3] = substr( $m[3], 1 );
2101 # fix up urlencoded title texts
2102 if ( strpos( $m[1], '%' ) !== false ) {
2103 # Should anchors '#' also be rejected?
2104 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) );
2107 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2108 # Invalid, but might be an image with a link in its caption
2109 $might_be_img = true;
2111 if ( strpos( $m[1], '%' ) !== false ) {
2112 $m[1] = rawurldecode( $m[1] );
2115 } else { # Invalid form; output directly
2116 $s .= $prefix . '[[' . $line;
2122 # Don't allow internal links to pages containing
2123 # PROTO: where PROTO is a valid URL protocol; these
2124 # should be external links.
2125 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2126 $s .= $prefix . '[[' . $line;
2130 # Make subpage if necessary
2131 if ( $useSubpages ) {
2132 $link = $this->maybeDoSubpageLink( $origLink, $text );
2137 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2139 # Strip off leading ':'
2140 $link = substr( $link, 1 );
2143 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
2144 if ( $nt === null ) {
2145 $s .= $prefix . '[[' . $line;
2149 $ns = $nt->getNamespace();
2150 $iw = $nt->getInterwiki();
2152 if ( $might_be_img ) { # if this is actually an invalid link
2153 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2156 # look at the next 'line' to see if we can close it there
2158 $next_line = $a->current();
2159 if ( $next_line === false ||
$next_line === null ) {
2162 $m = explode( ']]', $next_line, 3 );
2163 if ( count( $m ) == 3 ) {
2164 # the first ]] closes the inner link, the second the image
2166 $text .= "[[{$m[0]}]]{$m[1]}";
2169 } elseif ( count( $m ) == 2 ) {
2170 # if there's exactly one ]] that's fine, we'll keep looking
2171 $text .= "[[{$m[0]}]]{$m[1]}";
2173 # if $next_line is invalid too, we need look no further
2174 $text .= '[[' . $next_line;
2179 # we couldn't find the end of this imageLink, so output it raw
2180 # but don't ignore what might be perfectly normal links in the text we've examined
2181 $holders->merge( $this->replaceInternalLinks2( $text ) );
2182 $s .= "{$prefix}[[$link|$text";
2183 # note: no $trail, because without an end, there *is* no trail
2186 } else { # it's not an image, so output it raw
2187 $s .= "{$prefix}[[$link|$text";
2188 # note: no $trail, because without an end, there *is* no trail
2193 $wasblank = ( $text == '' );
2197 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
2198 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2199 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2200 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2201 $text = $this->doQuotes( $text );
2204 # Link not escaped by : , create the various objects
2205 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2208 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2209 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2210 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2213 # Bug 24502: filter duplicates
2214 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2215 $this->mLangLinkLanguages
[$iw] = true;
2216 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2219 $s = rtrim( $s . $prefix );
2220 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2224 if ( $ns == NS_FILE
) {
2225 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2227 # if no parameters were passed, $text
2228 # becomes something like "File:Foo.png",
2229 # which we don't want to pass on to the
2233 # recursively parse links inside the image caption
2234 # actually, this will parse them in any other parameters, too,
2235 # but it might be hard to fix that, and it doesn't matter ATM
2236 $text = $this->replaceExternalLinks( $text );
2237 $holders->merge( $this->replaceInternalLinks2( $text ) );
2239 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2240 $s .= $prefix . $this->armorLinks(
2241 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2243 $s .= $prefix . $trail;
2248 if ( $ns == NS_CATEGORY
) {
2249 $s = rtrim( $s . "\n" ); # bug 87
2252 $sortkey = $this->getDefaultSort();
2256 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2257 $sortkey = str_replace( "\n", '', $sortkey );
2258 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2259 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2262 * Strip the whitespace Category links produce, see bug 87
2264 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2270 # Self-link checking. For some languages, variants of the title are checked in
2271 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2272 # for linking to a different variant.
2273 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2274 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2278 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2279 # @todo FIXME: Should do batch file existence checks, see comment below
2280 if ( $ns == NS_MEDIA
) {
2281 # Give extensions a chance to select the file revision for us
2284 Hooks
::run( 'BeforeParserFetchFileAndTitle',
2285 array( $this, $nt, &$options, &$descQuery ) );
2286 # Fetch and register the file (file title may be different via hooks)
2287 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2288 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2289 $s .= $prefix . $this->armorLinks(
2290 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2294 # Some titles, such as valid special pages or files in foreign repos, should
2295 # be shown as bluelinks even though they're not included in the page table
2297 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2298 # batch file existence checks for NS_FILE and NS_MEDIA
2299 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2300 $this->mOutput
->addLink( $nt );
2301 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2303 # Links will be added to the output link list after checking
2304 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2311 * Render a forced-blue link inline; protect against double expansion of
2312 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2313 * Since this little disaster has to split off the trail text to avoid
2314 * breaking URLs in the following text without breaking trails on the
2315 * wiki links, it's been made into a horrible function.
2318 * @param string $text
2319 * @param array|string $query
2320 * @param string $trail
2321 * @param string $prefix
2322 * @return string HTML-wikitext mix oh yuck
2324 public function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2325 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2327 if ( is_string( $query ) ) {
2328 $query = wfCgiToArray( $query );
2330 if ( $text == '' ) {
2331 $text = htmlspecialchars( $nt->getPrefixedText() );
2334 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2336 return $this->armorLinks( $link ) . $trail;
2340 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2341 * going to go through further parsing steps before inline URL expansion.
2343 * Not needed quite as much as it used to be since free links are a bit
2344 * more sensible these days. But bracketed links are still an issue.
2346 * @param string $text More-or-less HTML
2347 * @return string Less-or-more HTML with NOPARSE bits
2349 public function armorLinks( $text ) {
2350 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2351 "{$this->mUniqPrefix}NOPARSE$1", $text );
2355 * Return true if subpage links should be expanded on this page.
2358 public function areSubpagesAllowed() {
2359 # Some namespaces don't allow subpages
2360 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2364 * Handle link to subpage if necessary
2366 * @param string $target The source of the link
2367 * @param string &$text The link text, modified as necessary
2368 * @return string The full name of the link
2371 public function maybeDoSubpageLink( $target, &$text ) {
2372 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2376 * Used by doBlockLevels()
2381 public function closeParagraph() {
2383 if ( $this->mLastSection
!= '' ) {
2384 $result = '</' . $this->mLastSection
. ">\n";
2386 $this->mInPre
= false;
2387 $this->mLastSection
= '';
2392 * getCommon() returns the length of the longest common substring
2393 * of both arguments, starting at the beginning of both.
2396 * @param string $st1
2397 * @param string $st2
2401 public function getCommon( $st1, $st2 ) {
2402 $fl = strlen( $st1 );
2403 $shorter = strlen( $st2 );
2404 if ( $fl < $shorter ) {
2408 for ( $i = 0; $i < $shorter; ++
$i ) {
2409 if ( $st1[$i] != $st2[$i] ) {
2417 * These next three functions open, continue, and close the list
2418 * element appropriate to the prefix character passed into them.
2421 * @param string $char
2425 public function openList( $char ) {
2426 $result = $this->closeParagraph();
2428 if ( '*' === $char ) {
2429 $result .= "<ul><li>";
2430 } elseif ( '#' === $char ) {
2431 $result .= "<ol><li>";
2432 } elseif ( ':' === $char ) {
2433 $result .= "<dl><dd>";
2434 } elseif ( ';' === $char ) {
2435 $result .= "<dl><dt>";
2436 $this->mDTopen
= true;
2438 $result = '<!-- ERR 1 -->';
2446 * @param string $char
2451 public function nextItem( $char ) {
2452 if ( '*' === $char ||
'#' === $char ) {
2453 return "</li>\n<li>";
2454 } elseif ( ':' === $char ||
';' === $char ) {
2456 if ( $this->mDTopen
) {
2459 if ( ';' === $char ) {
2460 $this->mDTopen
= true;
2461 return $close . '<dt>';
2463 $this->mDTopen
= false;
2464 return $close . '<dd>';
2467 return '<!-- ERR 2 -->';
2472 * @param string $char
2477 public function closeList( $char ) {
2478 if ( '*' === $char ) {
2479 $text = "</li></ul>";
2480 } elseif ( '#' === $char ) {
2481 $text = "</li></ol>";
2482 } elseif ( ':' === $char ) {
2483 if ( $this->mDTopen
) {
2484 $this->mDTopen
= false;
2485 $text = "</dt></dl>";
2487 $text = "</dd></dl>";
2490 return '<!-- ERR 3 -->';
2497 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2499 * @param string $text
2500 * @param bool $linestart Whether or not this is at the start of a line.
2502 * @return string The lists rendered as HTML
2504 public function doBlockLevels( $text, $linestart ) {
2506 # Parsing through the text line by line. The main thing
2507 # happening here is handling of block-level elements p, pre,
2508 # and making lists from lines starting with * # : etc.
2510 $textLines = StringUtils
::explode( "\n", $text );
2512 $lastPrefix = $output = '';
2513 $this->mDTopen
= $inBlockElem = false;
2515 $paragraphStack = false;
2516 $inBlockquote = false;
2518 foreach ( $textLines as $oLine ) {
2520 if ( !$linestart ) {
2530 $lastPrefixLength = strlen( $lastPrefix );
2531 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2532 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2533 # If not in a <pre> element, scan for and figure out what prefixes are there.
2534 if ( !$this->mInPre
) {
2535 # Multiple prefixes may abut each other for nested lists.
2536 $prefixLength = strspn( $oLine, '*#:;' );
2537 $prefix = substr( $oLine, 0, $prefixLength );
2540 # ; and : are both from definition-lists, so they're equivalent
2541 # for the purposes of determining whether or not we need to open/close
2543 $prefix2 = str_replace( ';', ':', $prefix );
2544 $t = substr( $oLine, $prefixLength );
2545 $this->mInPre
= (bool)$preOpenMatch;
2547 # Don't interpret any other prefixes in preformatted text
2549 $prefix = $prefix2 = '';
2554 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2555 # Same as the last item, so no need to deal with nesting or opening stuff
2556 $output .= $this->nextItem( substr( $prefix, -1 ) );
2557 $paragraphStack = false;
2559 if ( substr( $prefix, -1 ) === ';' ) {
2560 # The one nasty exception: definition lists work like this:
2561 # ; title : definition text
2562 # So we check for : in the remainder text to split up the
2563 # title and definition, without b0rking links.
2565 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2567 $output .= $term . $this->nextItem( ':' );
2570 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2571 # We need to open or close prefixes, or both.
2573 # Either open or close a level...
2574 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2575 $paragraphStack = false;
2577 # Close all the prefixes which aren't shared.
2578 while ( $commonPrefixLength < $lastPrefixLength ) {
2579 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2580 --$lastPrefixLength;
2583 # Continue the current prefix if appropriate.
2584 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2585 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2588 # Open prefixes where appropriate.
2589 if ( $lastPrefix && $prefixLength > $commonPrefixLength ) {
2592 while ( $prefixLength > $commonPrefixLength ) {
2593 $char = substr( $prefix, $commonPrefixLength, 1 );
2594 $output .= $this->openList( $char );
2596 if ( ';' === $char ) {
2597 # @todo FIXME: This is dupe of code above
2598 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2600 $output .= $term . $this->nextItem( ':' );
2603 ++
$commonPrefixLength;
2605 if ( !$prefixLength && $lastPrefix ) {
2608 $lastPrefix = $prefix2;
2611 # If we have no prefixes, go to paragraph mode.
2612 if ( 0 == $prefixLength ) {
2613 # No prefix (not in list)--go to paragraph mode
2614 # XXX: use a stack for nestable elements like span, table and div
2615 $openmatch = preg_match(
2616 '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|'
2617 . '<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS',
2620 $closematch = preg_match(
2621 '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'
2622 . '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|<\\/mw:|'
2623 . $this->mUniqPrefix
2624 . '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS',
2628 if ( $openmatch ||
$closematch ) {
2629 $paragraphStack = false;
2630 # @todo bug 5718: paragraph closed
2631 $output .= $this->closeParagraph();
2632 if ( $preOpenMatch && !$preCloseMatch ) {
2633 $this->mInPre
= true;
2636 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t, $bqMatch, PREG_OFFSET_CAPTURE
, $bqOffset ) ) {
2637 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
2638 $bqOffset = $bqMatch[0][1] +
strlen( $bqMatch[0][0] );
2640 $inBlockElem = !$closematch;
2641 } elseif ( !$inBlockElem && !$this->mInPre
) {
2642 if ( ' ' == substr( $t, 0, 1 )
2643 && ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' )
2647 if ( $this->mLastSection
!== 'pre' ) {
2648 $paragraphStack = false;
2649 $output .= $this->closeParagraph() . '<pre>';
2650 $this->mLastSection
= 'pre';
2652 $t = substr( $t, 1 );
2655 if ( trim( $t ) === '' ) {
2656 if ( $paragraphStack ) {
2657 $output .= $paragraphStack . '<br />';
2658 $paragraphStack = false;
2659 $this->mLastSection
= 'p';
2661 if ( $this->mLastSection
!== 'p' ) {
2662 $output .= $this->closeParagraph();
2663 $this->mLastSection
= '';
2664 $paragraphStack = '<p>';
2666 $paragraphStack = '</p><p>';
2670 if ( $paragraphStack ) {
2671 $output .= $paragraphStack;
2672 $paragraphStack = false;
2673 $this->mLastSection
= 'p';
2674 } elseif ( $this->mLastSection
!== 'p' ) {
2675 $output .= $this->closeParagraph() . '<p>';
2676 $this->mLastSection
= 'p';
2682 # somewhere above we forget to get out of pre block (bug 785)
2683 if ( $preCloseMatch && $this->mInPre
) {
2684 $this->mInPre
= false;
2686 if ( $paragraphStack === false ) {
2688 if ( $prefixLength === 0 ) {
2693 while ( $prefixLength ) {
2694 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2696 if ( !$prefixLength ) {
2700 if ( $this->mLastSection
!= '' ) {
2701 $output .= '</' . $this->mLastSection
. '>';
2702 $this->mLastSection
= '';
2709 * Split up a string on ':', ignoring any occurrences inside tags
2710 * to prevent illegal overlapping.
2712 * @param string $str The string to split
2713 * @param string &$before Set to everything before the ':'
2714 * @param string &$after Set to everything after the ':'
2715 * @throws MWException
2716 * @return string The position of the ':', or false if none found
2718 public function findColonNoLinks( $str, &$before, &$after ) {
2720 $pos = strpos( $str, ':' );
2721 if ( $pos === false ) {
2726 $lt = strpos( $str, '<' );
2727 if ( $lt === false ||
$lt > $pos ) {
2728 # Easy; no tag nesting to worry about
2729 $before = substr( $str, 0, $pos );
2730 $after = substr( $str, $pos +
1 );
2734 # Ugly state machine to walk through avoiding tags.
2735 $state = self
::COLON_STATE_TEXT
;
2737 $len = strlen( $str );
2738 for ( $i = 0; $i < $len; $i++
) {
2742 # (Using the number is a performance hack for common cases)
2743 case 0: # self::COLON_STATE_TEXT:
2746 # Could be either a <start> tag or an </end> tag
2747 $state = self
::COLON_STATE_TAGSTART
;
2750 if ( $stack == 0 ) {
2752 $before = substr( $str, 0, $i );
2753 $after = substr( $str, $i +
1 );
2756 # Embedded in a tag; don't break it.
2759 # Skip ahead looking for something interesting
2760 $colon = strpos( $str, ':', $i );
2761 if ( $colon === false ) {
2762 # Nothing else interesting
2765 $lt = strpos( $str, '<', $i );
2766 if ( $stack === 0 ) {
2767 if ( $lt === false ||
$colon < $lt ) {
2769 $before = substr( $str, 0, $colon );
2770 $after = substr( $str, $colon +
1 );
2774 if ( $lt === false ) {
2775 # Nothing else interesting to find; abort!
2776 # We're nested, but there's no close tags left. Abort!
2779 # Skip ahead to next tag start
2781 $state = self
::COLON_STATE_TAGSTART
;
2784 case 1: # self::COLON_STATE_TAG:
2789 $state = self
::COLON_STATE_TEXT
;
2792 # Slash may be followed by >?
2793 $state = self
::COLON_STATE_TAGSLASH
;
2799 case 2: # self::COLON_STATE_TAGSTART:
2802 $state = self
::COLON_STATE_CLOSETAG
;
2805 $state = self
::COLON_STATE_COMMENT
;
2808 # Illegal early close? This shouldn't happen D:
2809 $state = self
::COLON_STATE_TEXT
;
2812 $state = self
::COLON_STATE_TAG
;
2815 case 3: # self::COLON_STATE_CLOSETAG:
2820 wfDebug( __METHOD__
. ": Invalid input; too many close tags\n" );
2823 $state = self
::COLON_STATE_TEXT
;
2826 case self
::COLON_STATE_TAGSLASH
:
2828 # Yes, a self-closed tag <blah/>
2829 $state = self
::COLON_STATE_TEXT
;
2831 # Probably we're jumping the gun, and this is an attribute
2832 $state = self
::COLON_STATE_TAG
;
2835 case 5: # self::COLON_STATE_COMMENT:
2837 $state = self
::COLON_STATE_COMMENTDASH
;
2840 case self
::COLON_STATE_COMMENTDASH
:
2842 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2844 $state = self
::COLON_STATE_COMMENT
;
2847 case self
::COLON_STATE_COMMENTDASHDASH
:
2849 $state = self
::COLON_STATE_TEXT
;
2851 $state = self
::COLON_STATE_COMMENT
;
2855 throw new MWException( "State machine error in " . __METHOD__
);
2859 wfDebug( __METHOD__
. ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2866 * Return value of a magic variable (like PAGENAME)
2871 * @param bool|PPFrame $frame
2873 * @throws MWException
2876 public function getVariableValue( $index, $frame = false ) {
2877 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2878 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2880 if ( is_null( $this->mTitle
) ) {
2881 // If no title set, bad things are going to happen
2882 // later. Title should always be set since this
2883 // should only be called in the middle of a parse
2884 // operation (but the unit-tests do funky stuff)
2885 throw new MWException( __METHOD__
. ' Should only be '
2886 . ' called while parsing (no title set)' );
2890 * Some of these require message or data lookups and can be
2891 * expensive to check many times.
2893 if ( Hooks
::run( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2894 if ( isset( $this->mVarCache
[$index] ) ) {
2895 return $this->mVarCache
[$index];
2899 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2900 Hooks
::run( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2902 $pageLang = $this->getFunctionLang();
2908 case 'currentmonth':
2909 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ) );
2911 case 'currentmonth1':
2912 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2914 case 'currentmonthname':
2915 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2917 case 'currentmonthnamegen':
2918 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2920 case 'currentmonthabbrev':
2921 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2924 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ) );
2927 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ) );
2930 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ) );
2933 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2935 case 'localmonthname':
2936 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2938 case 'localmonthnamegen':
2939 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2941 case 'localmonthabbrev':
2942 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2945 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ) );
2948 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ) );
2951 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2954 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2956 case 'fullpagename':
2957 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2959 case 'fullpagenamee':
2960 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2963 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2965 case 'subpagenamee':
2966 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2968 case 'rootpagename':
2969 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2971 case 'rootpagenamee':
2972 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
2975 $this->mTitle
->getRootText()
2978 case 'basepagename':
2979 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2981 case 'basepagenamee':
2982 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
2985 $this->mTitle
->getBaseText()
2988 case 'talkpagename':
2989 if ( $this->mTitle
->canTalk() ) {
2990 $talkPage = $this->mTitle
->getTalkPage();
2991 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2996 case 'talkpagenamee':
2997 if ( $this->mTitle
->canTalk() ) {
2998 $talkPage = $this->mTitle
->getTalkPage();
2999 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
3004 case 'subjectpagename':
3005 $subjPage = $this->mTitle
->getSubjectPage();
3006 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
3008 case 'subjectpagenamee':
3009 $subjPage = $this->mTitle
->getSubjectPage();
3010 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
3012 case 'pageid': // requested in bug 23427
3013 $pageid = $this->getTitle()->getArticleID();
3014 if ( $pageid == 0 ) {
3015 # 0 means the page doesn't exist in the database,
3016 # which means the user is previewing a new page.
3017 # The vary-revision flag must be set, because the magic word
3018 # will have a different value once the page is saved.
3019 $this->mOutput
->setFlag( 'vary-revision' );
3020 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
3022 $value = $pageid ?
$pageid : null;
3025 # Let the edit saving system know we should parse the page
3026 # *after* a revision ID has been assigned.
3027 $this->mOutput
->setFlag( 'vary-revision' );
3028 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
3029 $value = $this->mRevisionId
;
3032 # Let the edit saving system know we should parse the page
3033 # *after* a revision ID has been assigned. This is for null edits.
3034 $this->mOutput
->setFlag( 'vary-revision' );
3035 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
3036 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
3038 case 'revisionday2':
3039 # Let the edit saving system know we should parse the page
3040 # *after* a revision ID has been assigned. This is for null edits.
3041 $this->mOutput
->setFlag( 'vary-revision' );
3042 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
3043 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
3045 case 'revisionmonth':
3046 # Let the edit saving system know we should parse the page
3047 # *after* a revision ID has been assigned. This is for null edits.
3048 $this->mOutput
->setFlag( 'vary-revision' );
3049 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
3050 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
3052 case 'revisionmonth1':
3053 # Let the edit saving system know we should parse the page
3054 # *after* a revision ID has been assigned. This is for null edits.
3055 $this->mOutput
->setFlag( 'vary-revision' );
3056 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
3057 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
3059 case 'revisionyear':
3060 # Let the edit saving system know we should parse the page
3061 # *after* a revision ID has been assigned. This is for null edits.
3062 $this->mOutput
->setFlag( 'vary-revision' );
3063 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
3064 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
3066 case 'revisiontimestamp':
3067 # Let the edit saving system know we should parse the page
3068 # *after* a revision ID has been assigned. This is for null edits.
3069 $this->mOutput
->setFlag( 'vary-revision' );
3070 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
3071 $value = $this->getRevisionTimestamp();
3073 case 'revisionuser':
3074 # Let the edit saving system know we should parse the page
3075 # *after* a revision ID has been assigned. This is for null edits.
3076 $this->mOutput
->setFlag( 'vary-revision' );
3077 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
3078 $value = $this->getRevisionUser();
3080 case 'revisionsize':
3081 # Let the edit saving system know we should parse the page
3082 # *after* a revision ID has been assigned. This is for null edits.
3083 $this->mOutput
->setFlag( 'vary-revision' );
3084 wfDebug( __METHOD__
. ": {{REVISIONSIZE}} used, setting vary-revision...\n" );
3085 $value = $this->getRevisionSize();
3088 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3091 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3093 case 'namespacenumber':
3094 $value = $this->mTitle
->getNamespace();
3097 $value = $this->mTitle
->canTalk()
3098 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
3102 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
3104 case 'subjectspace':
3105 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
3107 case 'subjectspacee':
3108 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
3110 case 'currentdayname':
3111 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
3114 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
3117 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
3120 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
3123 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3124 # int to remove the padding
3125 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
3128 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
3130 case 'localdayname':
3131 $value = $pageLang->getWeekdayName(
3132 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
3136 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
3139 $value = $pageLang->time(
3140 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
3146 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
3149 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3150 # int to remove the padding
3151 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
3154 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
3156 case 'numberofarticles':
3157 $value = $pageLang->formatNum( SiteStats
::articles() );
3159 case 'numberoffiles':
3160 $value = $pageLang->formatNum( SiteStats
::images() );
3162 case 'numberofusers':
3163 $value = $pageLang->formatNum( SiteStats
::users() );
3165 case 'numberofactiveusers':
3166 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
3168 case 'numberofpages':
3169 $value = $pageLang->formatNum( SiteStats
::pages() );
3171 case 'numberofadmins':
3172 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
3174 case 'numberofedits':
3175 $value = $pageLang->formatNum( SiteStats
::edits() );
3177 case 'currenttimestamp':
3178 $value = wfTimestamp( TS_MW
, $ts );
3180 case 'localtimestamp':
3181 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
3183 case 'currentversion':
3184 $value = SpecialVersion
::getVersion();
3187 return $wgArticlePath;
3193 return $wgServerName;
3195 return $wgScriptPath;
3197 return $wgStylePath;
3198 case 'directionmark':
3199 return $pageLang->getDirMark();
3200 case 'contentlanguage':
3201 global $wgLanguageCode;
3202 return $wgLanguageCode;
3203 case 'cascadingsources':
3204 $value = CoreParserFunctions
::cascadingsources( $this );
3209 'ParserGetVariableValueSwitch',
3210 array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame )
3217 $this->mVarCache
[$index] = $value;
3224 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3228 public function initialiseVariables() {
3229 $variableIDs = MagicWord
::getVariableIDs();
3230 $substIDs = MagicWord
::getSubstIDs();
3232 $this->mVariables
= new MagicWordArray( $variableIDs );
3233 $this->mSubstWords
= new MagicWordArray( $substIDs );
3237 * Preprocess some wikitext and return the document tree.
3238 * This is the ghost of replace_variables().
3240 * @param string $text The text to parse
3241 * @param int $flags Bitwise combination of:
3242 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
3243 * included. Default is to assume a direct page view.
3245 * The generated DOM tree must depend only on the input text and the flags.
3246 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3248 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3249 * change in the DOM tree for a given text, must be passed through the section identifier
3250 * in the section edit link and thus back to extractSections().
3252 * The output of this function is currently only cached in process memory, but a persistent
3253 * cache may be implemented at a later date which takes further advantage of these strict
3254 * dependency requirements.
3258 public function preprocessToDom( $text, $flags = 0 ) {
3259 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3264 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3270 public static function splitWhitespace( $s ) {
3271 $ltrimmed = ltrim( $s );
3272 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3273 $trimmed = rtrim( $ltrimmed );
3274 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3276 $w2 = substr( $ltrimmed, -$diff );
3280 return array( $w1, $trimmed, $w2 );
3284 * Replace magic variables, templates, and template arguments
3285 * with the appropriate text. Templates are substituted recursively,
3286 * taking care to avoid infinite loops.
3288 * Note that the substitution depends on value of $mOutputType:
3289 * self::OT_WIKI: only {{subst:}} templates
3290 * self::OT_PREPROCESS: templates but not extension tags
3291 * self::OT_HTML: all templates and extension tags
3293 * @param string $text The text to transform
3294 * @param bool|PPFrame $frame Object describing the arguments passed to the
3295 * template. Arguments may also be provided as an associative array, as
3296 * was the usual case before MW1.12. Providing arguments this way may be
3297 * useful for extensions wishing to perform variable replacement
3299 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3300 * double-brace expansion.
3303 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3304 # Is there any text? Also, Prevent too big inclusions!
3305 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3309 if ( $frame === false ) {
3310 $frame = $this->getPreprocessor()->newFrame();
3311 } elseif ( !( $frame instanceof PPFrame
) ) {
3312 wfDebug( __METHOD__
. " called using plain parameters instead of "
3313 . "a PPFrame instance. Creating custom frame.\n" );
3314 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3317 $dom = $this->preprocessToDom( $text );
3318 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3319 $text = $frame->expand( $dom, $flags );
3325 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3327 * @param array $args
3331 public static function createAssocArgs( $args ) {
3332 $assocArgs = array();
3334 foreach ( $args as $arg ) {
3335 $eqpos = strpos( $arg, '=' );
3336 if ( $eqpos === false ) {
3337 $assocArgs[$index++
] = $arg;
3339 $name = trim( substr( $arg, 0, $eqpos ) );
3340 $value = trim( substr( $arg, $eqpos +
1 ) );
3341 if ( $value === false ) {
3344 if ( $name !== false ) {
3345 $assocArgs[$name] = $value;
3354 * Warn the user when a parser limitation is reached
3355 * Will warn at most once the user per limitation type
3357 * @param string $limitationType Should be one of:
3358 * 'expensive-parserfunction' (corresponding messages:
3359 * 'expensive-parserfunction-warning',
3360 * 'expensive-parserfunction-category')
3361 * 'post-expand-template-argument' (corresponding messages:
3362 * 'post-expand-template-argument-warning',
3363 * 'post-expand-template-argument-category')
3364 * 'post-expand-template-inclusion' (corresponding messages:
3365 * 'post-expand-template-inclusion-warning',
3366 * 'post-expand-template-inclusion-category')
3367 * 'node-count-exceeded' (corresponding messages:
3368 * 'node-count-exceeded-warning',
3369 * 'node-count-exceeded-category')
3370 * 'expansion-depth-exceeded' (corresponding messages:
3371 * 'expansion-depth-exceeded-warning',
3372 * 'expansion-depth-exceeded-category')
3373 * @param string|int|null $current Current value
3374 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3375 * exceeded, provide the values (optional)
3377 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3378 # does no harm if $current and $max are present but are unnecessary for the message
3379 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3380 ->inLanguage( $this->mOptions
->getUserLangObj() )->text();
3381 $this->mOutput
->addWarning( $warning );
3382 $this->addTrackingCategory( "$limitationType-category" );
3386 * Return the text of a template, after recursively
3387 * replacing any variables or templates within the template.
3389 * @param array $piece The parts of the template
3390 * $piece['title']: the title, i.e. the part before the |
3391 * $piece['parts']: the parameter array
3392 * $piece['lineStart']: whether the brace was at the start of a line
3393 * @param PPFrame $frame The current frame, contains template arguments
3395 * @return string The text of the template
3397 public function braceSubstitution( $piece, $frame ) {
3401 // $text has been filled
3403 // wiki markup in $text should be escaped
3405 // $text is HTML, armour it against wikitext transformation
3407 // Force interwiki transclusion to be done in raw mode not rendered
3408 $forceRawInterwiki = false;
3409 // $text is a DOM node needing expansion in a child frame
3410 $isChildObj = false;
3411 // $text is a DOM node needing expansion in the current frame
3412 $isLocalObj = false;
3414 # Title object, where $text came from
3417 # $part1 is the bit before the first |, and must contain only title characters.
3418 # Various prefixes will be stripped from it later.
3419 $titleWithSpaces = $frame->expand( $piece['title'] );
3420 $part1 = trim( $titleWithSpaces );
3423 # Original title text preserved for various purposes
3424 $originalTitle = $part1;
3426 # $args is a list of argument nodes, starting from index 0, not including $part1
3427 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3428 # below won't work b/c this $args isn't an object
3429 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3431 $profileSection = null; // profile templates
3436 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3438 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3439 # Decide whether to expand template or keep wikitext as-is.
3440 if ( $this->ot
['wiki'] ) {
3441 if ( $substMatch === false ) {
3442 $literal = true; # literal when in PST with no prefix
3444 $literal = false; # expand when in PST with subst: or safesubst:
3447 if ( $substMatch == 'subst' ) {
3448 $literal = true; # literal when not in PST with plain subst:
3450 $literal = false; # expand when not in PST with safesubst: or no prefix
3454 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3461 if ( !$found && $args->getLength() == 0 ) {
3462 $id = $this->mVariables
->matchStartToEnd( $part1 );
3463 if ( $id !== false ) {
3464 $text = $this->getVariableValue( $id, $frame );
3465 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3466 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3472 # MSG, MSGNW and RAW
3475 $mwMsgnw = MagicWord
::get( 'msgnw' );
3476 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3479 # Remove obsolete MSG:
3480 $mwMsg = MagicWord
::get( 'msg' );
3481 $mwMsg->matchStartAndRemove( $part1 );
3485 $mwRaw = MagicWord
::get( 'raw' );
3486 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3487 $forceRawInterwiki = true;
3494 $colonPos = strpos( $part1, ':' );
3495 if ( $colonPos !== false ) {
3496 $func = substr( $part1, 0, $colonPos );
3497 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3498 for ( $i = 0; $i < $args->getLength(); $i++
) {
3499 $funcArgs[] = $args->item( $i );
3502 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3503 } catch ( Exception
$ex ) {
3507 # The interface for parser functions allows for extracting
3508 # flags into the local scope. Extract any forwarded flags
3514 # Finish mangling title and then check for loops.
3515 # Set $title to a Title object and $titleText to the PDBK
3518 # Split the title into page and subpage
3520 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3521 if ( $part1 !== $relative ) {
3523 $ns = $this->mTitle
->getNamespace();
3525 $title = Title
::newFromText( $part1, $ns );
3527 $titleText = $title->getPrefixedText();
3528 # Check for language variants if the template is not found
3529 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3530 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3532 # Do recursion depth check
3533 $limit = $this->mOptions
->getMaxTemplateDepth();
3534 if ( $frame->depth
>= $limit ) {
3536 $text = '<span class="error">'
3537 . wfMessage( 'parser-template-recursion-depth-warning' )
3538 ->numParams( $limit )->inContentLanguage()->text()
3544 # Load from database
3545 if ( !$found && $title ) {
3546 $profileSection = $this->mProfiler
->scopedProfileIn( $title->getPrefixedDBkey() );
3547 if ( !$title->isExternal() ) {
3548 if ( $title->isSpecialPage()
3549 && $this->mOptions
->getAllowSpecialInclusion()
3550 && $this->ot
['html']
3552 // Pass the template arguments as URL parameters.
3553 // "uselang" will have no effect since the Language object
3554 // is forced to the one defined in ParserOptions.
3555 $pageArgs = array();
3556 $argsLength = $args->getLength();
3557 for ( $i = 0; $i < $argsLength; $i++
) {
3558 $bits = $args->item( $i )->splitArg();
3559 if ( strval( $bits['index'] ) === '' ) {
3560 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3561 $value = trim( $frame->expand( $bits['value'] ) );
3562 $pageArgs[$name] = $value;
3566 // Create a new context to execute the special page
3567 $context = new RequestContext
;
3568 $context->setTitle( $title );
3569 $context->setRequest( new FauxRequest( $pageArgs ) );
3570 $context->setUser( $this->getUser() );
3571 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3572 $ret = SpecialPageFactory
::capturePath( $title, $context );
3574 $text = $context->getOutput()->getHTML();
3575 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3578 $this->disableCache();
3580 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3581 $found = false; # access denied
3582 wfDebug( __METHOD__
. ": template inclusion denied for " .
3583 $title->getPrefixedDBkey() . "\n" );
3585 list( $text, $title ) = $this->getTemplateDom( $title );
3586 if ( $text !== false ) {
3592 # If the title is valid but undisplayable, make a link to it
3593 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3594 $text = "[[:$titleText]]";
3597 } elseif ( $title->isTrans() ) {
3598 # Interwiki transclusion
3599 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3600 $text = $this->interwikiTransclude( $title, 'render' );
3603 $text = $this->interwikiTransclude( $title, 'raw' );
3604 # Preprocess it like a template
3605 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3611 # Do infinite loop check
3612 # This has to be done after redirect resolution to avoid infinite loops via redirects
3613 if ( !$frame->loopCheck( $title ) ) {
3615 $text = '<span class="error">'
3616 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3618 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3622 # If we haven't found text to substitute by now, we're done
3623 # Recover the source wikitext and return it
3625 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3626 if ( $profileSection ) {
3627 $this->mProfiler
->scopedProfileOut( $profileSection );
3629 return array( 'object' => $text );
3632 # Expand DOM-style return values in a child frame
3633 if ( $isChildObj ) {
3634 # Clean up argument array
3635 $newFrame = $frame->newChild( $args, $title );
3638 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3639 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3640 # Expansion is eligible for the empty-frame cache
3641 $text = $newFrame->cachedExpand( $titleText, $text );
3643 # Uncached expansion
3644 $text = $newFrame->expand( $text );
3647 if ( $isLocalObj && $nowiki ) {
3648 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3649 $isLocalObj = false;
3652 if ( $profileSection ) {
3653 $this->mProfiler
->scopedProfileOut( $profileSection );
3656 # Replace raw HTML by a placeholder
3658 $text = $this->insertStripItem( $text );
3659 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3660 # Escape nowiki-style return values
3661 $text = wfEscapeWikiText( $text );
3662 } elseif ( is_string( $text )
3663 && !$piece['lineStart']
3664 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3666 # Bug 529: if the template begins with a table or block-level
3667 # element, it should be treated as beginning a new line.
3668 # This behavior is somewhat controversial.
3669 $text = "\n" . $text;
3672 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3673 # Error, oversize inclusion
3674 if ( $titleText !== false ) {
3675 # Make a working, properly escaped link if possible (bug 23588)
3676 $text = "[[:$titleText]]";
3678 # This will probably not be a working link, but at least it may
3679 # provide some hint of where the problem is
3680 preg_replace( '/^:/', '', $originalTitle );
3681 $text = "[[:$originalTitle]]";
3683 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3684 . 'post-expand include size too large -->' );
3685 $this->limitationWarn( 'post-expand-template-inclusion' );
3688 if ( $isLocalObj ) {
3689 $ret = array( 'object' => $text );
3691 $ret = array( 'text' => $text );
3698 * Call a parser function and return an array with text and flags.
3700 * The returned array will always contain a boolean 'found', indicating
3701 * whether the parser function was found or not. It may also contain the
3703 * text: string|object, resulting wikitext or PP DOM object
3704 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3705 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3706 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3707 * nowiki: bool, wiki markup in $text should be escaped
3710 * @param PPFrame $frame The current frame, contains template arguments
3711 * @param string $function Function name
3712 * @param array $args Arguments to the function
3713 * @throws MWException
3716 public function callParserFunction( $frame, $function, array $args = array() ) {
3720 # Case sensitive functions
3721 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3722 $function = $this->mFunctionSynonyms
[1][$function];
3724 # Case insensitive functions
3725 $function = $wgContLang->lc( $function );
3726 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3727 $function = $this->mFunctionSynonyms
[0][$function];
3729 return array( 'found' => false );
3733 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3735 # Workaround for PHP bug 35229 and similar
3736 if ( !is_callable( $callback ) ) {
3737 throw new MWException( "Tag hook for $function is not callable\n" );
3740 $allArgs = array( &$this );
3741 if ( $flags & self
::SFH_OBJECT_ARGS
) {
3742 # Convert arguments to PPNodes and collect for appending to $allArgs
3743 $funcArgs = array();
3744 foreach ( $args as $k => $v ) {
3745 if ( $v instanceof PPNode ||
$k === 0 ) {
3748 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( array( $k => $v ) )->item( 0 );
3752 # Add a frame parameter, and pass the arguments as an array
3753 $allArgs[] = $frame;
3754 $allArgs[] = $funcArgs;
3756 # Convert arguments to plain text and append to $allArgs
3757 foreach ( $args as $k => $v ) {
3758 if ( $v instanceof PPNode
) {
3759 $allArgs[] = trim( $frame->expand( $v ) );
3760 } elseif ( is_int( $k ) && $k >= 0 ) {
3761 $allArgs[] = trim( $v );
3763 $allArgs[] = trim( "$k=$v" );
3768 $result = call_user_func_array( $callback, $allArgs );
3770 # The interface for function hooks allows them to return a wikitext
3771 # string or an array containing the string and any flags. This mungs
3772 # things around to match what this method should return.
3773 if ( !is_array( $result ) ) {
3779 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3780 $result['text'] = $result[0];
3782 unset( $result[0] );
3789 $preprocessFlags = 0;
3790 if ( isset( $result['noparse'] ) ) {
3791 $noparse = $result['noparse'];
3793 if ( isset( $result['preprocessFlags'] ) ) {
3794 $preprocessFlags = $result['preprocessFlags'];
3798 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3799 $result['isChildObj'] = true;
3806 * Get the semi-parsed DOM representation of a template with a given title,
3807 * and its redirect destination title. Cached.
3809 * @param Title $title
3813 public function getTemplateDom( $title ) {
3814 $cacheTitle = $title;
3815 $titleText = $title->getPrefixedDBkey();
3817 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3818 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3819 $title = Title
::makeTitle( $ns, $dbk );
3820 $titleText = $title->getPrefixedDBkey();
3822 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3823 return array( $this->mTplDomCache
[$titleText], $title );
3826 # Cache miss, go to the database
3827 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3829 if ( $text === false ) {
3830 $this->mTplDomCache
[$titleText] = false;
3831 return array( false, $title );
3834 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3835 $this->mTplDomCache
[$titleText] = $dom;
3837 if ( !$title->equals( $cacheTitle ) ) {
3838 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3839 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3842 return array( $dom, $title );
3846 * Fetch the current revision of a given title. Note that the revision
3847 * (and even the title) may not exist in the database, so everything
3848 * contributing to the output of the parser should use this method
3849 * where possible, rather than getting the revisions themselves. This
3850 * method also caches its results, so using it benefits performance.
3853 * @param Title $title
3856 public function fetchCurrentRevisionOfTitle( $title ) {
3857 $cacheKey = $title->getPrefixedDBkey();
3858 if ( !$this->currentRevisionCache
) {
3859 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3861 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3862 $this->currentRevisionCache
->set( $cacheKey,
3863 // Defaults to Parser::statelessFetchRevision()
3864 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3867 return $this->currentRevisionCache
->get( $cacheKey );
3871 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3872 * without passing them on to it.
3875 * @param Title $title
3876 * @param Parser|bool $parser
3879 public static function statelessFetchRevision( $title, $parser = false ) {
3880 return Revision
::newFromTitle( $title );
3884 * Fetch the unparsed text of a template and register a reference to it.
3885 * @param Title $title
3886 * @return array ( string or false, Title )
3888 public function fetchTemplateAndTitle( $title ) {
3889 // Defaults to Parser::statelessFetchTemplate()
3890 $templateCb = $this->mOptions
->getTemplateCallback();
3891 $stuff = call_user_func( $templateCb, $title, $this );
3892 $text = $stuff['text'];
3893 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3894 if ( isset( $stuff['deps'] ) ) {
3895 foreach ( $stuff['deps'] as $dep ) {
3896 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3897 if ( $dep['title']->equals( $this->getTitle() ) ) {
3898 // If we transclude ourselves, the final result
3899 // will change based on the new version of the page
3900 $this->mOutput
->setFlag( 'vary-revision' );
3904 return array( $text, $finalTitle );
3908 * Fetch the unparsed text of a template and register a reference to it.
3909 * @param Title $title
3910 * @return string|bool
3912 public function fetchTemplate( $title ) {
3913 $rv = $this->fetchTemplateAndTitle( $title );
3918 * Static function to get a template
3919 * Can be overridden via ParserOptions::setTemplateCallback().
3921 * @param Title $title
3922 * @param bool|Parser $parser
3926 public static function statelessFetchTemplate( $title, $parser = false ) {
3927 $text = $skip = false;
3928 $finalTitle = $title;
3931 # Loop to fetch the article, with up to 1 redirect
3932 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3933 # Give extensions a chance to select the revision instead
3934 $id = false; # Assume current
3935 Hooks
::run( 'BeforeParserFetchTemplateAndtitle',
3936 array( $parser, $title, &$skip, &$id ) );
3942 'page_id' => $title->getArticleID(),
3949 $rev = Revision
::newFromId( $id );
3950 } elseif ( $parser ) {
3951 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3953 $rev = Revision
::newFromTitle( $title );
3955 $rev_id = $rev ?
$rev->getId() : 0;
3956 # If there is no current revision, there is no page
3957 if ( $id === false && !$rev ) {
3958 $linkCache = LinkCache
::singleton();
3959 $linkCache->addBadLinkObj( $title );
3964 'page_id' => $title->getArticleID(),
3965 'rev_id' => $rev_id );
3966 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3967 # We fetched a rev from a different title; register it too...
3969 'title' => $rev->getTitle(),
3970 'page_id' => $rev->getPage(),
3971 'rev_id' => $rev_id );
3975 $content = $rev->getContent();
3976 $text = $content ?
$content->getWikitextForTransclusion() : null;
3978 if ( $text === false ||
$text === null ) {
3982 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3984 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3985 if ( !$message->exists() ) {
3989 $content = $message->content();
3990 $text = $message->plain();
3998 $finalTitle = $title;
3999 $title = $content->getRedirectTarget();
4003 'finalTitle' => $finalTitle,
4008 * Fetch a file and its title and register a reference to it.
4009 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4010 * @param Title $title
4011 * @param array $options Array of options to RepoGroup::findFile
4014 public function fetchFile( $title, $options = array() ) {
4015 $res = $this->fetchFileAndTitle( $title, $options );
4020 * Fetch a file and its title and register a reference to it.
4021 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4022 * @param Title $title
4023 * @param array $options Array of options to RepoGroup::findFile
4024 * @return array ( File or false, Title of file )
4026 public function fetchFileAndTitle( $title, $options = array() ) {
4027 $file = $this->fetchFileNoRegister( $title, $options );
4029 $time = $file ?
$file->getTimestamp() : false;
4030 $sha1 = $file ?
$file->getSha1() : false;
4031 # Register the file as a dependency...
4032 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4033 if ( $file && !$title->equals( $file->getTitle() ) ) {
4034 # Update fetched file title
4035 $title = $file->getTitle();
4036 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4038 return array( $file, $title );
4042 * Helper function for fetchFileAndTitle.
4044 * Also useful if you need to fetch a file but not use it yet,
4045 * for example to get the file's handler.
4047 * @param Title $title
4048 * @param array $options Array of options to RepoGroup::findFile
4051 protected function fetchFileNoRegister( $title, $options = array() ) {
4052 if ( isset( $options['broken'] ) ) {
4053 $file = false; // broken thumbnail forced by hook
4054 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
4055 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
4056 } else { // get by (name,timestamp)
4057 $file = wfFindFile( $title, $options );
4063 * Transclude an interwiki link.
4065 * @param Title $title
4066 * @param string $action
4070 public function interwikiTransclude( $title, $action ) {
4071 global $wgEnableScaryTranscluding;
4073 if ( !$wgEnableScaryTranscluding ) {
4074 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
4077 $url = $title->getFullURL( array( 'action' => $action ) );
4079 if ( strlen( $url ) > 255 ) {
4080 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
4082 return $this->fetchScaryTemplateMaybeFromCache( $url );
4086 * @param string $url
4087 * @return mixed|string
4089 public function fetchScaryTemplateMaybeFromCache( $url ) {
4090 global $wgTranscludeCacheExpiry;
4091 $dbr = wfGetDB( DB_SLAVE
);
4092 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
4093 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
4094 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
4096 return $obj->tc_contents
;
4099 $req = MWHttpRequest
::factory( $url, array(), __METHOD__
);
4100 $status = $req->execute(); // Status object
4101 if ( $status->isOK() ) {
4102 $text = $req->getContent();
4103 } elseif ( $req->getStatus() != 200 ) {
4104 // Though we failed to fetch the content, this status is useless.
4105 return wfMessage( 'scarytranscludefailed-httpstatus' )
4106 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
4108 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
4111 $dbw = wfGetDB( DB_MASTER
);
4112 $dbw->replace( 'transcache', array( 'tc_url' ), array(
4114 'tc_time' => $dbw->timestamp( time() ),
4115 'tc_contents' => $text
4121 * Triple brace replacement -- used for template arguments
4124 * @param array $piece
4125 * @param PPFrame $frame
4129 public function argSubstitution( $piece, $frame ) {
4132 $parts = $piece['parts'];
4133 $nameWithSpaces = $frame->expand( $piece['title'] );
4134 $argName = trim( $nameWithSpaces );
4136 $text = $frame->getArgument( $argName );
4137 if ( $text === false && $parts->getLength() > 0
4138 && ( $this->ot
['html']
4140 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
4143 # No match in frame, use the supplied default
4144 $object = $parts->item( 0 )->getChildren();
4146 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
4147 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
4148 $this->limitationWarn( 'post-expand-template-argument' );
4151 if ( $text === false && $object === false ) {
4153 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
4155 if ( $error !== false ) {
4158 if ( $object !== false ) {
4159 $ret = array( 'object' => $object );
4161 $ret = array( 'text' => $text );
4168 * Return the text to be used for a given extension tag.
4169 * This is the ghost of strip().
4171 * @param array $params Associative array of parameters:
4172 * name PPNode for the tag name
4173 * attr PPNode for unparsed text where tag attributes are thought to be
4174 * attributes Optional associative array of parsed attributes
4175 * inner Contents of extension element
4176 * noClose Original text did not have a close tag
4177 * @param PPFrame $frame
4179 * @throws MWException
4182 public function extensionSubstitution( $params, $frame ) {
4183 $name = $frame->expand( $params['name'] );
4184 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
4185 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
4186 $marker = "{$this->mUniqPrefix}-$name-"
4187 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
4189 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
4190 ( $this->ot
['html'] ||
$this->ot
['pre'] );
4191 if ( $isFunctionTag ) {
4192 $markerType = 'none';
4194 $markerType = 'general';
4196 if ( $this->ot
['html'] ||
$isFunctionTag ) {
4197 $name = strtolower( $name );
4198 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
4199 if ( isset( $params['attributes'] ) ) {
4200 $attributes = $attributes +
$params['attributes'];
4203 if ( isset( $this->mTagHooks
[$name] ) ) {
4204 # Workaround for PHP bug 35229 and similar
4205 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
4206 throw new MWException( "Tag hook for $name is not callable\n" );
4208 $output = call_user_func_array( $this->mTagHooks
[$name],
4209 array( $content, $attributes, $this, $frame ) );
4210 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
4211 list( $callback, ) = $this->mFunctionTagHooks
[$name];
4212 if ( !is_callable( $callback ) ) {
4213 throw new MWException( "Tag hook for $name is not callable\n" );
4216 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
4218 $output = '<span class="error">Invalid tag extension name: ' .
4219 htmlspecialchars( $name ) . '</span>';
4222 if ( is_array( $output ) ) {
4223 # Extract flags to local scope (to override $markerType)
4225 $output = $flags[0];
4230 if ( is_null( $attrText ) ) {
4233 if ( isset( $params['attributes'] ) ) {
4234 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4235 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4236 htmlspecialchars( $attrValue ) . '"';
4239 if ( $content === null ) {
4240 $output = "<$name$attrText/>";
4242 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4243 $output = "<$name$attrText>$content$close";
4247 if ( $markerType === 'none' ) {
4249 } elseif ( $markerType === 'nowiki' ) {
4250 $this->mStripState
->addNoWiki( $marker, $output );
4251 } elseif ( $markerType === 'general' ) {
4252 $this->mStripState
->addGeneral( $marker, $output );
4254 throw new MWException( __METHOD__
. ': invalid marker type' );
4260 * Increment an include size counter
4262 * @param string $type The type of expansion
4263 * @param int $size The size of the text
4264 * @return bool False if this inclusion would take it over the maximum, true otherwise
4266 public function incrementIncludeSize( $type, $size ) {
4267 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4270 $this->mIncludeSizes
[$type] +
= $size;
4276 * Increment the expensive function count
4278 * @return bool False if the limit has been exceeded
4280 public function incrementExpensiveFunctionCount() {
4281 $this->mExpensiveFunctionCount++
;
4282 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4286 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4287 * Fills $this->mDoubleUnderscores, returns the modified text
4289 * @param string $text
4293 public function doDoubleUnderscore( $text ) {
4295 # The position of __TOC__ needs to be recorded
4296 $mw = MagicWord
::get( 'toc' );
4297 if ( $mw->match( $text ) ) {
4298 $this->mShowToc
= true;
4299 $this->mForceTocPosition
= true;
4301 # Set a placeholder. At the end we'll fill it in with the TOC.
4302 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4304 # Only keep the first one.
4305 $text = $mw->replace( '', $text );
4308 # Now match and remove the rest of them
4309 $mwa = MagicWord
::getDoubleUnderscoreArray();
4310 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4312 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4313 $this->mOutput
->mNoGallery
= true;
4315 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4316 $this->mShowToc
= false;
4318 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4319 && $this->mTitle
->getNamespace() == NS_CATEGORY
4321 $this->addTrackingCategory( 'hidden-category-category' );
4323 # (bug 8068) Allow control over whether robots index a page.
4325 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4326 # is not desirable, the last one on the page should win.
4327 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4328 $this->mOutput
->setIndexPolicy( 'noindex' );
4329 $this->addTrackingCategory( 'noindex-category' );
4331 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4332 $this->mOutput
->setIndexPolicy( 'index' );
4333 $this->addTrackingCategory( 'index-category' );
4336 # Cache all double underscores in the database
4337 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4338 $this->mOutput
->setProperty( $key, '' );
4345 * @see ParserOutput::addTrackingCategory()
4346 * @param string $msg Message key
4347 * @return bool Whether the addition was successful
4349 public function addTrackingCategory( $msg ) {
4350 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4354 * This function accomplishes several tasks:
4355 * 1) Auto-number headings if that option is enabled
4356 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4357 * 3) Add a Table of contents on the top for users who have enabled the option
4358 * 4) Auto-anchor headings
4360 * It loops through all headlines, collects the necessary data, then splits up the
4361 * string and re-inserts the newly formatted headlines.
4363 * @param string $text
4364 * @param string $origText Original, untouched wikitext
4365 * @param bool $isMain
4366 * @return mixed|string
4369 public function formatHeadings( $text, $origText, $isMain = true ) {
4370 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4372 # Inhibit editsection links if requested in the page
4373 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4374 $maybeShowEditLink = $showEditLink = false;
4376 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4377 $showEditLink = $this->mOptions
->getEditSection();
4379 if ( $showEditLink ) {
4380 $this->mOutput
->setEditSectionTokens( true );
4383 # Get all headlines for numbering them and adding funky stuff like [edit]
4384 # links - this is for later, but we need the number of headlines right now
4386 $numMatches = preg_match_all(
4387 '/<H(?P<level>[1-6])(?P<attrib>.*?>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i',
4392 # if there are fewer than 4 headlines in the article, do not show TOC
4393 # unless it's been explicitly enabled.
4394 $enoughToc = $this->mShowToc
&&
4395 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4397 # Allow user to stipulate that a page should have a "new section"
4398 # link added via __NEWSECTIONLINK__
4399 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4400 $this->mOutput
->setNewSection( true );
4403 # Allow user to remove the "new section"
4404 # link via __NONEWSECTIONLINK__
4405 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4406 $this->mOutput
->hideNewSection( true );
4409 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4410 # override above conditions and always show TOC above first header
4411 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4412 $this->mShowToc
= true;
4420 # Ugh .. the TOC should have neat indentation levels which can be
4421 # passed to the skin functions. These are determined here
4425 $sublevelCount = array();
4426 $levelCount = array();
4431 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4432 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4433 $oldType = $this->mOutputType
;
4434 $this->setOutputType( self
::OT_WIKI
);
4435 $frame = $this->getPreprocessor()->newFrame();
4436 $root = $this->preprocessToDom( $origText );
4437 $node = $root->getFirstChild();
4442 foreach ( $matches[3] as $headline ) {
4443 $isTemplate = false;
4445 $sectionIndex = false;
4447 $markerMatches = array();
4448 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4449 $serial = $markerMatches[1];
4450 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4451 $isTemplate = ( $titleText != $baseTitleText );
4452 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4456 $prevlevel = $level;
4458 $level = $matches[1][$headlineCount];
4460 if ( $level > $prevlevel ) {
4461 # Increase TOC level
4463 $sublevelCount[$toclevel] = 0;
4464 if ( $toclevel < $wgMaxTocLevel ) {
4465 $prevtoclevel = $toclevel;
4466 $toc .= Linker
::tocIndent();
4469 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4470 # Decrease TOC level, find level to jump to
4472 for ( $i = $toclevel; $i > 0; $i-- ) {
4473 if ( $levelCount[$i] == $level ) {
4474 # Found last matching level
4477 } elseif ( $levelCount[$i] < $level ) {
4478 # Found first matching level below current level
4486 if ( $toclevel < $wgMaxTocLevel ) {
4487 if ( $prevtoclevel < $wgMaxTocLevel ) {
4488 # Unindent only if the previous toc level was shown :p
4489 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4490 $prevtoclevel = $toclevel;
4492 $toc .= Linker
::tocLineEnd();
4496 # No change in level, end TOC line
4497 if ( $toclevel < $wgMaxTocLevel ) {
4498 $toc .= Linker
::tocLineEnd();
4502 $levelCount[$toclevel] = $level;
4504 # count number of headlines for each level
4505 $sublevelCount[$toclevel]++
;
4507 for ( $i = 1; $i <= $toclevel; $i++
) {
4508 if ( !empty( $sublevelCount[$i] ) ) {
4512 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4517 # The safe header is a version of the header text safe to use for links
4519 # Remove link placeholders by the link text.
4520 # <!--LINK number-->
4522 # link text with suffix
4523 # Do this before unstrip since link text can contain strip markers
4524 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4526 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4527 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4529 # Strip out HTML (first regex removes any tag not allowed)
4531 # * <sup> and <sub> (bug 8393)
4534 # * <bdi> (bug 72884)
4535 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4537 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4538 # to allow setting directionality in toc items.
4539 $tocline = preg_replace(
4541 '#<(?!/?(span|sup|sub|bdi|i|b)(?: [^>]*)?>).*?>#',
4542 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b))(?: .*?)?>#'
4544 array( '', '<$1>' ),
4547 $tocline = trim( $tocline );
4549 # For the anchor, strip out HTML-y stuff period
4550 $safeHeadline = preg_replace( '/<.*?>/', '', $safeHeadline );
4551 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4553 # Save headline for section edit hint before it's escaped
4554 $headlineHint = $safeHeadline;
4556 if ( $wgExperimentalHtmlIds ) {
4557 # For reverse compatibility, provide an id that's
4558 # HTML4-compatible, like we used to.
4560 # It may be worth noting, academically, that it's possible for
4561 # the legacy anchor to conflict with a non-legacy headline
4562 # anchor on the page. In this case likely the "correct" thing
4563 # would be to either drop the legacy anchors or make sure
4564 # they're numbered first. However, this would require people
4565 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4566 # manually, so let's not bother worrying about it.
4567 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4568 array( 'noninitial', 'legacy' ) );
4569 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4571 if ( $legacyHeadline == $safeHeadline ) {
4572 # No reason to have both (in fact, we can't)
4573 $legacyHeadline = false;
4576 $legacyHeadline = false;
4577 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4581 # HTML names must be case-insensitively unique (bug 10721).
4582 # This does not apply to Unicode characters per
4583 # http://www.w3.org/TR/html5/infrastructure.html#case-sensitivity-and-string-comparison
4584 # @todo FIXME: We may be changing them depending on the current locale.
4585 $arrayKey = strtolower( $safeHeadline );
4586 if ( $legacyHeadline === false ) {
4587 $legacyArrayKey = false;
4589 $legacyArrayKey = strtolower( $legacyHeadline );
4592 # Create the anchor for linking from the TOC to the section
4593 $anchor = $safeHeadline;
4594 $legacyAnchor = $legacyHeadline;
4595 if ( isset( $refers[$arrayKey] ) ) {
4596 for ( $i = 2; isset( $refers["${arrayKey}_$i"] ); ++
$i );
4598 $refers["${arrayKey}_$i"] = true;
4600 $refers[$arrayKey] = true;
4602 if ( $legacyHeadline !== false && isset( $refers[$legacyArrayKey] ) ) {
4603 for ( $i = 2; isset( $refers["${legacyArrayKey}_$i"] ); ++
$i );
4604 $legacyAnchor .= "_$i";
4605 $refers["${legacyArrayKey}_$i"] = true;
4607 $refers[$legacyArrayKey] = true;
4610 # Don't number the heading if it is the only one (looks silly)
4611 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4612 # the two are different if the line contains a link
4613 $headline = Html
::element(
4615 array( 'class' => 'mw-headline-number' ),
4617 ) . ' ' . $headline;
4620 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4621 $toc .= Linker
::tocLine( $anchor, $tocline,
4622 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4625 # Add the section to the section tree
4626 # Find the DOM node for this header
4627 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4628 while ( $node && !$noOffset ) {
4629 if ( $node->getName() === 'h' ) {
4630 $bits = $node->splitHeading();
4631 if ( $bits['i'] == $sectionIndex ) {
4635 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4636 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4637 $node = $node->getNextSibling();
4640 'toclevel' => $toclevel,
4643 'number' => $numbering,
4644 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4645 'fromtitle' => $titleText,
4646 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4647 'anchor' => $anchor,
4650 # give headline the correct <h#> tag
4651 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4652 // Output edit section links as markers with styles that can be customized by skins
4653 if ( $isTemplate ) {
4654 # Put a T flag in the section identifier, to indicate to extractSections()
4655 # that sections inside <includeonly> should be counted.
4656 $editsectionPage = $titleText;
4657 $editsectionSection = "T-$sectionIndex";
4658 $editsectionContent = null;
4660 $editsectionPage = $this->mTitle
->getPrefixedText();
4661 $editsectionSection = $sectionIndex;
4662 $editsectionContent = $headlineHint;
4664 // We use a bit of pesudo-xml for editsection markers. The
4665 // language converter is run later on. Using a UNIQ style marker
4666 // leads to the converter screwing up the tokens when it
4667 // converts stuff. And trying to insert strip tags fails too. At
4668 // this point all real inputted tags have already been escaped,
4669 // so we don't have to worry about a user trying to input one of
4670 // these markers directly. We use a page and section attribute
4671 // to stop the language converter from converting these
4672 // important bits of data, but put the headline hint inside a
4673 // content block because the language converter is supposed to
4674 // be able to convert that piece of data.
4675 // Gets replaced with html in ParserOutput::getText
4676 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4677 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4678 if ( $editsectionContent !== null ) {
4679 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4686 $head[$headlineCount] = Linker
::makeHeadline( $level,
4687 $matches['attrib'][$headlineCount], $anchor, $headline,
4688 $editlink, $legacyAnchor );
4693 $this->setOutputType( $oldType );
4695 # Never ever show TOC if no headers
4696 if ( $numVisible < 1 ) {
4701 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4702 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4704 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4705 $this->mOutput
->setTOCHTML( $toc );
4706 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4707 $this->mOutput
->addModules( 'mediawiki.toc' );
4711 $this->mOutput
->setSections( $tocraw );
4714 # split up and insert constructed headlines
4715 $blocks = preg_split( '/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4718 // build an array of document sections
4719 $sections = array();
4720 foreach ( $blocks as $block ) {
4721 // $head is zero-based, sections aren't.
4722 if ( empty( $head[$i - 1] ) ) {
4723 $sections[$i] = $block;
4725 $sections[$i] = $head[$i - 1] . $block;
4729 * Send a hook, one per section.
4730 * The idea here is to be able to make section-level DIVs, but to do so in a
4731 * lower-impact, more correct way than r50769
4734 * $section : the section number
4735 * &$sectionContent : ref to the content of the section
4736 * $showEditLinks : boolean describing whether this section has an edit link
4738 Hooks
::run( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4743 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4744 // append the TOC at the beginning
4745 // Top anchor now in skin
4746 $sections[0] = $sections[0] . $toc . "\n";
4749 $full .= join( '', $sections );
4751 if ( $this->mForceTocPosition
) {
4752 return str_replace( '<!--MWTOC-->', $toc, $full );
4759 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4760 * conversion, substituting signatures, {{subst:}} templates, etc.
4762 * @param string $text The text to transform
4763 * @param Title $title The Title object for the current article
4764 * @param User $user The User object describing the current user
4765 * @param ParserOptions $options Parsing options
4766 * @param bool $clearState Whether to clear the parser state first
4767 * @return string The altered wiki markup
4769 public function preSaveTransform( $text, Title
$title, User
$user,
4770 ParserOptions
$options, $clearState = true
4772 if ( $clearState ) {
4773 $magicScopeVariable = $this->lock();
4775 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4776 $this->setUser( $user );
4782 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4783 if ( $options->getPreSaveTransform() ) {
4784 $text = $this->pstPass2( $text, $user );
4786 $text = $this->mStripState
->unstripBoth( $text );
4788 $this->setUser( null ); #Reset
4794 * Pre-save transform helper function
4796 * @param string $text
4801 private function pstPass2( $text, $user ) {
4804 # Note: This is the timestamp saved as hardcoded wikitext to
4805 # the database, we use $wgContLang here in order to give
4806 # everyone the same signature and use the default one rather
4807 # than the one selected in each user's preferences.
4808 # (see also bug 12815)
4809 $ts = $this->mOptions
->getTimestamp();
4810 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4811 $ts = $timestamp->format( 'YmdHis' );
4812 $tzMsg = $timestamp->format( 'T' ); # might vary on DST changeover!
4814 # Allow translation of timezones through wiki. format() can return
4815 # whatever crap the system uses, localised or not, so we cannot
4816 # ship premade translations.
4817 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4818 $msg = wfMessage( $key )->inContentLanguage();
4819 if ( $msg->exists() ) {
4820 $tzMsg = $msg->text();
4823 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4825 # Variable replacement
4826 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4827 $text = $this->replaceVariables( $text );
4829 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4830 # which may corrupt this parser instance via its wfMessage()->text() call-
4833 $sigText = $this->getUserSig( $user );
4834 $text = strtr( $text, array(
4836 '~~~~' => "$sigText $d",
4840 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4841 $tc = '[' . Title
::legalChars() . ']';
4842 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4844 // [[ns:page (context)|]]
4845 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4846 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4847 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4848 // [[ns:page (context), context|]] (using either single or double-width comma)
4849 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4850 // [[|page]] (reverse pipe trick: add context from page title)
4851 $p2 = "/\[\[\\|($tc+)]]/";
4853 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4854 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4855 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4856 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4858 $t = $this->mTitle
->getText();
4860 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4861 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4862 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4863 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4865 # if there's no context, don't bother duplicating the title
4866 $text = preg_replace( $p2, '[[\\1]]', $text );
4869 # Trim trailing whitespace
4870 $text = rtrim( $text );
4876 * Fetch the user's signature text, if any, and normalize to
4877 * validated, ready-to-insert wikitext.
4878 * If you have pre-fetched the nickname or the fancySig option, you can
4879 * specify them here to save a database query.
4880 * Do not reuse this parser instance after calling getUserSig(),
4881 * as it may have changed if it's the $wgParser.
4884 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4885 * @param bool|null $fancySig whether the nicknname is the complete signature
4886 * or null to use default value
4889 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4890 global $wgMaxSigChars;
4892 $username = $user->getName();
4894 # If not given, retrieve from the user object.
4895 if ( $nickname === false ) {
4896 $nickname = $user->getOption( 'nickname' );
4899 if ( is_null( $fancySig ) ) {
4900 $fancySig = $user->getBoolOption( 'fancysig' );
4903 $nickname = $nickname == null ?
$username : $nickname;
4905 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4906 $nickname = $username;
4907 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4908 } elseif ( $fancySig !== false ) {
4909 # Sig. might contain markup; validate this
4910 if ( $this->validateSig( $nickname ) !== false ) {
4911 # Validated; clean up (if needed) and return it
4912 return $this->cleanSig( $nickname, true );
4914 # Failed to validate; fall back to the default
4915 $nickname = $username;
4916 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4920 # Make sure nickname doesnt get a sig in a sig
4921 $nickname = self
::cleanSigInSig( $nickname );
4923 # If we're still here, make it a link to the user page
4924 $userText = wfEscapeWikiText( $username );
4925 $nickText = wfEscapeWikiText( $nickname );
4926 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4928 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4929 ->title( $this->getTitle() )->text();
4933 * Check that the user's signature contains no bad XML
4935 * @param string $text
4936 * @return string|bool An expanded string, or false if invalid.
4938 public function validateSig( $text ) {
4939 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4943 * Clean up signature text
4945 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4946 * 2) Substitute all transclusions
4948 * @param string $text
4949 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4950 * @return string Signature text
4952 public function cleanSig( $text, $parsing = false ) {
4955 $magicScopeVariable = $this->lock();
4956 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4959 # Option to disable this feature
4960 if ( !$this->mOptions
->getCleanSignatures() ) {
4964 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4965 # => Move this logic to braceSubstitution()
4966 $substWord = MagicWord
::get( 'subst' );
4967 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4968 $substText = '{{' . $substWord->getSynonym( 0 );
4970 $text = preg_replace( $substRegex, $substText, $text );
4971 $text = self
::cleanSigInSig( $text );
4972 $dom = $this->preprocessToDom( $text );
4973 $frame = $this->getPreprocessor()->newFrame();
4974 $text = $frame->expand( $dom );
4977 $text = $this->mStripState
->unstripBoth( $text );
4984 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4986 * @param string $text
4987 * @return string Signature text with /~{3,5}/ removed
4989 public static function cleanSigInSig( $text ) {
4990 $text = preg_replace( '/~{3,5}/', '', $text );
4995 * Set up some variables which are usually set up in parse()
4996 * so that an external function can call some class members with confidence
4998 * @param Title|null $title
4999 * @param ParserOptions $options
5000 * @param int $outputType
5001 * @param bool $clearState
5003 public function startExternalParse( Title
$title = null, ParserOptions
$options,
5004 $outputType, $clearState = true
5006 $this->startParse( $title, $options, $outputType, $clearState );
5010 * @param Title|null $title
5011 * @param ParserOptions $options
5012 * @param int $outputType
5013 * @param bool $clearState
5015 private function startParse( Title
$title = null, ParserOptions
$options,
5016 $outputType, $clearState = true
5018 $this->setTitle( $title );
5019 $this->mOptions
= $options;
5020 $this->setOutputType( $outputType );
5021 if ( $clearState ) {
5022 $this->clearState();
5027 * Wrapper for preprocess()
5029 * @param string $text The text to preprocess
5030 * @param ParserOptions $options Options
5031 * @param Title|null $title Title object or null to use $wgTitle
5034 public function transformMsg( $text, $options, $title = null ) {
5035 static $executing = false;
5037 # Guard against infinite recursion
5048 $text = $this->preprocess( $text, $title, $options );
5055 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
5056 * The callback should have the following form:
5057 * function myParserHook( $text, $params, $parser, $frame ) { ... }
5059 * Transform and return $text. Use $parser for any required context, e.g. use
5060 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
5062 * Hooks may return extended information by returning an array, of which the
5063 * first numbered element (index 0) must be the return string, and all other
5064 * entries are extracted into local variables within an internal function
5065 * in the Parser class.
5067 * This interface (introduced r61913) appears to be undocumented, but
5068 * 'markerName' is used by some core tag hooks to override which strip
5069 * array their results are placed in. **Use great caution if attempting
5070 * this interface, as it is not documented and injudicious use could smash
5071 * private variables.**
5073 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5074 * @param callable $callback The callback function (and object) to use for the tag
5075 * @throws MWException
5076 * @return callable|null The old value of the mTagHooks array associated with the hook
5078 public function setHook( $tag, $callback ) {
5079 $tag = strtolower( $tag );
5080 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5081 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
5083 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
5084 $this->mTagHooks
[$tag] = $callback;
5085 if ( !in_array( $tag, $this->mStripList
) ) {
5086 $this->mStripList
[] = $tag;
5093 * As setHook(), but letting the contents be parsed.
5095 * Transparent tag hooks are like regular XML-style tag hooks, except they
5096 * operate late in the transformation sequence, on HTML instead of wikitext.
5098 * This is probably obsoleted by things dealing with parser frames?
5099 * The only extension currently using it is geoserver.
5102 * @todo better document or deprecate this
5104 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5105 * @param callable $callback The callback function (and object) to use for the tag
5106 * @throws MWException
5107 * @return callable|null The old value of the mTagHooks array associated with the hook
5109 public function setTransparentTagHook( $tag, $callback ) {
5110 $tag = strtolower( $tag );
5111 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5112 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
5114 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
5115 $this->mTransparentTagHooks
[$tag] = $callback;
5121 * Remove all tag hooks
5123 public function clearTagHooks() {
5124 $this->mTagHooks
= array();
5125 $this->mFunctionTagHooks
= array();
5126 $this->mStripList
= $this->mDefaultStripList
;
5130 * Create a function, e.g. {{sum:1|2|3}}
5131 * The callback function should have the form:
5132 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
5134 * Or with Parser::SFH_OBJECT_ARGS:
5135 * function myParserFunction( $parser, $frame, $args ) { ... }
5137 * The callback may either return the text result of the function, or an array with the text
5138 * in element 0, and a number of flags in the other elements. The names of the flags are
5139 * specified in the keys. Valid flags are:
5140 * found The text returned is valid, stop processing the template. This
5142 * nowiki Wiki markup in the return value should be escaped
5143 * isHTML The returned text is HTML, armour it against wikitext transformation
5145 * @param string $id The magic word ID
5146 * @param callable $callback The callback function (and object) to use
5147 * @param int $flags A combination of the following flags:
5148 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
5150 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
5151 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
5152 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
5153 * the arguments, and to control the way they are expanded.
5155 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
5156 * arguments, for instance:
5157 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
5159 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
5160 * future versions. Please call $frame->expand() on it anyway so that your code keeps
5161 * working if/when this is changed.
5163 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
5166 * Please read the documentation in includes/parser/Preprocessor.php for more information
5167 * about the methods available in PPFrame and PPNode.
5169 * @throws MWException
5170 * @return string|callable The old callback function for this name, if any
5172 public function setFunctionHook( $id, $callback, $flags = 0 ) {
5175 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
5176 $this->mFunctionHooks
[$id] = array( $callback, $flags );
5178 # Add to function cache
5179 $mw = MagicWord
::get( $id );
5181 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
5184 $synonyms = $mw->getSynonyms();
5185 $sensitive = intval( $mw->isCaseSensitive() );
5187 foreach ( $synonyms as $syn ) {
5189 if ( !$sensitive ) {
5190 $syn = $wgContLang->lc( $syn );
5193 if ( !( $flags & self
::SFH_NO_HASH
) ) {
5196 # Remove trailing colon
5197 if ( substr( $syn, -1, 1 ) === ':' ) {
5198 $syn = substr( $syn, 0, -1 );
5200 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
5206 * Get all registered function hook identifiers
5210 public function getFunctionHooks() {
5211 return array_keys( $this->mFunctionHooks
);
5215 * Create a tag function, e.g. "<test>some stuff</test>".
5216 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5217 * Unlike parser functions, their content is not preprocessed.
5218 * @param string $tag
5219 * @param callable $callback
5221 * @throws MWException
5224 public function setFunctionTagHook( $tag, $callback, $flags ) {
5225 $tag = strtolower( $tag );
5226 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5227 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5229 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
5230 $this->mFunctionTagHooks
[$tag] : null;
5231 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
5233 if ( !in_array( $tag, $this->mStripList
) ) {
5234 $this->mStripList
[] = $tag;
5241 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
5242 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5243 * Placeholders created in Skin::makeLinkObj()
5245 * @param string $text
5246 * @param int $options
5248 public function replaceLinkHolders( &$text, $options = 0 ) {
5249 $this->mLinkHolders
->replace( $text );
5253 * Replace "<!--LINK-->" link placeholders with plain text of links
5254 * (not HTML-formatted).
5256 * @param string $text
5259 public function replaceLinkHoldersText( $text ) {
5260 return $this->mLinkHolders
->replaceText( $text );
5264 * Renders an image gallery from a text with one line per image.
5265 * text labels may be given by using |-style alternative text. E.g.
5266 * Image:one.jpg|The number "1"
5267 * Image:tree.jpg|A tree
5268 * given as text will return the HTML of a gallery with two images,
5269 * labeled 'The number "1"' and
5272 * @param string $text
5273 * @param array $params
5274 * @return string HTML
5276 public function renderImageGallery( $text, $params ) {
5279 if ( isset( $params['mode'] ) ) {
5280 $mode = $params['mode'];
5284 $ig = ImageGalleryBase
::factory( $mode );
5285 } catch ( Exception
$e ) {
5286 // If invalid type set, fallback to default.
5287 $ig = ImageGalleryBase
::factory( false );
5290 $ig->setContextTitle( $this->mTitle
);
5291 $ig->setShowBytes( false );
5292 $ig->setShowFilename( false );
5293 $ig->setParser( $this );
5294 $ig->setHideBadImages();
5295 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
5297 if ( isset( $params['showfilename'] ) ) {
5298 $ig->setShowFilename( true );
5300 $ig->setShowFilename( false );
5302 if ( isset( $params['caption'] ) ) {
5303 $caption = $params['caption'];
5304 $caption = htmlspecialchars( $caption );
5305 $caption = $this->replaceInternalLinks( $caption );
5306 $ig->setCaptionHtml( $caption );
5308 if ( isset( $params['perrow'] ) ) {
5309 $ig->setPerRow( $params['perrow'] );
5311 if ( isset( $params['widths'] ) ) {
5312 $ig->setWidths( $params['widths'] );
5314 if ( isset( $params['heights'] ) ) {
5315 $ig->setHeights( $params['heights'] );
5317 $ig->setAdditionalOptions( $params );
5319 Hooks
::run( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5321 $lines = StringUtils
::explode( "\n", $text );
5322 foreach ( $lines as $line ) {
5323 # match lines like these:
5324 # Image:someimage.jpg|This is some image
5326 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5328 if ( count( $matches ) == 0 ) {
5332 if ( strpos( $matches[0], '%' ) !== false ) {
5333 $matches[1] = rawurldecode( $matches[1] );
5335 $title = Title
::newFromText( $matches[1], NS_FILE
);
5336 if ( is_null( $title ) ) {
5337 # Bogus title. Ignore these so we don't bomb out later.
5341 # We need to get what handler the file uses, to figure out parameters.
5342 # Note, a hook can overide the file name, and chose an entirely different
5343 # file (which potentially could be of a different type and have different handler).
5346 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5347 array( $this, $title, &$options, &$descQuery ) );
5348 # Don't register it now, as ImageGallery does that later.
5349 $file = $this->fetchFileNoRegister( $title, $options );
5350 $handler = $file ?
$file->getHandler() : false;
5353 'img_alt' => 'gallery-internal-alt',
5354 'img_link' => 'gallery-internal-link',
5357 $paramMap = $paramMap +
$handler->getParamMap();
5358 // We don't want people to specify per-image widths.
5359 // Additionally the width parameter would need special casing anyhow.
5360 unset( $paramMap['img_width'] );
5363 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5368 $handlerOptions = array();
5369 if ( isset( $matches[3] ) ) {
5370 // look for an |alt= definition while trying not to break existing
5371 // captions with multiple pipes (|) in it, until a more sensible grammar
5372 // is defined for images in galleries
5374 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5375 // splitting on '|' is a bit odd, and different from makeImage.
5376 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5377 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
5379 foreach ( $parameterMatches as $parameterMatch ) {
5380 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5382 $paramName = $paramMap[$magicName];
5384 switch ( $paramName ) {
5385 case 'gallery-internal-alt':
5386 $alt = $this->stripAltText( $match, false );
5388 case 'gallery-internal-link':
5389 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5390 $chars = self
::EXT_LINK_URL_CLASS
;
5391 $prots = $this->mUrlProtocols
;
5392 //check to see if link matches an absolute url, if not then it must be a wiki link.
5393 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5396 $localLinkTitle = Title
::newFromText( $linkValue );
5397 if ( $localLinkTitle !== null ) {
5398 $link = $localLinkTitle->getLinkURL();
5403 // Must be a handler specific parameter.
5404 if ( $handler->validateParam( $paramName, $match ) ) {
5405 $handlerOptions[$paramName] = $match;
5407 // Guess not. Append it to the caption.
5408 wfDebug( "$parameterMatch failed parameter validation\n" );
5409 $label .= '|' . $parameterMatch;
5414 // concatenate all other pipes
5415 $label .= '|' . $parameterMatch;
5418 // remove the first pipe
5419 $label = substr( $label, 1 );
5422 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5424 $html = $ig->toHTML();
5425 Hooks
::run( 'AfterParserFetchFileAndTitle', array( $this, $ig, &$html ) );
5430 * @param string $handler
5433 public function getImageParams( $handler ) {
5435 $handlerClass = get_class( $handler );
5439 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5440 # Initialise static lists
5441 static $internalParamNames = array(
5442 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5443 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5444 'bottom', 'text-bottom' ),
5445 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5446 'upright', 'border', 'link', 'alt', 'class' ),
5448 static $internalParamMap;
5449 if ( !$internalParamMap ) {
5450 $internalParamMap = array();
5451 foreach ( $internalParamNames as $type => $names ) {
5452 foreach ( $names as $name ) {
5453 $magicName = str_replace( '-', '_', "img_$name" );
5454 $internalParamMap[$magicName] = array( $type, $name );
5459 # Add handler params
5460 $paramMap = $internalParamMap;
5462 $handlerParamMap = $handler->getParamMap();
5463 foreach ( $handlerParamMap as $magic => $paramName ) {
5464 $paramMap[$magic] = array( 'handler', $paramName );
5467 $this->mImageParams
[$handlerClass] = $paramMap;
5468 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5470 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5474 * Parse image options text and use it to make an image
5476 * @param Title $title
5477 * @param string $options
5478 * @param LinkHolderArray|bool $holders
5479 * @return string HTML
5481 public function makeImage( $title, $options, $holders = false ) {
5482 # Check if the options text is of the form "options|alt text"
5484 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5485 # * left no resizing, just left align. label is used for alt= only
5486 # * right same, but right aligned
5487 # * none same, but not aligned
5488 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5489 # * center center the image
5490 # * frame Keep original image size, no magnify-button.
5491 # * framed Same as "frame"
5492 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5493 # * upright reduce width for upright images, rounded to full __0 px
5494 # * border draw a 1px border around the image
5495 # * alt Text for HTML alt attribute (defaults to empty)
5496 # * class Set a class for img node
5497 # * link Set the target of the image link. Can be external, interwiki, or local
5498 # vertical-align values (no % or length right now):
5508 $parts = StringUtils
::explode( "|", $options );
5510 # Give extensions a chance to select the file revision for us
5513 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5514 array( $this, $title, &$options, &$descQuery ) );
5515 # Fetch and register the file (file title may be different via hooks)
5516 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5519 $handler = $file ?
$file->getHandler() : false;
5521 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5524 $this->addTrackingCategory( 'broken-file-category' );
5527 # Process the input parameters
5529 $params = array( 'frame' => array(), 'handler' => array(),
5530 'horizAlign' => array(), 'vertAlign' => array() );
5531 $seenformat = false;
5532 foreach ( $parts as $part ) {
5533 $part = trim( $part );
5534 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5536 if ( isset( $paramMap[$magicName] ) ) {
5537 list( $type, $paramName ) = $paramMap[$magicName];
5539 # Special case; width and height come in one variable together
5540 if ( $type === 'handler' && $paramName === 'width' ) {
5541 $parsedWidthParam = $this->parseWidthParam( $value );
5542 if ( isset( $parsedWidthParam['width'] ) ) {
5543 $width = $parsedWidthParam['width'];
5544 if ( $handler->validateParam( 'width', $width ) ) {
5545 $params[$type]['width'] = $width;
5549 if ( isset( $parsedWidthParam['height'] ) ) {
5550 $height = $parsedWidthParam['height'];
5551 if ( $handler->validateParam( 'height', $height ) ) {
5552 $params[$type]['height'] = $height;
5556 # else no validation -- bug 13436
5558 if ( $type === 'handler' ) {
5559 # Validate handler parameter
5560 $validated = $handler->validateParam( $paramName, $value );
5562 # Validate internal parameters
5563 switch ( $paramName ) {
5567 # @todo FIXME: Possibly check validity here for
5568 # manualthumb? downstream behavior seems odd with
5569 # missing manual thumbs.
5571 $value = $this->stripAltText( $value, $holders );
5574 $chars = self
::EXT_LINK_URL_CLASS
;
5575 $prots = $this->mUrlProtocols
;
5576 if ( $value === '' ) {
5577 $paramName = 'no-link';
5580 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5581 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5582 $paramName = 'link-url';
5583 $this->mOutput
->addExternalLink( $value );
5584 if ( $this->mOptions
->getExternalLinkTarget() ) {
5585 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5590 $linkTitle = Title
::newFromText( $value );
5592 $paramName = 'link-title';
5593 $value = $linkTitle;
5594 $this->mOutput
->addLink( $linkTitle );
5602 // use first appearing option, discard others.
5603 $validated = ! $seenformat;
5607 # Most other things appear to be empty or numeric...
5608 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5613 $params[$type][$paramName] = $value;
5617 if ( !$validated ) {
5622 # Process alignment parameters
5623 if ( $params['horizAlign'] ) {
5624 $params['frame']['align'] = key( $params['horizAlign'] );
5626 if ( $params['vertAlign'] ) {
5627 $params['frame']['valign'] = key( $params['vertAlign'] );
5630 $params['frame']['caption'] = $caption;
5632 # Will the image be presented in a frame, with the caption below?
5633 $imageIsFramed = isset( $params['frame']['frame'] )
5634 ||
isset( $params['frame']['framed'] )
5635 ||
isset( $params['frame']['thumbnail'] )
5636 ||
isset( $params['frame']['manualthumb'] );
5638 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5639 # came to also set the caption, ordinary text after the image -- which
5640 # makes no sense, because that just repeats the text multiple times in
5641 # screen readers. It *also* came to set the title attribute.
5643 # Now that we have an alt attribute, we should not set the alt text to
5644 # equal the caption: that's worse than useless, it just repeats the
5645 # text. This is the framed/thumbnail case. If there's no caption, we
5646 # use the unnamed parameter for alt text as well, just for the time be-
5647 # ing, if the unnamed param is set and the alt param is not.
5649 # For the future, we need to figure out if we want to tweak this more,
5650 # e.g., introducing a title= parameter for the title; ignoring the un-
5651 # named parameter entirely for images without a caption; adding an ex-
5652 # plicit caption= parameter and preserving the old magic unnamed para-
5654 if ( $imageIsFramed ) { # Framed image
5655 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5656 # No caption or alt text, add the filename as the alt text so
5657 # that screen readers at least get some description of the image
5658 $params['frame']['alt'] = $title->getText();
5660 # Do not set $params['frame']['title'] because tooltips don't make sense
5662 } else { # Inline image
5663 if ( !isset( $params['frame']['alt'] ) ) {
5664 # No alt text, use the "caption" for the alt text
5665 if ( $caption !== '' ) {
5666 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5668 # No caption, fall back to using the filename for the
5670 $params['frame']['alt'] = $title->getText();
5673 # Use the "caption" for the tooltip text
5674 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5677 Hooks
::run( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5679 # Linker does the rest
5680 $time = isset( $options['time'] ) ?
$options['time'] : false;
5681 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5682 $time, $descQuery, $this->mOptions
->getThumbSize() );
5684 # Give the handler a chance to modify the parser object
5686 $handler->parserTransformHook( $this, $file );
5693 * @param string $caption
5694 * @param LinkHolderArray|bool $holders
5695 * @return mixed|string
5697 protected function stripAltText( $caption, $holders ) {
5698 # Strip bad stuff out of the title (tooltip). We can't just use
5699 # replaceLinkHoldersText() here, because if this function is called
5700 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5702 $tooltip = $holders->replaceText( $caption );
5704 $tooltip = $this->replaceLinkHoldersText( $caption );
5707 # make sure there are no placeholders in thumbnail attributes
5708 # that are later expanded to html- so expand them now and
5710 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5711 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5717 * Set a flag in the output object indicating that the content is dynamic and
5718 * shouldn't be cached.
5720 public function disableCache() {
5721 wfDebug( "Parser output marked as uncacheable.\n" );
5722 if ( !$this->mOutput
) {
5723 throw new MWException( __METHOD__
.
5724 " can only be called when actually parsing something" );
5726 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5727 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5731 * Callback from the Sanitizer for expanding items found in HTML attribute
5732 * values, so they can be safely tested and escaped.
5734 * @param string $text
5735 * @param bool|PPFrame $frame
5738 public function attributeStripCallback( &$text, $frame = false ) {
5739 $text = $this->replaceVariables( $text, $frame );
5740 $text = $this->mStripState
->unstripBoth( $text );
5749 public function getTags() {
5751 array_keys( $this->mTransparentTagHooks
),
5752 array_keys( $this->mTagHooks
),
5753 array_keys( $this->mFunctionTagHooks
)
5758 * Replace transparent tags in $text with the values given by the callbacks.
5760 * Transparent tag hooks are like regular XML-style tag hooks, except they
5761 * operate late in the transformation sequence, on HTML instead of wikitext.
5763 * @param string $text
5767 public function replaceTransparentTags( $text ) {
5769 $elements = array_keys( $this->mTransparentTagHooks
);
5770 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5771 $replacements = array();
5773 foreach ( $matches as $marker => $data ) {
5774 list( $element, $content, $params, $tag ) = $data;
5775 $tagName = strtolower( $element );
5776 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5777 $output = call_user_func_array(
5778 $this->mTransparentTagHooks
[$tagName],
5779 array( $content, $params, $this )
5784 $replacements[$marker] = $output;
5786 return strtr( $text, $replacements );
5790 * Break wikitext input into sections, and either pull or replace
5791 * some particular section's text.
5793 * External callers should use the getSection and replaceSection methods.
5795 * @param string $text Page wikitext
5796 * @param string|number $sectionId A section identifier string of the form:
5797 * "<flag1> - <flag2> - ... - <section number>"
5799 * Currently the only recognised flag is "T", which means the target section number
5800 * was derived during a template inclusion parse, in other words this is a template
5801 * section edit link. If no flags are given, it was an ordinary section edit link.
5802 * This flag is required to avoid a section numbering mismatch when a section is
5803 * enclosed by "<includeonly>" (bug 6563).
5805 * The section number 0 pulls the text before the first heading; other numbers will
5806 * pull the given section along with its lower-level subsections. If the section is
5807 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5809 * Section 0 is always considered to exist, even if it only contains the empty
5810 * string. If $text is the empty string and section 0 is replaced, $newText is
5813 * @param string $mode One of "get" or "replace"
5814 * @param string $newText Replacement text for section data.
5815 * @return string For "get", the extracted section text.
5816 * for "replace", the whole page with the section replaced.
5818 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5819 global $wgTitle; # not generally used but removes an ugly failure mode
5821 $magicScopeVariable = $this->lock();
5822 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5824 $frame = $this->getPreprocessor()->newFrame();
5826 # Process section extraction flags
5828 $sectionParts = explode( '-', $sectionId );
5829 $sectionIndex = array_pop( $sectionParts );
5830 foreach ( $sectionParts as $part ) {
5831 if ( $part === 'T' ) {
5832 $flags |
= self
::PTD_FOR_INCLUSION
;
5836 # Check for empty input
5837 if ( strval( $text ) === '' ) {
5838 # Only sections 0 and T-0 exist in an empty document
5839 if ( $sectionIndex == 0 ) {
5840 if ( $mode === 'get' ) {
5846 if ( $mode === 'get' ) {
5854 # Preprocess the text
5855 $root = $this->preprocessToDom( $text, $flags );
5857 # <h> nodes indicate section breaks
5858 # They can only occur at the top level, so we can find them by iterating the root's children
5859 $node = $root->getFirstChild();
5861 # Find the target section
5862 if ( $sectionIndex == 0 ) {
5863 # Section zero doesn't nest, level=big
5864 $targetLevel = 1000;
5867 if ( $node->getName() === 'h' ) {
5868 $bits = $node->splitHeading();
5869 if ( $bits['i'] == $sectionIndex ) {
5870 $targetLevel = $bits['level'];
5874 if ( $mode === 'replace' ) {
5875 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5877 $node = $node->getNextSibling();
5883 if ( $mode === 'get' ) {
5890 # Find the end of the section, including nested sections
5892 if ( $node->getName() === 'h' ) {
5893 $bits = $node->splitHeading();
5894 $curLevel = $bits['level'];
5895 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5899 if ( $mode === 'get' ) {
5900 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5902 $node = $node->getNextSibling();
5905 # Write out the remainder (in replace mode only)
5906 if ( $mode === 'replace' ) {
5907 # Output the replacement text
5908 # Add two newlines on -- trailing whitespace in $newText is conventionally
5909 # stripped by the editor, so we need both newlines to restore the paragraph gap
5910 # Only add trailing whitespace if there is newText
5911 if ( $newText != "" ) {
5912 $outText .= $newText . "\n\n";
5916 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5917 $node = $node->getNextSibling();
5921 if ( is_string( $outText ) ) {
5922 # Re-insert stripped tags
5923 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5930 * This function returns the text of a section, specified by a number ($section).
5931 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5932 * the first section before any such heading (section 0).
5934 * If a section contains subsections, these are also returned.
5936 * @param string $text Text to look in
5937 * @param string|number $sectionId Section identifier as a number or string
5938 * (e.g. 0, 1 or 'T-1').
5939 * @param string $defaultText Default to return if section is not found
5941 * @return string Text of the requested section
5943 public function getSection( $text, $sectionId, $defaultText = '' ) {
5944 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5948 * This function returns $oldtext after the content of the section
5949 * specified by $section has been replaced with $text. If the target
5950 * section does not exist, $oldtext is returned unchanged.
5952 * @param string $oldText Former text of the article
5953 * @param string|number $sectionId Section identifier as a number or string
5954 * (e.g. 0, 1 or 'T-1').
5955 * @param string $newText Replacing text
5957 * @return string Modified text
5959 public function replaceSection( $oldText, $sectionId, $newText ) {
5960 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5964 * Get the ID of the revision we are parsing
5968 public function getRevisionId() {
5969 return $this->mRevisionId
;
5973 * Get the revision object for $this->mRevisionId
5975 * @return Revision|null Either a Revision object or null
5976 * @since 1.23 (public since 1.23)
5978 public function getRevisionObject() {
5979 if ( !is_null( $this->mRevisionObject
) ) {
5980 return $this->mRevisionObject
;
5982 if ( is_null( $this->mRevisionId
) ) {
5986 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5987 return $this->mRevisionObject
;
5991 * Get the timestamp associated with the current revision, adjusted for
5992 * the default server-local timestamp
5995 public function getRevisionTimestamp() {
5996 if ( is_null( $this->mRevisionTimestamp
) ) {
6000 $revObject = $this->getRevisionObject();
6001 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
6003 # The cryptic '' timezone parameter tells to use the site-default
6004 # timezone offset instead of the user settings.
6006 # Since this value will be saved into the parser cache, served
6007 # to other users, and potentially even used inside links and such,
6008 # it needs to be consistent for all visitors.
6009 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
6012 return $this->mRevisionTimestamp
;
6016 * Get the name of the user that edited the last revision
6018 * @return string User name
6020 public function getRevisionUser() {
6021 if ( is_null( $this->mRevisionUser
) ) {
6022 $revObject = $this->getRevisionObject();
6024 # if this template is subst: the revision id will be blank,
6025 # so just use the current user's name
6027 $this->mRevisionUser
= $revObject->getUserText();
6028 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6029 $this->mRevisionUser
= $this->getUser()->getName();
6032 return $this->mRevisionUser
;
6036 * Get the size of the revision
6038 * @return int|null Revision size
6040 public function getRevisionSize() {
6041 if ( is_null( $this->mRevisionSize
) ) {
6042 $revObject = $this->getRevisionObject();
6044 # if this variable is subst: the revision id will be blank,
6045 # so just use the parser input size, because the own substituation
6046 # will change the size.
6048 $this->mRevisionSize
= $revObject->getSize();
6049 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6050 $this->mRevisionSize
= $this->mInputSize
;
6053 return $this->mRevisionSize
;
6057 * Mutator for $mDefaultSort
6059 * @param string $sort New value
6061 public function setDefaultSort( $sort ) {
6062 $this->mDefaultSort
= $sort;
6063 $this->mOutput
->setProperty( 'defaultsort', $sort );
6067 * Accessor for $mDefaultSort
6068 * Will use the empty string if none is set.
6070 * This value is treated as a prefix, so the
6071 * empty string is equivalent to sorting by
6076 public function getDefaultSort() {
6077 if ( $this->mDefaultSort
!== false ) {
6078 return $this->mDefaultSort
;
6085 * Accessor for $mDefaultSort
6086 * Unlike getDefaultSort(), will return false if none is set
6088 * @return string|bool
6090 public function getCustomDefaultSort() {
6091 return $this->mDefaultSort
;
6095 * Try to guess the section anchor name based on a wikitext fragment
6096 * presumably extracted from a heading, for example "Header" from
6099 * @param string $text
6103 public function guessSectionNameFromWikiText( $text ) {
6104 # Strip out wikitext links(they break the anchor)
6105 $text = $this->stripSectionName( $text );
6106 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6107 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
6111 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6112 * instead. For use in redirects, since IE6 interprets Redirect: headers
6113 * as something other than UTF-8 (apparently?), resulting in breakage.
6115 * @param string $text The section name
6116 * @return string An anchor
6118 public function guessLegacySectionNameFromWikiText( $text ) {
6119 # Strip out wikitext links(they break the anchor)
6120 $text = $this->stripSectionName( $text );
6121 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6122 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
6126 * Strips a text string of wikitext for use in a section anchor
6128 * Accepts a text string and then removes all wikitext from the
6129 * string and leaves only the resultant text (i.e. the result of
6130 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6131 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6132 * to create valid section anchors by mimicing the output of the
6133 * parser when headings are parsed.
6135 * @param string $text Text string to be stripped of wikitext
6136 * for use in a Section anchor
6137 * @return string Filtered text string
6139 public function stripSectionName( $text ) {
6140 # Strip internal link markup
6141 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6142 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6144 # Strip external link markup
6145 # @todo FIXME: Not tolerant to blank link text
6146 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6147 # on how many empty links there are on the page - need to figure that out.
6148 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6150 # Parse wikitext quotes (italics & bold)
6151 $text = $this->doQuotes( $text );
6154 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
6159 * strip/replaceVariables/unstrip for preprocessor regression testing
6161 * @param string $text
6162 * @param Title $title
6163 * @param ParserOptions $options
6164 * @param int $outputType
6168 public function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
6169 $magicScopeVariable = $this->lock();
6170 $this->startParse( $title, $options, $outputType, true );
6172 $text = $this->replaceVariables( $text );
6173 $text = $this->mStripState
->unstripBoth( $text );
6174 $text = Sanitizer
::removeHTMLtags( $text );
6179 * @param string $text
6180 * @param Title $title
6181 * @param ParserOptions $options
6184 public function testPst( $text, Title
$title, ParserOptions
$options ) {
6185 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6189 * @param string $text
6190 * @param Title $title
6191 * @param ParserOptions $options
6194 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
6195 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
6199 * Call a callback function on all regions of the given text that are not
6200 * inside strip markers, and replace those regions with the return value
6201 * of the callback. For example, with input:
6205 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6206 * two strings will be replaced with the value returned by the callback in
6210 * @param callable $callback
6214 public function markerSkipCallback( $s, $callback ) {
6217 while ( $i < strlen( $s ) ) {
6218 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
6219 if ( $markerStart === false ) {
6220 $out .= call_user_func( $callback, substr( $s, $i ) );
6223 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6224 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6225 if ( $markerEnd === false ) {
6226 $out .= substr( $s, $markerStart );
6229 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6230 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6239 * Remove any strip markers found in the given text.
6241 * @param string $text Input string
6244 public function killMarkers( $text ) {
6245 return $this->mStripState
->killMarkers( $text );
6249 * Save the parser state required to convert the given half-parsed text to
6250 * HTML. "Half-parsed" in this context means the output of
6251 * recursiveTagParse() or internalParse(). This output has strip markers
6252 * from replaceVariables (extensionSubstitution() etc.), and link
6253 * placeholders from replaceLinkHolders().
6255 * Returns an array which can be serialized and stored persistently. This
6256 * array can later be loaded into another parser instance with
6257 * unserializeHalfParsedText(). The text can then be safely incorporated into
6258 * the return value of a parser hook.
6260 * @param string $text
6264 public function serializeHalfParsedText( $text ) {
6267 'version' => self
::HALF_PARSED_VERSION
,
6268 'stripState' => $this->mStripState
->getSubState( $text ),
6269 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6275 * Load the parser state given in the $data array, which is assumed to
6276 * have been generated by serializeHalfParsedText(). The text contents is
6277 * extracted from the array, and its markers are transformed into markers
6278 * appropriate for the current Parser instance. This transformed text is
6279 * returned, and can be safely included in the return value of a parser
6282 * If the $data array has been stored persistently, the caller should first
6283 * check whether it is still valid, by calling isValidHalfParsedText().
6285 * @param array $data Serialized data
6286 * @throws MWException
6289 public function unserializeHalfParsedText( $data ) {
6290 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6291 throw new MWException( __METHOD__
. ': invalid version' );
6294 # First, extract the strip state.
6295 $texts = array( $data['text'] );
6296 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6298 # Now renumber links
6299 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6301 # Should be good to go.
6306 * Returns true if the given array, presumed to be generated by
6307 * serializeHalfParsedText(), is compatible with the current version of the
6310 * @param array $data
6314 public function isValidHalfParsedText( $data ) {
6315 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6319 * Parsed a width param of imagelink like 300px or 200x300px
6321 * @param string $value
6326 public function parseWidthParam( $value ) {
6327 $parsedWidthParam = array();
6328 if ( $value === '' ) {
6329 return $parsedWidthParam;
6332 # (bug 13500) In both cases (width/height and width only),
6333 # permit trailing "px" for backward compatibility.
6334 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6335 $width = intval( $m[1] );
6336 $height = intval( $m[2] );
6337 $parsedWidthParam['width'] = $width;
6338 $parsedWidthParam['height'] = $height;
6339 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6340 $width = intval( $value );
6341 $parsedWidthParam['width'] = $width;
6343 return $parsedWidthParam;
6347 * Lock the current instance of the parser.
6349 * This is meant to stop someone from calling the parser
6350 * recursively and messing up all the strip state.
6352 * @throws MWException If parser is in a parse
6353 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6355 protected function lock() {
6356 if ( $this->mInParse
) {
6357 throw new MWException( "Parser state cleared while parsing. "
6358 . "Did you call Parser::parse recursively?" );
6360 $this->mInParse
= true;
6363 $recursiveCheck = new ScopedCallback( function() use ( $that ) {
6364 $that->mInParse
= false;
6367 return $recursiveCheck;
6371 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6373 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6374 * or if there is more than one <p/> tag in the input HTML.
6376 * @param string $html
6380 public static function stripOuterParagraph( $html ) {
6382 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6383 if ( strpos( $m[1], '</p>' ) === false ) {
6392 * Return this parser if it is not doing anything, otherwise
6393 * get a fresh parser. You can use this method by doing
6394 * $myParser = $wgParser->getFreshParser(), or more simply
6395 * $wgParser->getFreshParser()->parse( ... );
6396 * if you're unsure if $wgParser is safe to use.
6399 * @return Parser A parser object that is not parsing anything
6401 public function getFreshParser() {
6402 global $wgParserConf;
6403 if ( $this->mInParse
) {
6404 return new $wgParserConf['class']( $wgParserConf );