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, $mExtLinkBracketedRegex, $mUrlProtocols;
152 # Initialized in getPreprocessor()
153 /** @var Preprocessor */
154 public $mPreprocessor;
156 # Cleared with clearState():
161 public $mAutonumber, $mDTopen;
168 public $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
170 * @var LinkHolderArray
172 public $mLinkHolders;
175 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
176 public $mDefaultSort;
177 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
178 public $mExpensiveFunctionCount; # number of expensive parser function calls
179 public $mShowToc, $mForceTocPosition;
184 public $mUser; # User object; only used when doing pre-save transform
187 # These are variables reset at least once per parse regardless of $clearState
197 public $mTitle; # Title context, used for self-link rendering and similar things
198 public $mOutputType; # Output type, one of the OT_xxx constants
199 public $ot; # Shortcut alias, see setOutputType()
200 public $mRevisionObject; # The revision object of the specified revision ID
201 public $mRevisionId; # ID to display in {{REVISIONID}} tags
202 public $mRevisionTimestamp; # The timestamp of the specified revision ID
203 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag
204 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
205 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp
206 public $mInputSize = false; # For {{PAGESIZE}} on current page.
214 * @var array Array with the language name of each language link (i.e. the
215 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
216 * duplicate language links to the ParserOutput.
218 public $mLangLinkLanguages;
221 * @var MapCacheLRU|null
224 * A cache of the current revisions of titles. Keys are $title->getPrefixedDbKey()
226 public $currentRevisionCache;
229 * @var bool Recursive call protection.
230 * This variable should be treated as if it were private.
232 public $mInParse = false;
234 /** @var SectionProfiler */
235 protected $mProfiler;
240 public function __construct( $conf = array() ) {
241 $this->mConf
= $conf;
242 $this->mUrlProtocols
= wfUrlProtocols();
243 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
244 self
::EXT_LINK_URL_CLASS
. '+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
245 if ( isset( $conf['preprocessorClass'] ) ) {
246 $this->mPreprocessorClass
= $conf['preprocessorClass'];
247 } elseif ( defined( 'HPHP_VERSION' ) ) {
248 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
249 $this->mPreprocessorClass
= 'Preprocessor_Hash';
250 } elseif ( extension_loaded( 'domxml' ) ) {
251 # PECL extension that conflicts with the core DOM extension (bug 13770)
252 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
253 $this->mPreprocessorClass
= 'Preprocessor_Hash';
254 } elseif ( extension_loaded( 'dom' ) ) {
255 $this->mPreprocessorClass
= 'Preprocessor_DOM';
257 $this->mPreprocessorClass
= 'Preprocessor_Hash';
259 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
263 * Reduce memory usage to reduce the impact of circular references
265 public function __destruct() {
266 if ( isset( $this->mLinkHolders
) ) {
267 unset( $this->mLinkHolders
);
269 foreach ( $this as $name => $value ) {
270 unset( $this->$name );
275 * Allow extensions to clean up when the parser is cloned
277 public function __clone() {
278 $this->mInParse
= false;
280 // Bug 56226: When you create a reference "to" an object field, that
281 // makes the object field itself be a reference too (until the other
282 // reference goes out of scope). When cloning, any field that's a
283 // reference is copied as a reference in the new object. Both of these
284 // are defined PHP5 behaviors, as inconvenient as it is for us when old
285 // hooks from PHP4 days are passing fields by reference.
286 foreach ( array( 'mStripState', 'mVarCache' ) as $k ) {
287 // Make a non-reference copy of the field, then rebind the field to
288 // reference the new copy.
294 Hooks
::run( 'ParserCloned', array( $this ) );
298 * Do various kinds of initialisation on the first call of the parser
300 public function firstCallInit() {
301 if ( !$this->mFirstCall
) {
304 $this->mFirstCall
= false;
306 CoreParserFunctions
::register( $this );
307 CoreTagHooks
::register( $this );
308 $this->initialiseVariables();
310 Hooks
::run( 'ParserFirstCallInit', array( &$this ) );
318 public function clearState() {
319 if ( $this->mFirstCall
) {
320 $this->firstCallInit();
322 $this->mOutput
= new ParserOutput
;
323 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
324 $this->mAutonumber
= 0;
325 $this->mLastSection
= '';
326 $this->mDTopen
= false;
327 $this->mIncludeCount
= array();
328 $this->mArgStack
= false;
329 $this->mInPre
= false;
330 $this->mLinkHolders
= new LinkHolderArray( $this );
332 $this->mRevisionObject
= $this->mRevisionTimestamp
=
333 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
334 $this->mVarCache
= array();
336 $this->mLangLinkLanguages
= array();
337 $this->currentRevisionCache
= null;
340 * Prefix for temporary replacement strings for the multipass parser.
341 * \x07 should never appear in input as it's disallowed in XML.
342 * Using it at the front also gives us a little extra robustness
343 * since it shouldn't match when butted up against identifier-like
346 * Must not consist of all title characters, or else it will change
347 * the behavior of <nowiki> in a link.
349 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
350 $this->mStripState
= new StripState( $this->mUniqPrefix
);
352 # Clear these on every parse, bug 4549
353 $this->mTplRedirCache
= $this->mTplDomCache
= array();
355 $this->mShowToc
= true;
356 $this->mForceTocPosition
= false;
357 $this->mIncludeSizes
= array(
361 $this->mPPNodeCount
= 0;
362 $this->mGeneratedPPNodeCount
= 0;
363 $this->mHighestExpansionDepth
= 0;
364 $this->mDefaultSort
= false;
365 $this->mHeadings
= array();
366 $this->mDoubleUnderscores
= array();
367 $this->mExpensiveFunctionCount
= 0;
370 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
371 $this->mPreprocessor
= null;
374 $this->mProfiler
= new SectionProfiler();
376 Hooks
::run( 'ParserClearState', array( &$this ) );
380 * Convert wikitext to HTML
381 * Do not call this function recursively.
383 * @param string $text Text we want to parse
384 * @param Title $title
385 * @param ParserOptions $options
386 * @param bool $linestart
387 * @param bool $clearState
388 * @param int $revid Number to pass in {{REVISIONID}}
389 * @return ParserOutput A ParserOutput
391 public function parse( $text, Title
$title, ParserOptions
$options,
392 $linestart = true, $clearState = true, $revid = null
395 * First pass--just handle <nowiki> sections, pass the rest off
396 * to internalParse() which does all the real work.
399 global $wgShowHostnames;
402 $magicScopeVariable = $this->lock();
405 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
407 $this->currentRevisionCache
= null;
408 $this->mInputSize
= strlen( $text );
409 if ( $this->mOptions
->getEnableLimitReport() ) {
410 $this->mOutput
->resetParseStartTime();
413 # Remove the strip marker tag prefix from the input, if present.
415 $text = str_replace( $this->mUniqPrefix
, '', $text );
418 $oldRevisionId = $this->mRevisionId
;
419 $oldRevisionObject = $this->mRevisionObject
;
420 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
421 $oldRevisionUser = $this->mRevisionUser
;
422 $oldRevisionSize = $this->mRevisionSize
;
423 if ( $revid !== null ) {
424 $this->mRevisionId
= $revid;
425 $this->mRevisionObject
= null;
426 $this->mRevisionTimestamp
= null;
427 $this->mRevisionUser
= null;
428 $this->mRevisionSize
= null;
431 Hooks
::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
433 Hooks
::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
434 $text = $this->internalParse( $text );
435 Hooks
::run( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
437 $text = $this->internalParseHalfParsed( $text, true, $linestart );
440 * A converted title will be provided in the output object if title and
441 * content conversion are enabled, the article text does not contain
442 * a conversion-suppressing double-underscore tag, and no
443 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
444 * automatic link conversion.
446 if ( !( $options->getDisableTitleConversion()
447 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
448 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
449 ||
$this->mOutput
->getDisplayTitle() !== false )
451 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
452 if ( $convruletitle ) {
453 $this->mOutput
->setTitleText( $convruletitle );
455 $titleText = $this->getConverterLanguage()->convertTitle( $title );
456 $this->mOutput
->setTitleText( $titleText );
460 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
461 $this->limitationWarn( 'expensive-parserfunction',
462 $this->mExpensiveFunctionCount
,
463 $this->mOptions
->getExpensiveParserFunctionLimit()
467 # Information on include size limits, for the benefit of users who try to skirt them
468 if ( $this->mOptions
->getEnableLimitReport() ) {
469 $max = $this->mOptions
->getMaxIncludeSize();
471 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
472 if ( $cpuTime !== null ) {
473 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
474 sprintf( "%.3f", $cpuTime )
478 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
479 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
480 sprintf( "%.3f", $wallTime )
483 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
484 array( $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() )
486 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
487 array( $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() )
489 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
490 array( $this->mIncludeSizes
['post-expand'], $max )
492 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
493 array( $this->mIncludeSizes
['arg'], $max )
495 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
496 array( $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() )
498 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
499 array( $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() )
501 Hooks
::run( 'ParserLimitReportPrepare', array( $this, $this->mOutput
) );
503 $limitReport = "NewPP limit report\n";
504 if ( $wgShowHostnames ) {
505 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
507 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
508 if ( Hooks
::run( 'ParserLimitReportFormat',
509 array( $key, &$value, &$limitReport, false, false )
511 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
512 $valueMsg = wfMessage( array( "$key-value-text", "$key-value" ) )
513 ->inLanguage( 'en' )->useDatabase( false );
514 if ( !$valueMsg->exists() ) {
515 $valueMsg = new RawMessage( '$1' );
517 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
518 $valueMsg->params( $value );
519 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
523 // Since we're not really outputting HTML, decode the entities and
524 // then re-encode the things that need hiding inside HTML comments.
525 $limitReport = htmlspecialchars_decode( $limitReport );
526 Hooks
::run( 'ParserLimitReport', array( $this, &$limitReport ) );
528 // Sanitize for comment. Note '‐' in the replacement is U+2010,
529 // which looks much like the problematic '-'.
530 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&' ), $limitReport );
531 $text .= "\n<!-- \n$limitReport-->\n";
533 // Add on template profiling data
534 $dataByFunc = $this->mProfiler
->getFunctionStats();
535 uasort( $dataByFunc, function ( $a, $b ) {
536 return $a['real'] < $b['real']; // descending order
538 $profileReport = "Transclusion expansion time report (%,ms,calls,template)\n";
539 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
540 $profileReport .= sprintf( "%6.2f%% %8.3f %6d - %s\n",
541 $item['%real'], $item['real'], $item['calls'],
542 htmlspecialchars( $item['name'] ) );
544 $text .= "\n<!-- \n$profileReport-->\n";
546 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
547 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
548 $this->mTitle
->getPrefixedDBkey() );
551 $this->mOutput
->setText( $text );
553 $this->mRevisionId
= $oldRevisionId;
554 $this->mRevisionObject
= $oldRevisionObject;
555 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
556 $this->mRevisionUser
= $oldRevisionUser;
557 $this->mRevisionSize
= $oldRevisionSize;
558 $this->mInputSize
= false;
559 $this->currentRevisionCache
= null;
561 return $this->mOutput
;
565 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
566 * can be called from an extension tag hook.
568 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
569 * instead, which means that lists and links have not been fully parsed yet,
570 * and strip markers are still present.
572 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
574 * Use this function if you're a parser tag hook and you want to parse
575 * wikitext before or after applying additional transformations, and you
576 * intend to *return the result as hook output*, which will cause it to go
577 * through the rest of parsing process automatically.
579 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
580 * $text are not expanded
582 * @param string $text Text extension wants to have parsed
583 * @param bool|PPFrame $frame The frame to use for expanding any template variables
584 * @return string UNSAFE half-parsed HTML
586 public function recursiveTagParse( $text, $frame = false ) {
587 Hooks
::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
588 Hooks
::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
589 $text = $this->internalParse( $text, false, $frame );
594 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
595 * point can be called from an extension tag hook.
597 * The output of this function is fully-parsed HTML that is safe for output.
598 * If you're a parser tag hook, you might want to use recursiveTagParse()
601 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
602 * $text are not expanded
606 * @param string $text Text extension wants to have parsed
607 * @param bool|PPFrame $frame The frame to use for expanding any template variables
608 * @return string Fully parsed HTML
610 public function recursiveTagParseFully( $text, $frame = false ) {
611 $text = $this->recursiveTagParse( $text, $frame );
612 $text = $this->internalParseHalfParsed( $text, false );
617 * Expand templates and variables in the text, producing valid, static wikitext.
618 * Also removes comments.
619 * Do not call this function recursively.
620 * @param string $text
621 * @param Title $title
622 * @param ParserOptions $options
623 * @param int|null $revid
624 * @param bool|PPFrame $frame
625 * @return mixed|string
627 public function preprocess( $text, Title
$title = null,
628 ParserOptions
$options, $revid = null, $frame = false
630 $magicScopeVariable = $this->lock();
631 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
632 if ( $revid !== null ) {
633 $this->mRevisionId
= $revid;
635 Hooks
::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
636 Hooks
::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
637 $text = $this->replaceVariables( $text, $frame );
638 $text = $this->mStripState
->unstripBoth( $text );
643 * Recursive parser entry point that can be called from an extension tag
646 * @param string $text Text to be expanded
647 * @param bool|PPFrame $frame The frame to use for expanding any template variables
651 public function recursivePreprocess( $text, $frame = false ) {
652 $text = $this->replaceVariables( $text, $frame );
653 $text = $this->mStripState
->unstripBoth( $text );
658 * Process the wikitext for the "?preload=" feature. (bug 5210)
660 * "<noinclude>", "<includeonly>" etc. are parsed as for template
661 * transclusion, comments, templates, arguments, tags hooks and parser
662 * functions are untouched.
664 * @param string $text
665 * @param Title $title
666 * @param ParserOptions $options
667 * @param array $params
670 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = array() ) {
671 $msg = new RawMessage( $text );
672 $text = $msg->params( $params )->plain();
674 # Parser (re)initialisation
675 $magicScopeVariable = $this->lock();
676 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
678 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
679 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
680 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
681 $text = $this->mStripState
->unstripBoth( $text );
686 * Get a random string
690 public static function getRandomString() {
691 return wfRandomString( 16 );
695 * Set the current user.
696 * Should only be used when doing pre-save transform.
698 * @param User|null $user User object or null (to reset)
700 public function setUser( $user ) {
701 $this->mUser
= $user;
705 * Accessor for mUniqPrefix.
709 public function uniqPrefix() {
710 if ( !isset( $this->mUniqPrefix
) ) {
711 # @todo FIXME: This is probably *horribly wrong*
712 # LanguageConverter seems to want $wgParser's uniqPrefix, however
713 # if this is called for a parser cache hit, the parser may not
714 # have ever been initialized in the first place.
715 # Not really sure what the heck is supposed to be going on here.
717 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
719 return $this->mUniqPrefix
;
723 * Set the context title
727 public function setTitle( $t ) {
729 $t = Title
::newFromText( 'NO TITLE' );
732 if ( $t->hasFragment() ) {
733 # Strip the fragment to avoid various odd effects
734 $this->mTitle
= clone $t;
735 $this->mTitle
->setFragment( '' );
742 * Accessor for the Title object
746 public function getTitle() {
747 return $this->mTitle
;
751 * Accessor/mutator for the Title object
753 * @param Title $x Title object or null to just get the current one
756 public function Title( $x = null ) {
757 return wfSetVar( $this->mTitle
, $x );
761 * Set the output type
763 * @param int $ot New value
765 public function setOutputType( $ot ) {
766 $this->mOutputType
= $ot;
769 'html' => $ot == self
::OT_HTML
,
770 'wiki' => $ot == self
::OT_WIKI
,
771 'pre' => $ot == self
::OT_PREPROCESS
,
772 'plain' => $ot == self
::OT_PLAIN
,
777 * Accessor/mutator for the output type
779 * @param int|null $x New value or null to just get the current one
782 public function OutputType( $x = null ) {
783 return wfSetVar( $this->mOutputType
, $x );
787 * Get the ParserOutput object
789 * @return ParserOutput
791 public function getOutput() {
792 return $this->mOutput
;
796 * Get the ParserOptions object
798 * @return ParserOptions
800 public function getOptions() {
801 return $this->mOptions
;
805 * Accessor/mutator for the ParserOptions object
807 * @param ParserOptions $x New value or null to just get the current one
808 * @return ParserOptions Current ParserOptions object
810 public function Options( $x = null ) {
811 return wfSetVar( $this->mOptions
, $x );
817 public function nextLinkID() {
818 return $this->mLinkID++
;
824 public function setLinkID( $id ) {
825 $this->mLinkID
= $id;
829 * Get a language object for use in parser functions such as {{FORMATNUM:}}
832 public function getFunctionLang() {
833 return $this->getTargetLanguage();
837 * Get the target language for the content being parsed. This is usually the
838 * language that the content is in.
842 * @throws MWException
845 public function getTargetLanguage() {
846 $target = $this->mOptions
->getTargetLanguage();
848 if ( $target !== null ) {
850 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
851 return $this->mOptions
->getUserLangObj();
852 } elseif ( is_null( $this->mTitle
) ) {
853 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
856 return $this->mTitle
->getPageLanguage();
860 * Get the language object for language conversion
861 * @return Language|null
863 public function getConverterLanguage() {
864 return $this->getTargetLanguage();
868 * Get a User object either from $this->mUser, if set, or from the
869 * ParserOptions object otherwise
873 public function getUser() {
874 if ( !is_null( $this->mUser
) ) {
877 return $this->mOptions
->getUser();
881 * Get a preprocessor object
883 * @return Preprocessor
885 public function getPreprocessor() {
886 if ( !isset( $this->mPreprocessor
) ) {
887 $class = $this->mPreprocessorClass
;
888 $this->mPreprocessor
= new $class( $this );
890 return $this->mPreprocessor
;
894 * Replaces all occurrences of HTML-style comments and the given tags
895 * in the text with a random marker and returns the next text. The output
896 * parameter $matches will be an associative array filled with data in
900 * 'UNIQ-xxxxx' => array(
903 * array( 'param' => 'x' ),
904 * '<element param="x">tag content</element>' ) )
907 * @param array $elements List of element names. Comments are always extracted.
908 * @param string $text Source text string.
909 * @param array $matches Out parameter, Array: extracted tags
910 * @param string $uniq_prefix
911 * @return string Stripped text
913 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
918 $taglist = implode( '|', $elements );
919 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
921 while ( $text != '' ) {
922 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
924 if ( count( $p ) < 5 ) {
927 if ( count( $p ) > 5 ) {
941 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
942 $stripped .= $marker;
944 if ( $close === '/>' ) {
945 # Empty element tag, <tag />
950 if ( $element === '!--' ) {
953 $end = "/(<\\/$element\\s*>)/i";
955 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
957 if ( count( $q ) < 3 ) {
958 # No end tag -- let it run out to the end of the text.
967 $matches[$marker] = array( $element,
969 Sanitizer
::decodeTagAttributes( $attributes ),
970 "<$element$attributes$close$content$tail" );
976 * Get a list of strippable XML-like elements
980 public function getStripList() {
981 return $this->mStripList
;
985 * Add an item to the strip state
986 * Returns the unique tag which must be inserted into the stripped text
987 * The tag will be replaced with the original text in unstrip()
989 * @param string $text
993 public function insertStripItem( $text ) {
994 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
995 $this->mMarkerIndex++
;
996 $this->mStripState
->addGeneral( $rnd, $text );
1001 * parse the wiki syntax used to render tables
1004 * @param string $text
1007 public function doTableStuff( $text ) {
1009 $lines = StringUtils
::explode( "\n", $text );
1011 $td_history = array(); # Is currently a td tag open?
1012 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
1013 $tr_history = array(); # Is currently a tr tag open?
1014 $tr_attributes = array(); # history of tr attributes
1015 $has_opened_tr = array(); # Did this table open a <tr> element?
1016 $indent_level = 0; # indent level of the table
1018 foreach ( $lines as $outLine ) {
1019 $line = trim( $outLine );
1021 if ( $line === '' ) { # empty line, go to next line
1022 $out .= $outLine . "\n";
1026 $first_character = $line[0];
1029 if ( preg_match( '/^(:*)\{\|(.*)$/', $line, $matches ) ) {
1030 # First check if we are starting a new table
1031 $indent_level = strlen( $matches[1] );
1033 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1034 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1036 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1037 array_push( $td_history, false );
1038 array_push( $last_tag_history, '' );
1039 array_push( $tr_history, false );
1040 array_push( $tr_attributes, '' );
1041 array_push( $has_opened_tr, false );
1042 } elseif ( count( $td_history ) == 0 ) {
1043 # Don't do any of the following
1044 $out .= $outLine . "\n";
1046 } elseif ( substr( $line, 0, 2 ) === '|}' ) {
1047 # We are ending a table
1048 $line = '</table>' . substr( $line, 2 );
1049 $last_tag = array_pop( $last_tag_history );
1051 if ( !array_pop( $has_opened_tr ) ) {
1052 $line = "<tr><td></td></tr>{$line}";
1055 if ( array_pop( $tr_history ) ) {
1056 $line = "</tr>{$line}";
1059 if ( array_pop( $td_history ) ) {
1060 $line = "</{$last_tag}>{$line}";
1062 array_pop( $tr_attributes );
1063 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
1064 } elseif ( substr( $line, 0, 2 ) === '|-' ) {
1065 # Now we have a table row
1066 $line = preg_replace( '#^\|-+#', '', $line );
1068 # Whats after the tag is now only attributes
1069 $attributes = $this->mStripState
->unstripBoth( $line );
1070 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1071 array_pop( $tr_attributes );
1072 array_push( $tr_attributes, $attributes );
1075 $last_tag = array_pop( $last_tag_history );
1076 array_pop( $has_opened_tr );
1077 array_push( $has_opened_tr, true );
1079 if ( array_pop( $tr_history ) ) {
1083 if ( array_pop( $td_history ) ) {
1084 $line = "</{$last_tag}>{$line}";
1088 array_push( $tr_history, false );
1089 array_push( $td_history, false );
1090 array_push( $last_tag_history, '' );
1091 } elseif ( $first_character === '|'
1092 ||
$first_character === '!'
1093 ||
substr( $line, 0, 2 ) === '|+'
1095 # This might be cell elements, td, th or captions
1096 if ( substr( $line, 0, 2 ) === '|+' ) {
1097 $first_character = '+';
1098 $line = substr( $line, 1 );
1101 $line = substr( $line, 1 );
1103 if ( $first_character === '!' ) {
1104 $line = str_replace( '!!', '||', $line );
1107 # Split up multiple cells on the same line.
1108 # FIXME : This can result in improper nesting of tags processed
1109 # by earlier parser steps, but should avoid splitting up eg
1110 # attribute values containing literal "||".
1111 $cells = StringUtils
::explodeMarkup( '||', $line );
1115 # Loop through each table cell
1116 foreach ( $cells as $cell ) {
1118 if ( $first_character !== '+' ) {
1119 $tr_after = array_pop( $tr_attributes );
1120 if ( !array_pop( $tr_history ) ) {
1121 $previous = "<tr{$tr_after}>\n";
1123 array_push( $tr_history, true );
1124 array_push( $tr_attributes, '' );
1125 array_pop( $has_opened_tr );
1126 array_push( $has_opened_tr, true );
1129 $last_tag = array_pop( $last_tag_history );
1131 if ( array_pop( $td_history ) ) {
1132 $previous = "</{$last_tag}>\n{$previous}";
1135 if ( $first_character === '|' ) {
1137 } elseif ( $first_character === '!' ) {
1139 } elseif ( $first_character === '+' ) {
1140 $last_tag = 'caption';
1145 array_push( $last_tag_history, $last_tag );
1147 # A cell could contain both parameters and data
1148 $cell_data = explode( '|', $cell, 2 );
1150 # Bug 553: Note that a '|' inside an invalid link should not
1151 # be mistaken as delimiting cell parameters
1152 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1153 $cell = "{$previous}<{$last_tag}>{$cell}";
1154 } elseif ( count( $cell_data ) == 1 ) {
1155 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1157 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1158 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1159 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1163 array_push( $td_history, true );
1166 $out .= $outLine . "\n";
1169 # Closing open td, tr && table
1170 while ( count( $td_history ) > 0 ) {
1171 if ( array_pop( $td_history ) ) {
1174 if ( array_pop( $tr_history ) ) {
1177 if ( !array_pop( $has_opened_tr ) ) {
1178 $out .= "<tr><td></td></tr>\n";
1181 $out .= "</table>\n";
1184 # Remove trailing line-ending (b/c)
1185 if ( substr( $out, -1 ) === "\n" ) {
1186 $out = substr( $out, 0, -1 );
1189 # special case: don't return empty table
1190 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1198 * Helper function for parse() that transforms wiki markup into half-parsed
1199 * HTML. Only called for $mOutputType == self::OT_HTML.
1203 * @param string $text
1204 * @param bool $isMain
1205 * @param PPFrame|bool $frame
1209 public function internalParse( $text, $isMain = true, $frame = false ) {
1213 # Hook to suspend the parser in this state
1214 if ( !Hooks
::run( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1218 # if $frame is provided, then use $frame for replacing any variables
1220 # use frame depth to infer how include/noinclude tags should be handled
1221 # depth=0 means this is the top-level document; otherwise it's an included document
1222 if ( !$frame->depth
) {
1225 $flag = Parser
::PTD_FOR_INCLUSION
;
1227 $dom = $this->preprocessToDom( $text, $flag );
1228 $text = $frame->expand( $dom );
1230 # if $frame is not provided, then use old-style replaceVariables
1231 $text = $this->replaceVariables( $text );
1234 Hooks
::run( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1235 $text = Sanitizer
::removeHTMLtags(
1237 array( &$this, 'attributeStripCallback' ),
1239 array_keys( $this->mTransparentTagHooks
)
1241 Hooks
::run( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1243 # Tables need to come after variable replacement for things to work
1244 # properly; putting them before other transformations should keep
1245 # exciting things like link expansions from showing up in surprising
1247 $text = $this->doTableStuff( $text );
1249 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1251 $text = $this->doDoubleUnderscore( $text );
1253 $text = $this->doHeadings( $text );
1254 $text = $this->replaceInternalLinks( $text );
1255 $text = $this->doAllQuotes( $text );
1256 $text = $this->replaceExternalLinks( $text );
1258 # replaceInternalLinks may sometimes leave behind
1259 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1260 $text = str_replace( $this->mUniqPrefix
. 'NOPARSE', '', $text );
1262 $text = $this->doMagicLinks( $text );
1263 $text = $this->formatHeadings( $text, $origText, $isMain );
1269 * Helper function for parse() that transforms half-parsed HTML into fully
1272 * @param string $text
1273 * @param bool $isMain
1274 * @param bool $linestart
1277 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1278 global $wgUseTidy, $wgAlwaysUseTidy;
1280 $text = $this->mStripState
->unstripGeneral( $text );
1282 # Clean up special characters, only run once, next-to-last before doBlockLevels
1284 # french spaces, last one Guillemet-left
1285 # only if there is something before the space
1286 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
1287 # french spaces, Guillemet-right
1288 '/(\\302\\253) /' => '\\1 ',
1289 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
1291 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
1293 $text = $this->doBlockLevels( $text, $linestart );
1295 $this->replaceLinkHolders( $text );
1298 * The input doesn't get language converted if
1300 * b) Content isn't converted
1301 * c) It's a conversion table
1302 * d) it is an interface message (which is in the user language)
1304 if ( !( $this->mOptions
->getDisableContentConversion()
1305 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
1307 if ( !$this->mOptions
->getInterfaceMessage() ) {
1308 # The position of the convert() call should not be changed. it
1309 # assumes that the links are all replaced and the only thing left
1310 # is the <nowiki> mark.
1311 $text = $this->getConverterLanguage()->convert( $text );
1315 $text = $this->mStripState
->unstripNoWiki( $text );
1318 Hooks
::run( 'ParserBeforeTidy', array( &$this, &$text ) );
1321 $text = $this->replaceTransparentTags( $text );
1322 $text = $this->mStripState
->unstripGeneral( $text );
1324 $text = Sanitizer
::normalizeCharReferences( $text );
1326 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
1327 $text = MWTidy
::tidy( $text );
1329 # attempt to sanitize at least some nesting problems
1330 # (bug #2702 and quite a few others)
1332 # ''Something [http://www.cool.com cool''] -->
1333 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1334 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1335 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1336 # fix up an anchor inside another anchor, only
1337 # at least for a single single nested link (bug 3695)
1338 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1339 '\\1\\2</a>\\3</a>\\1\\4</a>',
1340 # fix div inside inline elements- doBlockLevels won't wrap a line which
1341 # contains a div, so fix it up here; replace
1342 # div with escaped text
1343 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1344 '\\1\\3<div\\5>\\6</div>\\8\\9',
1345 # remove empty italic or bold tag pairs, some
1346 # introduced by rules above
1347 '/<([bi])><\/\\1>/' => '',
1350 $text = preg_replace(
1351 array_keys( $tidyregs ),
1352 array_values( $tidyregs ),
1357 Hooks
::run( 'ParserAfterTidy', array( &$this, &$text ) );
1364 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1365 * magic external links.
1370 * @param string $text
1374 public function doMagicLinks( $text ) {
1375 $prots = wfUrlProtocolsWithoutProtRel();
1376 $urlChar = self
::EXT_LINK_URL_CLASS
;
1377 $space = self
::SPACE_NOT_NL
; # non-newline space
1378 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1379 $spaces = "$space++"; # possessive match of 1 or more spaces
1380 $text = preg_replace_callback(
1382 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1383 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1384 (\b(?i:$prots)$urlChar+) | # m[3]: Free external links
1385 \b(?:RFC|PMID) $spaces # m[4]: RFC or PMID, capture number
1387 \bISBN $spaces ( # m[5]: ISBN, capture number
1388 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1389 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1390 [0-9Xx] # check digit
1392 )!xu", array( &$this, 'magicLinkCallback' ), $text );
1397 * @throws MWException
1399 * @return HTML|string
1401 public function magicLinkCallback( $m ) {
1402 if ( isset( $m[1] ) && $m[1] !== '' ) {
1405 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1408 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1409 # Free external link
1410 return $this->makeFreeExternalLink( $m[0] );
1411 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1413 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1416 $cssClass = 'mw-magiclink-rfc';
1418 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1420 $urlmsg = 'pubmedurl';
1421 $cssClass = 'mw-magiclink-pmid';
1424 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1425 substr( $m[0], 0, 20 ) . '"' );
1427 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1428 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass );
1429 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1432 $space = self
::SPACE_NOT_NL
; # non-newline space
1433 $isbn = preg_replace( "/$space/", ' ', $isbn );
1434 $num = strtr( $isbn, array(
1439 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1440 return '<a href="' .
1441 htmlspecialchars( $titleObj->getLocalURL() ) .
1442 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1449 * Make a free external link, given a user-supplied URL
1451 * @param string $url
1453 * @return string HTML
1456 public function makeFreeExternalLink( $url ) {
1460 # The characters '<' and '>' (which were escaped by
1461 # removeHTMLtags()) should not be included in
1462 # URLs, per RFC 2396.
1464 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1465 $trail = substr( $url, $m2[0][1] ) . $trail;
1466 $url = substr( $url, 0, $m2[0][1] );
1469 # Move trailing punctuation to $trail
1471 # If there is no left bracket, then consider right brackets fair game too
1472 if ( strpos( $url, '(' ) === false ) {
1476 $urlRev = strrev( $url );
1477 $numSepChars = strspn( $urlRev, $sep );
1478 # Don't break a trailing HTML entity by moving the ; into $trail
1479 # This is in hot code, so use substr_compare to avoid having to
1480 # create a new string object for the comparison
1481 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0) {
1482 # more optimization: instead of running preg_match with a $
1483 # anchor, which can be slow, do the match on the reversed
1484 # string starting at the desired offset.
1485 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1486 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1490 if ( $numSepChars ) {
1491 $trail = substr( $url, -$numSepChars ) . $trail;
1492 $url = substr( $url, 0, -$numSepChars );
1495 $url = Sanitizer
::cleanUrl( $url );
1497 # Is this an external image?
1498 $text = $this->maybeMakeExternalImage( $url );
1499 if ( $text === false ) {
1500 # Not an image, make a link
1501 $text = Linker
::makeExternalLink( $url,
1502 $this->getConverterLanguage()->markNoConversion( $url, true ),
1504 $this->getExternalLinkAttribs( $url ) );
1505 # Register it in the output object...
1506 # Replace unnecessary URL escape codes with their equivalent characters
1507 $pasteurized = self
::normalizeLinkUrl( $url );
1508 $this->mOutput
->addExternalLink( $pasteurized );
1510 return $text . $trail;
1514 * Parse headers and return html
1518 * @param string $text
1522 public function doHeadings( $text ) {
1523 for ( $i = 6; $i >= 1; --$i ) {
1524 $h = str_repeat( '=', $i );
1525 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1531 * Replace single quotes with HTML markup
1534 * @param string $text
1536 * @return string The altered text
1538 public function doAllQuotes( $text ) {
1540 $lines = StringUtils
::explode( "\n", $text );
1541 foreach ( $lines as $line ) {
1542 $outtext .= $this->doQuotes( $line ) . "\n";
1544 $outtext = substr( $outtext, 0, -1 );
1549 * Helper function for doAllQuotes()
1551 * @param string $text
1555 public function doQuotes( $text ) {
1556 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1557 $countarr = count( $arr );
1558 if ( $countarr == 1 ) {
1562 // First, do some preliminary work. This may shift some apostrophes from
1563 // being mark-up to being text. It also counts the number of occurrences
1564 // of bold and italics mark-ups.
1567 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1568 $thislen = strlen( $arr[$i] );
1569 // If there are ever four apostrophes, assume the first is supposed to
1570 // be text, and the remaining three constitute mark-up for bold text.
1571 // (bug 13227: ''''foo'''' turns into ' ''' foo ' ''')
1572 if ( $thislen == 4 ) {
1573 $arr[$i - 1] .= "'";
1576 } elseif ( $thislen > 5 ) {
1577 // If there are more than 5 apostrophes in a row, assume they're all
1578 // text except for the last 5.
1579 // (bug 13227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1580 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1584 // Count the number of occurrences of bold and italics mark-ups.
1585 if ( $thislen == 2 ) {
1587 } elseif ( $thislen == 3 ) {
1589 } elseif ( $thislen == 5 ) {
1595 // If there is an odd number of both bold and italics, it is likely
1596 // that one of the bold ones was meant to be an apostrophe followed
1597 // by italics. Which one we cannot know for certain, but it is more
1598 // likely to be one that has a single-letter word before it.
1599 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1600 $firstsingleletterword = -1;
1601 $firstmultiletterword = -1;
1603 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1604 if ( strlen( $arr[$i] ) == 3 ) {
1605 $x1 = substr( $arr[$i - 1], -1 );
1606 $x2 = substr( $arr[$i - 1], -2, 1 );
1607 if ( $x1 === ' ' ) {
1608 if ( $firstspace == -1 ) {
1611 } elseif ( $x2 === ' ' ) {
1612 if ( $firstsingleletterword == -1 ) {
1613 $firstsingleletterword = $i;
1614 // if $firstsingleletterword is set, we don't
1615 // look at the other options, so we can bail early.
1619 if ( $firstmultiletterword == -1 ) {
1620 $firstmultiletterword = $i;
1626 // If there is a single-letter word, use it!
1627 if ( $firstsingleletterword > -1 ) {
1628 $arr[$firstsingleletterword] = "''";
1629 $arr[$firstsingleletterword - 1] .= "'";
1630 } elseif ( $firstmultiletterword > -1 ) {
1631 // If not, but there's a multi-letter word, use that one.
1632 $arr[$firstmultiletterword] = "''";
1633 $arr[$firstmultiletterword - 1] .= "'";
1634 } elseif ( $firstspace > -1 ) {
1635 // ... otherwise use the first one that has neither.
1636 // (notice that it is possible for all three to be -1 if, for example,
1637 // there is only one pentuple-apostrophe in the line)
1638 $arr[$firstspace] = "''";
1639 $arr[$firstspace - 1] .= "'";
1643 // Now let's actually convert our apostrophic mush to HTML!
1648 foreach ( $arr as $r ) {
1649 if ( ( $i %
2 ) == 0 ) {
1650 if ( $state === 'both' ) {
1656 $thislen = strlen( $r );
1657 if ( $thislen == 2 ) {
1658 if ( $state === 'i' ) {
1661 } elseif ( $state === 'bi' ) {
1664 } elseif ( $state === 'ib' ) {
1665 $output .= '</b></i><b>';
1667 } elseif ( $state === 'both' ) {
1668 $output .= '<b><i>' . $buffer . '</i>';
1670 } else { // $state can be 'b' or ''
1674 } elseif ( $thislen == 3 ) {
1675 if ( $state === 'b' ) {
1678 } elseif ( $state === 'bi' ) {
1679 $output .= '</i></b><i>';
1681 } elseif ( $state === 'ib' ) {
1684 } elseif ( $state === 'both' ) {
1685 $output .= '<i><b>' . $buffer . '</b>';
1687 } else { // $state can be 'i' or ''
1691 } elseif ( $thislen == 5 ) {
1692 if ( $state === 'b' ) {
1693 $output .= '</b><i>';
1695 } elseif ( $state === 'i' ) {
1696 $output .= '</i><b>';
1698 } elseif ( $state === 'bi' ) {
1699 $output .= '</i></b>';
1701 } elseif ( $state === 'ib' ) {
1702 $output .= '</b></i>';
1704 } elseif ( $state === 'both' ) {
1705 $output .= '<i><b>' . $buffer . '</b></i>';
1707 } else { // ($state == '')
1715 // Now close all remaining tags. Notice that the order is important.
1716 if ( $state === 'b' ||
$state === 'ib' ) {
1719 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1722 if ( $state === 'bi' ) {
1725 // There might be lonely ''''', so make sure we have a buffer
1726 if ( $state === 'both' && $buffer ) {
1727 $output .= '<b><i>' . $buffer . '</i></b>';
1733 * Replace external links (REL)
1735 * Note: this is all very hackish and the order of execution matters a lot.
1736 * Make sure to run tests/parserTests.php if you change this code.
1740 * @param string $text
1742 * @throws MWException
1745 public function replaceExternalLinks( $text ) {
1747 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1748 if ( $bits === false ) {
1749 throw new MWException( "PCRE needs to be compiled with "
1750 . "--enable-unicode-properties in order for MediaWiki to function" );
1752 $s = array_shift( $bits );
1755 while ( $i < count( $bits ) ) {
1758 $text = $bits[$i++
];
1759 $trail = $bits[$i++
];
1761 # The characters '<' and '>' (which were escaped by
1762 # removeHTMLtags()) should not be included in
1763 # URLs, per RFC 2396.
1765 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1766 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1767 $url = substr( $url, 0, $m2[0][1] );
1770 # If the link text is an image URL, replace it with an <img> tag
1771 # This happened by accident in the original parser, but some people used it extensively
1772 $img = $this->maybeMakeExternalImage( $text );
1773 if ( $img !== false ) {
1779 # Set linktype for CSS - if URL==text, link is essentially free
1780 $linktype = ( $text === $url ) ?
'free' : 'text';
1782 # No link text, e.g. [http://domain.tld/some.link]
1783 if ( $text == '' ) {
1785 $langObj = $this->getTargetLanguage();
1786 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1787 $linktype = 'autonumber';
1789 # Have link text, e.g. [http://domain.tld/some.link text]s
1791 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1794 $text = $this->getConverterLanguage()->markNoConversion( $text );
1796 $url = Sanitizer
::cleanUrl( $url );
1798 # Use the encoded URL
1799 # This means that users can paste URLs directly into the text
1800 # Funny characters like ö aren't valid in URLs anyway
1801 # This was changed in August 2004
1802 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1803 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1805 # Register link in the output object.
1806 # Replace unnecessary URL escape codes with the referenced character
1807 # This prevents spammers from hiding links from the filters
1808 $pasteurized = self
::normalizeLinkUrl( $url );
1809 $this->mOutput
->addExternalLink( $pasteurized );
1816 * Get the rel attribute for a particular external link.
1819 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1820 * nofollow if appropriate
1821 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1822 * @return string|null Rel attribute for $url
1824 public static function getExternalLinkRel( $url = false, $title = null ) {
1825 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1826 $ns = $title ?
$title->getNamespace() : false;
1827 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1828 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1836 * Get an associative array of additional HTML attributes appropriate for a
1837 * particular external link. This currently may include rel => nofollow
1838 * (depending on configuration, namespace, and the URL's domain) and/or a
1839 * target attribute (depending on configuration).
1841 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1842 * nofollow if appropriate
1843 * @return array Associative array of HTML attributes
1845 public function getExternalLinkAttribs( $url = false ) {
1847 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1849 if ( $this->mOptions
->getExternalLinkTarget() ) {
1850 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1856 * Replace unusual escape codes in a URL with their equivalent characters
1858 * @deprecated since 1.24, use normalizeLinkUrl
1859 * @param string $url
1862 public static function replaceUnusualEscapes( $url ) {
1863 wfDeprecated( __METHOD__
, '1.24' );
1864 return self
::normalizeLinkUrl( $url );
1868 * Replace unusual escape codes in a URL with their equivalent characters
1870 * This generally follows the syntax defined in RFC 3986, with special
1871 * consideration for HTTP query strings.
1873 * @param string $url
1876 public static function normalizeLinkUrl( $url ) {
1877 # First, make sure unsafe characters are encoded
1878 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
1880 return rawurlencode( $m[0] );
1886 $end = strlen( $url );
1888 # Fragment part - 'fragment'
1889 $start = strpos( $url, '#' );
1890 if ( $start !== false && $start < $end ) {
1891 $ret = self
::normalizeUrlComponent(
1892 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
1896 # Query part - 'query' minus &=+;
1897 $start = strpos( $url, '?' );
1898 if ( $start !== false && $start < $end ) {
1899 $ret = self
::normalizeUrlComponent(
1900 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
1904 # Scheme and path part - 'pchar'
1905 # (we assume no userinfo or encoded colons in the host)
1906 $ret = self
::normalizeUrlComponent(
1907 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
1912 private static function normalizeUrlComponent( $component, $unsafe ) {
1913 $callback = function ( $matches ) use ( $unsafe ) {
1914 $char = urldecode( $matches[0] );
1915 $ord = ord( $char );
1916 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
1920 # Leave it escaped, but use uppercase for a-f
1921 return strtoupper( $matches[0] );
1924 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
1928 * make an image if it's allowed, either through the global
1929 * option, through the exception, or through the on-wiki whitelist
1931 * @param string $url
1935 private function maybeMakeExternalImage( $url ) {
1936 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1937 $imagesexception = !empty( $imagesfrom );
1939 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1940 if ( $imagesexception && is_array( $imagesfrom ) ) {
1941 $imagematch = false;
1942 foreach ( $imagesfrom as $match ) {
1943 if ( strpos( $url, $match ) === 0 ) {
1948 } elseif ( $imagesexception ) {
1949 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1951 $imagematch = false;
1954 if ( $this->mOptions
->getAllowExternalImages()
1955 ||
( $imagesexception && $imagematch )
1957 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1959 $text = Linker
::makeExternalImage( $url );
1962 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1963 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
1965 $whitelist = explode(
1967 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
1970 foreach ( $whitelist as $entry ) {
1971 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1972 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1975 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1976 # Image matches a whitelist entry
1977 $text = Linker
::makeExternalImage( $url );
1986 * Process [[ ]] wikilinks
1990 * @return string Processed text
1994 public function replaceInternalLinks( $s ) {
1995 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
2000 * Process [[ ]] wikilinks (RIL)
2002 * @throws MWException
2003 * @return LinkHolderArray
2007 public function replaceInternalLinks2( &$s ) {
2008 global $wgExtraInterlanguageLinkPrefixes;
2010 static $tc = false, $e1, $e1_img;
2011 # the % is needed to support urlencoded titles as well
2013 $tc = Title
::legalChars() . '#%';
2014 # Match a link having the form [[namespace:link|alternate]]trail
2015 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2016 # Match cases where there is no "]]", which might still be images
2017 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2020 $holders = new LinkHolderArray( $this );
2022 # split the entire text string on occurrences of [[
2023 $a = StringUtils
::explode( '[[', ' ' . $s );
2024 # get the first element (all text up to first [[), and remove the space we added
2027 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2028 $s = substr( $s, 1 );
2030 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2032 if ( $useLinkPrefixExtension ) {
2033 # Match the end of a line for a word that's not followed by whitespace,
2034 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2036 $charset = $wgContLang->linkPrefixCharset();
2037 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2040 if ( is_null( $this->mTitle
) ) {
2041 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
2043 $nottalk = !$this->mTitle
->isTalkPage();
2045 if ( $useLinkPrefixExtension ) {
2047 if ( preg_match( $e2, $s, $m ) ) {
2048 $first_prefix = $m[2];
2050 $first_prefix = false;
2056 $useSubpages = $this->areSubpagesAllowed();
2058 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
2059 # Loop for each link
2060 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2061 // @codingStandardsIgnoreStart
2063 # Check for excessive memory usage
2064 if ( $holders->isBig() ) {
2066 # Do the existence check, replace the link holders and clear the array
2067 $holders->replace( $s );
2071 if ( $useLinkPrefixExtension ) {
2072 if ( preg_match( $e2, $s, $m ) ) {
2079 if ( $first_prefix ) {
2080 $prefix = $first_prefix;
2081 $first_prefix = false;
2085 $might_be_img = false;
2087 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2089 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2090 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2091 # the real problem is with the $e1 regex
2094 # Still some problems for cases where the ] is meant to be outside punctuation,
2095 # and no image is in sight. See bug 2095.
2098 && substr( $m[3], 0, 1 ) === ']'
2099 && strpos( $text, '[' ) !== false
2101 $text .= ']'; # so that replaceExternalLinks($text) works later
2102 $m[3] = substr( $m[3], 1 );
2104 # fix up urlencoded title texts
2105 if ( strpos( $m[1], '%' ) !== false ) {
2106 # Should anchors '#' also be rejected?
2107 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) );
2110 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2111 # Invalid, but might be an image with a link in its caption
2112 $might_be_img = true;
2114 if ( strpos( $m[1], '%' ) !== false ) {
2115 $m[1] = rawurldecode( $m[1] );
2118 } else { # Invalid form; output directly
2119 $s .= $prefix . '[[' . $line;
2125 # Don't allow internal links to pages containing
2126 # PROTO: where PROTO is a valid URL protocol; these
2127 # should be external links.
2128 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2129 $s .= $prefix . '[[' . $line;
2133 # Make subpage if necessary
2134 if ( $useSubpages ) {
2135 $link = $this->maybeDoSubpageLink( $origLink, $text );
2140 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2142 # Strip off leading ':'
2143 $link = substr( $link, 1 );
2146 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
2147 if ( $nt === null ) {
2148 $s .= $prefix . '[[' . $line;
2152 $ns = $nt->getNamespace();
2153 $iw = $nt->getInterwiki();
2155 if ( $might_be_img ) { # if this is actually an invalid link
2156 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2159 # look at the next 'line' to see if we can close it there
2161 $next_line = $a->current();
2162 if ( $next_line === false ||
$next_line === null ) {
2165 $m = explode( ']]', $next_line, 3 );
2166 if ( count( $m ) == 3 ) {
2167 # the first ]] closes the inner link, the second the image
2169 $text .= "[[{$m[0]}]]{$m[1]}";
2172 } elseif ( count( $m ) == 2 ) {
2173 # if there's exactly one ]] that's fine, we'll keep looking
2174 $text .= "[[{$m[0]}]]{$m[1]}";
2176 # if $next_line is invalid too, we need look no further
2177 $text .= '[[' . $next_line;
2182 # we couldn't find the end of this imageLink, so output it raw
2183 # but don't ignore what might be perfectly normal links in the text we've examined
2184 $holders->merge( $this->replaceInternalLinks2( $text ) );
2185 $s .= "{$prefix}[[$link|$text";
2186 # note: no $trail, because without an end, there *is* no trail
2189 } else { # it's not an image, so output it raw
2190 $s .= "{$prefix}[[$link|$text";
2191 # note: no $trail, because without an end, there *is* no trail
2196 $wasblank = ( $text == '' );
2200 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
2201 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2202 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2203 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2204 $text = $this->doQuotes( $text );
2207 # Link not escaped by : , create the various objects
2208 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2211 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2212 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2213 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2216 # Bug 24502: filter duplicates
2217 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2218 $this->mLangLinkLanguages
[$iw] = true;
2219 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2222 $s = rtrim( $s . $prefix );
2223 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2227 if ( $ns == NS_FILE
) {
2228 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2230 # if no parameters were passed, $text
2231 # becomes something like "File:Foo.png",
2232 # which we don't want to pass on to the
2236 # recursively parse links inside the image caption
2237 # actually, this will parse them in any other parameters, too,
2238 # but it might be hard to fix that, and it doesn't matter ATM
2239 $text = $this->replaceExternalLinks( $text );
2240 $holders->merge( $this->replaceInternalLinks2( $text ) );
2242 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2243 $s .= $prefix . $this->armorLinks(
2244 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2246 $s .= $prefix . $trail;
2251 if ( $ns == NS_CATEGORY
) {
2252 $s = rtrim( $s . "\n" ); # bug 87
2255 $sortkey = $this->getDefaultSort();
2259 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2260 $sortkey = str_replace( "\n", '', $sortkey );
2261 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2262 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2265 * Strip the whitespace Category links produce, see bug 87
2267 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2273 # Self-link checking. For some languages, variants of the title are checked in
2274 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2275 # for linking to a different variant.
2276 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2277 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2281 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2282 # @todo FIXME: Should do batch file existence checks, see comment below
2283 if ( $ns == NS_MEDIA
) {
2284 # Give extensions a chance to select the file revision for us
2287 Hooks
::run( 'BeforeParserFetchFileAndTitle',
2288 array( $this, $nt, &$options, &$descQuery ) );
2289 # Fetch and register the file (file title may be different via hooks)
2290 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2291 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2292 $s .= $prefix . $this->armorLinks(
2293 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2297 # Some titles, such as valid special pages or files in foreign repos, should
2298 # be shown as bluelinks even though they're not included in the page table
2300 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2301 # batch file existence checks for NS_FILE and NS_MEDIA
2302 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2303 $this->mOutput
->addLink( $nt );
2304 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2306 # Links will be added to the output link list after checking
2307 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2314 * Render a forced-blue link inline; protect against double expansion of
2315 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2316 * Since this little disaster has to split off the trail text to avoid
2317 * breaking URLs in the following text without breaking trails on the
2318 * wiki links, it's been made into a horrible function.
2321 * @param string $text
2322 * @param array|string $query
2323 * @param string $trail
2324 * @param string $prefix
2325 * @return string HTML-wikitext mix oh yuck
2327 public function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2328 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2330 if ( is_string( $query ) ) {
2331 $query = wfCgiToArray( $query );
2333 if ( $text == '' ) {
2334 $text = htmlspecialchars( $nt->getPrefixedText() );
2337 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2339 return $this->armorLinks( $link ) . $trail;
2343 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2344 * going to go through further parsing steps before inline URL expansion.
2346 * Not needed quite as much as it used to be since free links are a bit
2347 * more sensible these days. But bracketed links are still an issue.
2349 * @param string $text More-or-less HTML
2350 * @return string Less-or-more HTML with NOPARSE bits
2352 public function armorLinks( $text ) {
2353 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2354 "{$this->mUniqPrefix}NOPARSE$1", $text );
2358 * Return true if subpage links should be expanded on this page.
2361 public function areSubpagesAllowed() {
2362 # Some namespaces don't allow subpages
2363 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2367 * Handle link to subpage if necessary
2369 * @param string $target The source of the link
2370 * @param string &$text The link text, modified as necessary
2371 * @return string The full name of the link
2374 public function maybeDoSubpageLink( $target, &$text ) {
2375 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2379 * Used by doBlockLevels()
2384 public function closeParagraph() {
2386 if ( $this->mLastSection
!= '' ) {
2387 $result = '</' . $this->mLastSection
. ">\n";
2389 $this->mInPre
= false;
2390 $this->mLastSection
= '';
2395 * getCommon() returns the length of the longest common substring
2396 * of both arguments, starting at the beginning of both.
2399 * @param string $st1
2400 * @param string $st2
2404 public function getCommon( $st1, $st2 ) {
2405 $fl = strlen( $st1 );
2406 $shorter = strlen( $st2 );
2407 if ( $fl < $shorter ) {
2411 for ( $i = 0; $i < $shorter; ++
$i ) {
2412 if ( $st1[$i] != $st2[$i] ) {
2420 * These next three functions open, continue, and close the list
2421 * element appropriate to the prefix character passed into them.
2424 * @param string $char
2428 public function openList( $char ) {
2429 $result = $this->closeParagraph();
2431 if ( '*' === $char ) {
2432 $result .= "<ul><li>";
2433 } elseif ( '#' === $char ) {
2434 $result .= "<ol><li>";
2435 } elseif ( ':' === $char ) {
2436 $result .= "<dl><dd>";
2437 } elseif ( ';' === $char ) {
2438 $result .= "<dl><dt>";
2439 $this->mDTopen
= true;
2441 $result = '<!-- ERR 1 -->';
2449 * @param string $char
2454 public function nextItem( $char ) {
2455 if ( '*' === $char ||
'#' === $char ) {
2456 return "</li>\n<li>";
2457 } elseif ( ':' === $char ||
';' === $char ) {
2459 if ( $this->mDTopen
) {
2462 if ( ';' === $char ) {
2463 $this->mDTopen
= true;
2464 return $close . '<dt>';
2466 $this->mDTopen
= false;
2467 return $close . '<dd>';
2470 return '<!-- ERR 2 -->';
2475 * @param string $char
2480 public function closeList( $char ) {
2481 if ( '*' === $char ) {
2482 $text = "</li></ul>";
2483 } elseif ( '#' === $char ) {
2484 $text = "</li></ol>";
2485 } elseif ( ':' === $char ) {
2486 if ( $this->mDTopen
) {
2487 $this->mDTopen
= false;
2488 $text = "</dt></dl>";
2490 $text = "</dd></dl>";
2493 return '<!-- ERR 3 -->';
2500 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2502 * @param string $text
2503 * @param bool $linestart Whether or not this is at the start of a line.
2505 * @return string The lists rendered as HTML
2507 public function doBlockLevels( $text, $linestart ) {
2509 # Parsing through the text line by line. The main thing
2510 # happening here is handling of block-level elements p, pre,
2511 # and making lists from lines starting with * # : etc.
2513 $textLines = StringUtils
::explode( "\n", $text );
2515 $lastPrefix = $output = '';
2516 $this->mDTopen
= $inBlockElem = false;
2518 $paragraphStack = false;
2519 $inBlockquote = false;
2521 foreach ( $textLines as $oLine ) {
2523 if ( !$linestart ) {
2533 $lastPrefixLength = strlen( $lastPrefix );
2534 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2535 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2536 # If not in a <pre> element, scan for and figure out what prefixes are there.
2537 if ( !$this->mInPre
) {
2538 # Multiple prefixes may abut each other for nested lists.
2539 $prefixLength = strspn( $oLine, '*#:;' );
2540 $prefix = substr( $oLine, 0, $prefixLength );
2543 # ; and : are both from definition-lists, so they're equivalent
2544 # for the purposes of determining whether or not we need to open/close
2546 $prefix2 = str_replace( ';', ':', $prefix );
2547 $t = substr( $oLine, $prefixLength );
2548 $this->mInPre
= (bool)$preOpenMatch;
2550 # Don't interpret any other prefixes in preformatted text
2552 $prefix = $prefix2 = '';
2557 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2558 # Same as the last item, so no need to deal with nesting or opening stuff
2559 $output .= $this->nextItem( substr( $prefix, -1 ) );
2560 $paragraphStack = false;
2562 if ( substr( $prefix, -1 ) === ';' ) {
2563 # The one nasty exception: definition lists work like this:
2564 # ; title : definition text
2565 # So we check for : in the remainder text to split up the
2566 # title and definition, without b0rking links.
2568 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2570 $output .= $term . $this->nextItem( ':' );
2573 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2574 # We need to open or close prefixes, or both.
2576 # Either open or close a level...
2577 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2578 $paragraphStack = false;
2580 # Close all the prefixes which aren't shared.
2581 while ( $commonPrefixLength < $lastPrefixLength ) {
2582 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2583 --$lastPrefixLength;
2586 # Continue the current prefix if appropriate.
2587 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2588 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2591 # Open prefixes where appropriate.
2592 if ( $lastPrefix && $prefixLength > $commonPrefixLength ) {
2595 while ( $prefixLength > $commonPrefixLength ) {
2596 $char = substr( $prefix, $commonPrefixLength, 1 );
2597 $output .= $this->openList( $char );
2599 if ( ';' === $char ) {
2600 # @todo FIXME: This is dupe of code above
2601 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2603 $output .= $term . $this->nextItem( ':' );
2606 ++
$commonPrefixLength;
2608 if ( !$prefixLength && $lastPrefix ) {
2611 $lastPrefix = $prefix2;
2614 # If we have no prefixes, go to paragraph mode.
2615 if ( 0 == $prefixLength ) {
2616 # No prefix (not in list)--go to paragraph mode
2617 # XXX: use a stack for nestable elements like span, table and div
2618 $openmatch = preg_match(
2619 '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|'
2620 . '<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS',
2623 $closematch = preg_match(
2624 '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'
2625 . '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|<\\/mw:|'
2626 . $this->mUniqPrefix
2627 . '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS',
2631 if ( $openmatch ||
$closematch ) {
2632 $paragraphStack = false;
2633 # @todo bug 5718: paragraph closed
2634 $output .= $this->closeParagraph();
2635 if ( $preOpenMatch && !$preCloseMatch ) {
2636 $this->mInPre
= true;
2639 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t, $bqMatch, PREG_OFFSET_CAPTURE
, $bqOffset ) ) {
2640 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
2641 $bqOffset = $bqMatch[0][1] +
strlen( $bqMatch[0][0] );
2643 $inBlockElem = !$closematch;
2644 } elseif ( !$inBlockElem && !$this->mInPre
) {
2645 if ( ' ' == substr( $t, 0, 1 )
2646 && ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' )
2650 if ( $this->mLastSection
!== 'pre' ) {
2651 $paragraphStack = false;
2652 $output .= $this->closeParagraph() . '<pre>';
2653 $this->mLastSection
= 'pre';
2655 $t = substr( $t, 1 );
2658 if ( trim( $t ) === '' ) {
2659 if ( $paragraphStack ) {
2660 $output .= $paragraphStack . '<br />';
2661 $paragraphStack = false;
2662 $this->mLastSection
= 'p';
2664 if ( $this->mLastSection
!== 'p' ) {
2665 $output .= $this->closeParagraph();
2666 $this->mLastSection
= '';
2667 $paragraphStack = '<p>';
2669 $paragraphStack = '</p><p>';
2673 if ( $paragraphStack ) {
2674 $output .= $paragraphStack;
2675 $paragraphStack = false;
2676 $this->mLastSection
= 'p';
2677 } elseif ( $this->mLastSection
!== 'p' ) {
2678 $output .= $this->closeParagraph() . '<p>';
2679 $this->mLastSection
= 'p';
2685 # somewhere above we forget to get out of pre block (bug 785)
2686 if ( $preCloseMatch && $this->mInPre
) {
2687 $this->mInPre
= false;
2689 if ( $paragraphStack === false ) {
2691 if ( $prefixLength === 0 ) {
2696 while ( $prefixLength ) {
2697 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2699 if ( !$prefixLength ) {
2703 if ( $this->mLastSection
!= '' ) {
2704 $output .= '</' . $this->mLastSection
. '>';
2705 $this->mLastSection
= '';
2712 * Split up a string on ':', ignoring any occurrences inside tags
2713 * to prevent illegal overlapping.
2715 * @param string $str The string to split
2716 * @param string &$before Set to everything before the ':'
2717 * @param string &$after Set to everything after the ':'
2718 * @throws MWException
2719 * @return string The position of the ':', or false if none found
2721 public function findColonNoLinks( $str, &$before, &$after ) {
2723 $pos = strpos( $str, ':' );
2724 if ( $pos === false ) {
2729 $lt = strpos( $str, '<' );
2730 if ( $lt === false ||
$lt > $pos ) {
2731 # Easy; no tag nesting to worry about
2732 $before = substr( $str, 0, $pos );
2733 $after = substr( $str, $pos +
1 );
2737 # Ugly state machine to walk through avoiding tags.
2738 $state = self
::COLON_STATE_TEXT
;
2740 $len = strlen( $str );
2741 for ( $i = 0; $i < $len; $i++
) {
2745 # (Using the number is a performance hack for common cases)
2746 case 0: # self::COLON_STATE_TEXT:
2749 # Could be either a <start> tag or an </end> tag
2750 $state = self
::COLON_STATE_TAGSTART
;
2753 if ( $stack == 0 ) {
2755 $before = substr( $str, 0, $i );
2756 $after = substr( $str, $i +
1 );
2759 # Embedded in a tag; don't break it.
2762 # Skip ahead looking for something interesting
2763 $colon = strpos( $str, ':', $i );
2764 if ( $colon === false ) {
2765 # Nothing else interesting
2768 $lt = strpos( $str, '<', $i );
2769 if ( $stack === 0 ) {
2770 if ( $lt === false ||
$colon < $lt ) {
2772 $before = substr( $str, 0, $colon );
2773 $after = substr( $str, $colon +
1 );
2777 if ( $lt === false ) {
2778 # Nothing else interesting to find; abort!
2779 # We're nested, but there's no close tags left. Abort!
2782 # Skip ahead to next tag start
2784 $state = self
::COLON_STATE_TAGSTART
;
2787 case 1: # self::COLON_STATE_TAG:
2792 $state = self
::COLON_STATE_TEXT
;
2795 # Slash may be followed by >?
2796 $state = self
::COLON_STATE_TAGSLASH
;
2802 case 2: # self::COLON_STATE_TAGSTART:
2805 $state = self
::COLON_STATE_CLOSETAG
;
2808 $state = self
::COLON_STATE_COMMENT
;
2811 # Illegal early close? This shouldn't happen D:
2812 $state = self
::COLON_STATE_TEXT
;
2815 $state = self
::COLON_STATE_TAG
;
2818 case 3: # self::COLON_STATE_CLOSETAG:
2823 wfDebug( __METHOD__
. ": Invalid input; too many close tags\n" );
2826 $state = self
::COLON_STATE_TEXT
;
2829 case self
::COLON_STATE_TAGSLASH
:
2831 # Yes, a self-closed tag <blah/>
2832 $state = self
::COLON_STATE_TEXT
;
2834 # Probably we're jumping the gun, and this is an attribute
2835 $state = self
::COLON_STATE_TAG
;
2838 case 5: # self::COLON_STATE_COMMENT:
2840 $state = self
::COLON_STATE_COMMENTDASH
;
2843 case self
::COLON_STATE_COMMENTDASH
:
2845 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2847 $state = self
::COLON_STATE_COMMENT
;
2850 case self
::COLON_STATE_COMMENTDASHDASH
:
2852 $state = self
::COLON_STATE_TEXT
;
2854 $state = self
::COLON_STATE_COMMENT
;
2858 throw new MWException( "State machine error in " . __METHOD__
);
2862 wfDebug( __METHOD__
. ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2869 * Return value of a magic variable (like PAGENAME)
2874 * @param bool|PPFrame $frame
2876 * @throws MWException
2879 public function getVariableValue( $index, $frame = false ) {
2880 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2881 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2883 if ( is_null( $this->mTitle
) ) {
2884 // If no title set, bad things are going to happen
2885 // later. Title should always be set since this
2886 // should only be called in the middle of a parse
2887 // operation (but the unit-tests do funky stuff)
2888 throw new MWException( __METHOD__
. ' Should only be '
2889 . ' called while parsing (no title set)' );
2893 * Some of these require message or data lookups and can be
2894 * expensive to check many times.
2896 if ( Hooks
::run( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2897 if ( isset( $this->mVarCache
[$index] ) ) {
2898 return $this->mVarCache
[$index];
2902 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2903 Hooks
::run( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2905 $pageLang = $this->getFunctionLang();
2911 case 'currentmonth':
2912 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ) );
2914 case 'currentmonth1':
2915 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2917 case 'currentmonthname':
2918 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2920 case 'currentmonthnamegen':
2921 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2923 case 'currentmonthabbrev':
2924 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2927 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ) );
2930 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ) );
2933 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ) );
2936 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2938 case 'localmonthname':
2939 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2941 case 'localmonthnamegen':
2942 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2944 case 'localmonthabbrev':
2945 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2948 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ) );
2951 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ) );
2954 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2957 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2959 case 'fullpagename':
2960 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2962 case 'fullpagenamee':
2963 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2966 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2968 case 'subpagenamee':
2969 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2971 case 'rootpagename':
2972 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2974 case 'rootpagenamee':
2975 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
2978 $this->mTitle
->getRootText()
2981 case 'basepagename':
2982 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2984 case 'basepagenamee':
2985 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
2988 $this->mTitle
->getBaseText()
2991 case 'talkpagename':
2992 if ( $this->mTitle
->canTalk() ) {
2993 $talkPage = $this->mTitle
->getTalkPage();
2994 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2999 case 'talkpagenamee':
3000 if ( $this->mTitle
->canTalk() ) {
3001 $talkPage = $this->mTitle
->getTalkPage();
3002 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
3007 case 'subjectpagename':
3008 $subjPage = $this->mTitle
->getSubjectPage();
3009 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
3011 case 'subjectpagenamee':
3012 $subjPage = $this->mTitle
->getSubjectPage();
3013 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
3015 case 'pageid': // requested in bug 23427
3016 $pageid = $this->getTitle()->getArticleID();
3017 if ( $pageid == 0 ) {
3018 # 0 means the page doesn't exist in the database,
3019 # which means the user is previewing a new page.
3020 # The vary-revision flag must be set, because the magic word
3021 # will have a different value once the page is saved.
3022 $this->mOutput
->setFlag( 'vary-revision' );
3023 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
3025 $value = $pageid ?
$pageid : null;
3028 # Let the edit saving system know we should parse the page
3029 # *after* a revision ID has been assigned.
3030 $this->mOutput
->setFlag( 'vary-revision' );
3031 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
3032 $value = $this->mRevisionId
;
3035 # Let the edit saving system know we should parse the page
3036 # *after* a revision ID has been assigned. This is for null edits.
3037 $this->mOutput
->setFlag( 'vary-revision' );
3038 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
3039 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
3041 case 'revisionday2':
3042 # Let the edit saving system know we should parse the page
3043 # *after* a revision ID has been assigned. This is for null edits.
3044 $this->mOutput
->setFlag( 'vary-revision' );
3045 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
3046 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
3048 case 'revisionmonth':
3049 # Let the edit saving system know we should parse the page
3050 # *after* a revision ID has been assigned. This is for null edits.
3051 $this->mOutput
->setFlag( 'vary-revision' );
3052 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
3053 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
3055 case 'revisionmonth1':
3056 # Let the edit saving system know we should parse the page
3057 # *after* a revision ID has been assigned. This is for null edits.
3058 $this->mOutput
->setFlag( 'vary-revision' );
3059 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
3060 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
3062 case 'revisionyear':
3063 # Let the edit saving system know we should parse the page
3064 # *after* a revision ID has been assigned. This is for null edits.
3065 $this->mOutput
->setFlag( 'vary-revision' );
3066 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
3067 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
3069 case 'revisiontimestamp':
3070 # Let the edit saving system know we should parse the page
3071 # *after* a revision ID has been assigned. This is for null edits.
3072 $this->mOutput
->setFlag( 'vary-revision' );
3073 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
3074 $value = $this->getRevisionTimestamp();
3076 case 'revisionuser':
3077 # Let the edit saving system know we should parse the page
3078 # *after* a revision ID has been assigned. This is for null edits.
3079 $this->mOutput
->setFlag( 'vary-revision' );
3080 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
3081 $value = $this->getRevisionUser();
3083 case 'revisionsize':
3084 # Let the edit saving system know we should parse the page
3085 # *after* a revision ID has been assigned. This is for null edits.
3086 $this->mOutput
->setFlag( 'vary-revision' );
3087 wfDebug( __METHOD__
. ": {{REVISIONSIZE}} used, setting vary-revision...\n" );
3088 $value = $this->getRevisionSize();
3091 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3094 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3096 case 'namespacenumber':
3097 $value = $this->mTitle
->getNamespace();
3100 $value = $this->mTitle
->canTalk()
3101 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
3105 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
3107 case 'subjectspace':
3108 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
3110 case 'subjectspacee':
3111 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
3113 case 'currentdayname':
3114 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
3117 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
3120 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
3123 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
3126 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3127 # int to remove the padding
3128 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
3131 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
3133 case 'localdayname':
3134 $value = $pageLang->getWeekdayName(
3135 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
3139 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
3142 $value = $pageLang->time(
3143 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
3149 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
3152 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3153 # int to remove the padding
3154 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
3157 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
3159 case 'numberofarticles':
3160 $value = $pageLang->formatNum( SiteStats
::articles() );
3162 case 'numberoffiles':
3163 $value = $pageLang->formatNum( SiteStats
::images() );
3165 case 'numberofusers':
3166 $value = $pageLang->formatNum( SiteStats
::users() );
3168 case 'numberofactiveusers':
3169 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
3171 case 'numberofpages':
3172 $value = $pageLang->formatNum( SiteStats
::pages() );
3174 case 'numberofadmins':
3175 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
3177 case 'numberofedits':
3178 $value = $pageLang->formatNum( SiteStats
::edits() );
3180 case 'currenttimestamp':
3181 $value = wfTimestamp( TS_MW
, $ts );
3183 case 'localtimestamp':
3184 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
3186 case 'currentversion':
3187 $value = SpecialVersion
::getVersion();
3190 return $wgArticlePath;
3196 return $wgServerName;
3198 return $wgScriptPath;
3200 return $wgStylePath;
3201 case 'directionmark':
3202 return $pageLang->getDirMark();
3203 case 'contentlanguage':
3204 global $wgLanguageCode;
3205 return $wgLanguageCode;
3206 case 'cascadingsources':
3207 $value = CoreParserFunctions
::cascadingsources( $this );
3212 'ParserGetVariableValueSwitch',
3213 array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame )
3220 $this->mVarCache
[$index] = $value;
3227 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3231 public function initialiseVariables() {
3232 $variableIDs = MagicWord
::getVariableIDs();
3233 $substIDs = MagicWord
::getSubstIDs();
3235 $this->mVariables
= new MagicWordArray( $variableIDs );
3236 $this->mSubstWords
= new MagicWordArray( $substIDs );
3240 * Preprocess some wikitext and return the document tree.
3241 * This is the ghost of replace_variables().
3243 * @param string $text The text to parse
3244 * @param int $flags Bitwise combination of:
3245 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
3246 * included. Default is to assume a direct page view.
3248 * The generated DOM tree must depend only on the input text and the flags.
3249 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3251 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3252 * change in the DOM tree for a given text, must be passed through the section identifier
3253 * in the section edit link and thus back to extractSections().
3255 * The output of this function is currently only cached in process memory, but a persistent
3256 * cache may be implemented at a later date which takes further advantage of these strict
3257 * dependency requirements.
3261 public function preprocessToDom( $text, $flags = 0 ) {
3262 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3267 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3273 public static function splitWhitespace( $s ) {
3274 $ltrimmed = ltrim( $s );
3275 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3276 $trimmed = rtrim( $ltrimmed );
3277 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3279 $w2 = substr( $ltrimmed, -$diff );
3283 return array( $w1, $trimmed, $w2 );
3287 * Replace magic variables, templates, and template arguments
3288 * with the appropriate text. Templates are substituted recursively,
3289 * taking care to avoid infinite loops.
3291 * Note that the substitution depends on value of $mOutputType:
3292 * self::OT_WIKI: only {{subst:}} templates
3293 * self::OT_PREPROCESS: templates but not extension tags
3294 * self::OT_HTML: all templates and extension tags
3296 * @param string $text The text to transform
3297 * @param bool|PPFrame $frame Object describing the arguments passed to the
3298 * template. Arguments may also be provided as an associative array, as
3299 * was the usual case before MW1.12. Providing arguments this way may be
3300 * useful for extensions wishing to perform variable replacement
3302 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3303 * double-brace expansion.
3306 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3307 # Is there any text? Also, Prevent too big inclusions!
3308 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3312 if ( $frame === false ) {
3313 $frame = $this->getPreprocessor()->newFrame();
3314 } elseif ( !( $frame instanceof PPFrame
) ) {
3315 wfDebug( __METHOD__
. " called using plain parameters instead of "
3316 . "a PPFrame instance. Creating custom frame.\n" );
3317 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3320 $dom = $this->preprocessToDom( $text );
3321 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3322 $text = $frame->expand( $dom, $flags );
3328 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3330 * @param array $args
3334 public static function createAssocArgs( $args ) {
3335 $assocArgs = array();
3337 foreach ( $args as $arg ) {
3338 $eqpos = strpos( $arg, '=' );
3339 if ( $eqpos === false ) {
3340 $assocArgs[$index++
] = $arg;
3342 $name = trim( substr( $arg, 0, $eqpos ) );
3343 $value = trim( substr( $arg, $eqpos +
1 ) );
3344 if ( $value === false ) {
3347 if ( $name !== false ) {
3348 $assocArgs[$name] = $value;
3357 * Warn the user when a parser limitation is reached
3358 * Will warn at most once the user per limitation type
3360 * @param string $limitationType Should be one of:
3361 * 'expensive-parserfunction' (corresponding messages:
3362 * 'expensive-parserfunction-warning',
3363 * 'expensive-parserfunction-category')
3364 * 'post-expand-template-argument' (corresponding messages:
3365 * 'post-expand-template-argument-warning',
3366 * 'post-expand-template-argument-category')
3367 * 'post-expand-template-inclusion' (corresponding messages:
3368 * 'post-expand-template-inclusion-warning',
3369 * 'post-expand-template-inclusion-category')
3370 * 'node-count-exceeded' (corresponding messages:
3371 * 'node-count-exceeded-warning',
3372 * 'node-count-exceeded-category')
3373 * 'expansion-depth-exceeded' (corresponding messages:
3374 * 'expansion-depth-exceeded-warning',
3375 * 'expansion-depth-exceeded-category')
3376 * @param string|int|null $current Current value
3377 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3378 * exceeded, provide the values (optional)
3380 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3381 # does no harm if $current and $max are present but are unnecessary for the message
3382 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3383 ->inLanguage( $this->mOptions
->getUserLangObj() )->text();
3384 $this->mOutput
->addWarning( $warning );
3385 $this->addTrackingCategory( "$limitationType-category" );
3389 * Return the text of a template, after recursively
3390 * replacing any variables or templates within the template.
3392 * @param array $piece The parts of the template
3393 * $piece['title']: the title, i.e. the part before the |
3394 * $piece['parts']: the parameter array
3395 * $piece['lineStart']: whether the brace was at the start of a line
3396 * @param PPFrame $frame The current frame, contains template arguments
3398 * @return string The text of the template
3400 public function braceSubstitution( $piece, $frame ) {
3404 // $text has been filled
3406 // wiki markup in $text should be escaped
3408 // $text is HTML, armour it against wikitext transformation
3410 // Force interwiki transclusion to be done in raw mode not rendered
3411 $forceRawInterwiki = false;
3412 // $text is a DOM node needing expansion in a child frame
3413 $isChildObj = false;
3414 // $text is a DOM node needing expansion in the current frame
3415 $isLocalObj = false;
3417 # Title object, where $text came from
3420 # $part1 is the bit before the first |, and must contain only title characters.
3421 # Various prefixes will be stripped from it later.
3422 $titleWithSpaces = $frame->expand( $piece['title'] );
3423 $part1 = trim( $titleWithSpaces );
3426 # Original title text preserved for various purposes
3427 $originalTitle = $part1;
3429 # $args is a list of argument nodes, starting from index 0, not including $part1
3430 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3431 # below won't work b/c this $args isn't an object
3432 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3434 $profileSection = null; // profile templates
3439 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3441 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3442 # Decide whether to expand template or keep wikitext as-is.
3443 if ( $this->ot
['wiki'] ) {
3444 if ( $substMatch === false ) {
3445 $literal = true; # literal when in PST with no prefix
3447 $literal = false; # expand when in PST with subst: or safesubst:
3450 if ( $substMatch == 'subst' ) {
3451 $literal = true; # literal when not in PST with plain subst:
3453 $literal = false; # expand when not in PST with safesubst: or no prefix
3457 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3464 if ( !$found && $args->getLength() == 0 ) {
3465 $id = $this->mVariables
->matchStartToEnd( $part1 );
3466 if ( $id !== false ) {
3467 $text = $this->getVariableValue( $id, $frame );
3468 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3469 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3475 # MSG, MSGNW and RAW
3478 $mwMsgnw = MagicWord
::get( 'msgnw' );
3479 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3482 # Remove obsolete MSG:
3483 $mwMsg = MagicWord
::get( 'msg' );
3484 $mwMsg->matchStartAndRemove( $part1 );
3488 $mwRaw = MagicWord
::get( 'raw' );
3489 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3490 $forceRawInterwiki = true;
3497 $colonPos = strpos( $part1, ':' );
3498 if ( $colonPos !== false ) {
3499 $func = substr( $part1, 0, $colonPos );
3500 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3501 for ( $i = 0; $i < $args->getLength(); $i++
) {
3502 $funcArgs[] = $args->item( $i );
3505 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3506 } catch ( Exception
$ex ) {
3510 # The interface for parser functions allows for extracting
3511 # flags into the local scope. Extract any forwarded flags
3517 # Finish mangling title and then check for loops.
3518 # Set $title to a Title object and $titleText to the PDBK
3521 # Split the title into page and subpage
3523 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3524 if ( $part1 !== $relative ) {
3526 $ns = $this->mTitle
->getNamespace();
3528 $title = Title
::newFromText( $part1, $ns );
3530 $titleText = $title->getPrefixedText();
3531 # Check for language variants if the template is not found
3532 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3533 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3535 # Do recursion depth check
3536 $limit = $this->mOptions
->getMaxTemplateDepth();
3537 if ( $frame->depth
>= $limit ) {
3539 $text = '<span class="error">'
3540 . wfMessage( 'parser-template-recursion-depth-warning' )
3541 ->numParams( $limit )->inContentLanguage()->text()
3547 # Load from database
3548 if ( !$found && $title ) {
3549 $profileSection = $this->mProfiler
->scopedProfileIn( $title->getPrefixedDBkey() );
3550 if ( !$title->isExternal() ) {
3551 if ( $title->isSpecialPage()
3552 && $this->mOptions
->getAllowSpecialInclusion()
3553 && $this->ot
['html']
3555 // Pass the template arguments as URL parameters.
3556 // "uselang" will have no effect since the Language object
3557 // is forced to the one defined in ParserOptions.
3558 $pageArgs = array();
3559 $argsLength = $args->getLength();
3560 for ( $i = 0; $i < $argsLength; $i++
) {
3561 $bits = $args->item( $i )->splitArg();
3562 if ( strval( $bits['index'] ) === '' ) {
3563 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3564 $value = trim( $frame->expand( $bits['value'] ) );
3565 $pageArgs[$name] = $value;
3569 // Create a new context to execute the special page
3570 $context = new RequestContext
;
3571 $context->setTitle( $title );
3572 $context->setRequest( new FauxRequest( $pageArgs ) );
3573 $context->setUser( $this->getUser() );
3574 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3575 $ret = SpecialPageFactory
::capturePath( $title, $context );
3577 $text = $context->getOutput()->getHTML();
3578 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3581 $this->disableCache();
3583 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3584 $found = false; # access denied
3585 wfDebug( __METHOD__
. ": template inclusion denied for " .
3586 $title->getPrefixedDBkey() . "\n" );
3588 list( $text, $title ) = $this->getTemplateDom( $title );
3589 if ( $text !== false ) {
3595 # If the title is valid but undisplayable, make a link to it
3596 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3597 $text = "[[:$titleText]]";
3600 } elseif ( $title->isTrans() ) {
3601 # Interwiki transclusion
3602 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3603 $text = $this->interwikiTransclude( $title, 'render' );
3606 $text = $this->interwikiTransclude( $title, 'raw' );
3607 # Preprocess it like a template
3608 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3614 # Do infinite loop check
3615 # This has to be done after redirect resolution to avoid infinite loops via redirects
3616 if ( !$frame->loopCheck( $title ) ) {
3618 $text = '<span class="error">'
3619 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3621 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3625 # If we haven't found text to substitute by now, we're done
3626 # Recover the source wikitext and return it
3628 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3629 if ( $profileSection ) {
3630 $this->mProfiler
->scopedProfileOut( $profileSection );
3632 return array( 'object' => $text );
3635 # Expand DOM-style return values in a child frame
3636 if ( $isChildObj ) {
3637 # Clean up argument array
3638 $newFrame = $frame->newChild( $args, $title );
3641 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3642 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3643 # Expansion is eligible for the empty-frame cache
3644 $text = $newFrame->cachedExpand( $titleText, $text );
3646 # Uncached expansion
3647 $text = $newFrame->expand( $text );
3650 if ( $isLocalObj && $nowiki ) {
3651 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3652 $isLocalObj = false;
3655 if ( $profileSection ) {
3656 $this->mProfiler
->scopedProfileOut( $profileSection );
3659 # Replace raw HTML by a placeholder
3661 $text = $this->insertStripItem( $text );
3662 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3663 # Escape nowiki-style return values
3664 $text = wfEscapeWikiText( $text );
3665 } elseif ( is_string( $text )
3666 && !$piece['lineStart']
3667 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3669 # Bug 529: if the template begins with a table or block-level
3670 # element, it should be treated as beginning a new line.
3671 # This behavior is somewhat controversial.
3672 $text = "\n" . $text;
3675 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3676 # Error, oversize inclusion
3677 if ( $titleText !== false ) {
3678 # Make a working, properly escaped link if possible (bug 23588)
3679 $text = "[[:$titleText]]";
3681 # This will probably not be a working link, but at least it may
3682 # provide some hint of where the problem is
3683 preg_replace( '/^:/', '', $originalTitle );
3684 $text = "[[:$originalTitle]]";
3686 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3687 . 'post-expand include size too large -->' );
3688 $this->limitationWarn( 'post-expand-template-inclusion' );
3691 if ( $isLocalObj ) {
3692 $ret = array( 'object' => $text );
3694 $ret = array( 'text' => $text );
3701 * Call a parser function and return an array with text and flags.
3703 * The returned array will always contain a boolean 'found', indicating
3704 * whether the parser function was found or not. It may also contain the
3706 * text: string|object, resulting wikitext or PP DOM object
3707 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3708 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3709 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3710 * nowiki: bool, wiki markup in $text should be escaped
3713 * @param PPFrame $frame The current frame, contains template arguments
3714 * @param string $function Function name
3715 * @param array $args Arguments to the function
3716 * @throws MWException
3719 public function callParserFunction( $frame, $function, array $args = array() ) {
3723 # Case sensitive functions
3724 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3725 $function = $this->mFunctionSynonyms
[1][$function];
3727 # Case insensitive functions
3728 $function = $wgContLang->lc( $function );
3729 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3730 $function = $this->mFunctionSynonyms
[0][$function];
3732 return array( 'found' => false );
3736 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3738 # Workaround for PHP bug 35229 and similar
3739 if ( !is_callable( $callback ) ) {
3740 throw new MWException( "Tag hook for $function is not callable\n" );
3743 $allArgs = array( &$this );
3744 if ( $flags & self
::SFH_OBJECT_ARGS
) {
3745 # Convert arguments to PPNodes and collect for appending to $allArgs
3746 $funcArgs = array();
3747 foreach ( $args as $k => $v ) {
3748 if ( $v instanceof PPNode ||
$k === 0 ) {
3751 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( array( $k => $v ) )->item( 0 );
3755 # Add a frame parameter, and pass the arguments as an array
3756 $allArgs[] = $frame;
3757 $allArgs[] = $funcArgs;
3759 # Convert arguments to plain text and append to $allArgs
3760 foreach ( $args as $k => $v ) {
3761 if ( $v instanceof PPNode
) {
3762 $allArgs[] = trim( $frame->expand( $v ) );
3763 } elseif ( is_int( $k ) && $k >= 0 ) {
3764 $allArgs[] = trim( $v );
3766 $allArgs[] = trim( "$k=$v" );
3771 $result = call_user_func_array( $callback, $allArgs );
3773 # The interface for function hooks allows them to return a wikitext
3774 # string or an array containing the string and any flags. This mungs
3775 # things around to match what this method should return.
3776 if ( !is_array( $result ) ) {
3782 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3783 $result['text'] = $result[0];
3785 unset( $result[0] );
3792 $preprocessFlags = 0;
3793 if ( isset( $result['noparse'] ) ) {
3794 $noparse = $result['noparse'];
3796 if ( isset( $result['preprocessFlags'] ) ) {
3797 $preprocessFlags = $result['preprocessFlags'];
3801 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3802 $result['isChildObj'] = true;
3809 * Get the semi-parsed DOM representation of a template with a given title,
3810 * and its redirect destination title. Cached.
3812 * @param Title $title
3816 public function getTemplateDom( $title ) {
3817 $cacheTitle = $title;
3818 $titleText = $title->getPrefixedDBkey();
3820 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3821 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3822 $title = Title
::makeTitle( $ns, $dbk );
3823 $titleText = $title->getPrefixedDBkey();
3825 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3826 return array( $this->mTplDomCache
[$titleText], $title );
3829 # Cache miss, go to the database
3830 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3832 if ( $text === false ) {
3833 $this->mTplDomCache
[$titleText] = false;
3834 return array( false, $title );
3837 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3838 $this->mTplDomCache
[$titleText] = $dom;
3840 if ( !$title->equals( $cacheTitle ) ) {
3841 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3842 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3845 return array( $dom, $title );
3849 * Fetch the current revision of a given title. Note that the revision
3850 * (and even the title) may not exist in the database, so everything
3851 * contributing to the output of the parser should use this method
3852 * where possible, rather than getting the revisions themselves. This
3853 * method also caches its results, so using it benefits performance.
3856 * @param Title $title
3859 public function fetchCurrentRevisionOfTitle( $title ) {
3860 $cacheKey = $title->getPrefixedDBkey();
3861 if ( !$this->currentRevisionCache
) {
3862 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3864 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3865 $this->currentRevisionCache
->set( $cacheKey,
3866 // Defaults to Parser::statelessFetchRevision()
3867 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3870 return $this->currentRevisionCache
->get( $cacheKey );
3874 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3875 * without passing them on to it.
3878 * @param Title $title
3879 * @param Parser|bool $parser
3882 public static function statelessFetchRevision( $title, $parser = false ) {
3883 return Revision
::newFromTitle( $title );
3887 * Fetch the unparsed text of a template and register a reference to it.
3888 * @param Title $title
3889 * @return array ( string or false, Title )
3891 public function fetchTemplateAndTitle( $title ) {
3892 // Defaults to Parser::statelessFetchTemplate()
3893 $templateCb = $this->mOptions
->getTemplateCallback();
3894 $stuff = call_user_func( $templateCb, $title, $this );
3895 $text = $stuff['text'];
3896 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3897 if ( isset( $stuff['deps'] ) ) {
3898 foreach ( $stuff['deps'] as $dep ) {
3899 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3900 if ( $dep['title']->equals( $this->getTitle() ) ) {
3901 // If we transclude ourselves, the final result
3902 // will change based on the new version of the page
3903 $this->mOutput
->setFlag( 'vary-revision' );
3907 return array( $text, $finalTitle );
3911 * Fetch the unparsed text of a template and register a reference to it.
3912 * @param Title $title
3913 * @return string|bool
3915 public function fetchTemplate( $title ) {
3916 $rv = $this->fetchTemplateAndTitle( $title );
3921 * Static function to get a template
3922 * Can be overridden via ParserOptions::setTemplateCallback().
3924 * @param Title $title
3925 * @param bool|Parser $parser
3929 public static function statelessFetchTemplate( $title, $parser = false ) {
3930 $text = $skip = false;
3931 $finalTitle = $title;
3934 # Loop to fetch the article, with up to 1 redirect
3935 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3936 # Give extensions a chance to select the revision instead
3937 $id = false; # Assume current
3938 Hooks
::run( 'BeforeParserFetchTemplateAndtitle',
3939 array( $parser, $title, &$skip, &$id ) );
3945 'page_id' => $title->getArticleID(),
3952 $rev = Revision
::newFromId( $id );
3953 } elseif ( $parser ) {
3954 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3956 $rev = Revision
::newFromTitle( $title );
3958 $rev_id = $rev ?
$rev->getId() : 0;
3959 # If there is no current revision, there is no page
3960 if ( $id === false && !$rev ) {
3961 $linkCache = LinkCache
::singleton();
3962 $linkCache->addBadLinkObj( $title );
3967 'page_id' => $title->getArticleID(),
3968 'rev_id' => $rev_id );
3969 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3970 # We fetched a rev from a different title; register it too...
3972 'title' => $rev->getTitle(),
3973 'page_id' => $rev->getPage(),
3974 'rev_id' => $rev_id );
3978 $content = $rev->getContent();
3979 $text = $content ?
$content->getWikitextForTransclusion() : null;
3981 if ( $text === false ||
$text === null ) {
3985 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3987 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3988 if ( !$message->exists() ) {
3992 $content = $message->content();
3993 $text = $message->plain();
4001 $finalTitle = $title;
4002 $title = $content->getRedirectTarget();
4006 'finalTitle' => $finalTitle,
4011 * Fetch a file and its title and register a reference to it.
4012 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4013 * @param Title $title
4014 * @param array $options Array of options to RepoGroup::findFile
4017 public function fetchFile( $title, $options = array() ) {
4018 $res = $this->fetchFileAndTitle( $title, $options );
4023 * Fetch a file and its title and register a reference to it.
4024 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4025 * @param Title $title
4026 * @param array $options Array of options to RepoGroup::findFile
4027 * @return array ( File or false, Title of file )
4029 public function fetchFileAndTitle( $title, $options = array() ) {
4030 $file = $this->fetchFileNoRegister( $title, $options );
4032 $time = $file ?
$file->getTimestamp() : false;
4033 $sha1 = $file ?
$file->getSha1() : false;
4034 # Register the file as a dependency...
4035 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4036 if ( $file && !$title->equals( $file->getTitle() ) ) {
4037 # Update fetched file title
4038 $title = $file->getTitle();
4039 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4041 return array( $file, $title );
4045 * Helper function for fetchFileAndTitle.
4047 * Also useful if you need to fetch a file but not use it yet,
4048 * for example to get the file's handler.
4050 * @param Title $title
4051 * @param array $options Array of options to RepoGroup::findFile
4054 protected function fetchFileNoRegister( $title, $options = array() ) {
4055 if ( isset( $options['broken'] ) ) {
4056 $file = false; // broken thumbnail forced by hook
4057 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
4058 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
4059 } else { // get by (name,timestamp)
4060 $file = wfFindFile( $title, $options );
4066 * Transclude an interwiki link.
4068 * @param Title $title
4069 * @param string $action
4073 public function interwikiTransclude( $title, $action ) {
4074 global $wgEnableScaryTranscluding;
4076 if ( !$wgEnableScaryTranscluding ) {
4077 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
4080 $url = $title->getFullURL( array( 'action' => $action ) );
4082 if ( strlen( $url ) > 255 ) {
4083 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
4085 return $this->fetchScaryTemplateMaybeFromCache( $url );
4089 * @param string $url
4090 * @return mixed|string
4092 public function fetchScaryTemplateMaybeFromCache( $url ) {
4093 global $wgTranscludeCacheExpiry;
4094 $dbr = wfGetDB( DB_SLAVE
);
4095 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
4096 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
4097 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
4099 return $obj->tc_contents
;
4102 $req = MWHttpRequest
::factory( $url, array(), __METHOD__
);
4103 $status = $req->execute(); // Status object
4104 if ( $status->isOK() ) {
4105 $text = $req->getContent();
4106 } elseif ( $req->getStatus() != 200 ) {
4107 // Though we failed to fetch the content, this status is useless.
4108 return wfMessage( 'scarytranscludefailed-httpstatus' )
4109 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
4111 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
4114 $dbw = wfGetDB( DB_MASTER
);
4115 $dbw->replace( 'transcache', array( 'tc_url' ), array(
4117 'tc_time' => $dbw->timestamp( time() ),
4118 'tc_contents' => $text
4124 * Triple brace replacement -- used for template arguments
4127 * @param array $piece
4128 * @param PPFrame $frame
4132 public function argSubstitution( $piece, $frame ) {
4135 $parts = $piece['parts'];
4136 $nameWithSpaces = $frame->expand( $piece['title'] );
4137 $argName = trim( $nameWithSpaces );
4139 $text = $frame->getArgument( $argName );
4140 if ( $text === false && $parts->getLength() > 0
4141 && ( $this->ot
['html']
4143 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
4146 # No match in frame, use the supplied default
4147 $object = $parts->item( 0 )->getChildren();
4149 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
4150 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
4151 $this->limitationWarn( 'post-expand-template-argument' );
4154 if ( $text === false && $object === false ) {
4156 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
4158 if ( $error !== false ) {
4161 if ( $object !== false ) {
4162 $ret = array( 'object' => $object );
4164 $ret = array( 'text' => $text );
4171 * Return the text to be used for a given extension tag.
4172 * This is the ghost of strip().
4174 * @param array $params Associative array of parameters:
4175 * name PPNode for the tag name
4176 * attr PPNode for unparsed text where tag attributes are thought to be
4177 * attributes Optional associative array of parsed attributes
4178 * inner Contents of extension element
4179 * noClose Original text did not have a close tag
4180 * @param PPFrame $frame
4182 * @throws MWException
4185 public function extensionSubstitution( $params, $frame ) {
4186 $name = $frame->expand( $params['name'] );
4187 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
4188 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
4189 $marker = "{$this->mUniqPrefix}-$name-"
4190 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
4192 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
4193 ( $this->ot
['html'] ||
$this->ot
['pre'] );
4194 if ( $isFunctionTag ) {
4195 $markerType = 'none';
4197 $markerType = 'general';
4199 if ( $this->ot
['html'] ||
$isFunctionTag ) {
4200 $name = strtolower( $name );
4201 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
4202 if ( isset( $params['attributes'] ) ) {
4203 $attributes = $attributes +
$params['attributes'];
4206 if ( isset( $this->mTagHooks
[$name] ) ) {
4207 # Workaround for PHP bug 35229 and similar
4208 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
4209 throw new MWException( "Tag hook for $name is not callable\n" );
4211 $output = call_user_func_array( $this->mTagHooks
[$name],
4212 array( $content, $attributes, $this, $frame ) );
4213 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
4214 list( $callback, ) = $this->mFunctionTagHooks
[$name];
4215 if ( !is_callable( $callback ) ) {
4216 throw new MWException( "Tag hook for $name is not callable\n" );
4219 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
4221 $output = '<span class="error">Invalid tag extension name: ' .
4222 htmlspecialchars( $name ) . '</span>';
4225 if ( is_array( $output ) ) {
4226 # Extract flags to local scope (to override $markerType)
4228 $output = $flags[0];
4233 if ( is_null( $attrText ) ) {
4236 if ( isset( $params['attributes'] ) ) {
4237 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4238 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4239 htmlspecialchars( $attrValue ) . '"';
4242 if ( $content === null ) {
4243 $output = "<$name$attrText/>";
4245 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4246 $output = "<$name$attrText>$content$close";
4250 if ( $markerType === 'none' ) {
4252 } elseif ( $markerType === 'nowiki' ) {
4253 $this->mStripState
->addNoWiki( $marker, $output );
4254 } elseif ( $markerType === 'general' ) {
4255 $this->mStripState
->addGeneral( $marker, $output );
4257 throw new MWException( __METHOD__
. ': invalid marker type' );
4263 * Increment an include size counter
4265 * @param string $type The type of expansion
4266 * @param int $size The size of the text
4267 * @return bool False if this inclusion would take it over the maximum, true otherwise
4269 public function incrementIncludeSize( $type, $size ) {
4270 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4273 $this->mIncludeSizes
[$type] +
= $size;
4279 * Increment the expensive function count
4281 * @return bool False if the limit has been exceeded
4283 public function incrementExpensiveFunctionCount() {
4284 $this->mExpensiveFunctionCount++
;
4285 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4289 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4290 * Fills $this->mDoubleUnderscores, returns the modified text
4292 * @param string $text
4296 public function doDoubleUnderscore( $text ) {
4298 # The position of __TOC__ needs to be recorded
4299 $mw = MagicWord
::get( 'toc' );
4300 if ( $mw->match( $text ) ) {
4301 $this->mShowToc
= true;
4302 $this->mForceTocPosition
= true;
4304 # Set a placeholder. At the end we'll fill it in with the TOC.
4305 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4307 # Only keep the first one.
4308 $text = $mw->replace( '', $text );
4311 # Now match and remove the rest of them
4312 $mwa = MagicWord
::getDoubleUnderscoreArray();
4313 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4315 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4316 $this->mOutput
->mNoGallery
= true;
4318 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4319 $this->mShowToc
= false;
4321 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4322 && $this->mTitle
->getNamespace() == NS_CATEGORY
4324 $this->addTrackingCategory( 'hidden-category-category' );
4326 # (bug 8068) Allow control over whether robots index a page.
4328 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4329 # is not desirable, the last one on the page should win.
4330 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4331 $this->mOutput
->setIndexPolicy( 'noindex' );
4332 $this->addTrackingCategory( 'noindex-category' );
4334 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4335 $this->mOutput
->setIndexPolicy( 'index' );
4336 $this->addTrackingCategory( 'index-category' );
4339 # Cache all double underscores in the database
4340 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4341 $this->mOutput
->setProperty( $key, '' );
4348 * @see ParserOutput::addTrackingCategory()
4349 * @param string $msg Message key
4350 * @return bool Whether the addition was successful
4352 public function addTrackingCategory( $msg ) {
4353 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4357 * This function accomplishes several tasks:
4358 * 1) Auto-number headings if that option is enabled
4359 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4360 * 3) Add a Table of contents on the top for users who have enabled the option
4361 * 4) Auto-anchor headings
4363 * It loops through all headlines, collects the necessary data, then splits up the
4364 * string and re-inserts the newly formatted headlines.
4366 * @param string $text
4367 * @param string $origText Original, untouched wikitext
4368 * @param bool $isMain
4369 * @return mixed|string
4372 public function formatHeadings( $text, $origText, $isMain = true ) {
4373 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4375 # Inhibit editsection links if requested in the page
4376 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4377 $maybeShowEditLink = $showEditLink = false;
4379 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4380 $showEditLink = $this->mOptions
->getEditSection();
4382 if ( $showEditLink ) {
4383 $this->mOutput
->setEditSectionTokens( true );
4386 # Get all headlines for numbering them and adding funky stuff like [edit]
4387 # links - this is for later, but we need the number of headlines right now
4389 $numMatches = preg_match_all(
4390 '/<H(?P<level>[1-6])(?P<attrib>.*?>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i',
4395 # if there are fewer than 4 headlines in the article, do not show TOC
4396 # unless it's been explicitly enabled.
4397 $enoughToc = $this->mShowToc
&&
4398 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4400 # Allow user to stipulate that a page should have a "new section"
4401 # link added via __NEWSECTIONLINK__
4402 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4403 $this->mOutput
->setNewSection( true );
4406 # Allow user to remove the "new section"
4407 # link via __NONEWSECTIONLINK__
4408 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4409 $this->mOutput
->hideNewSection( true );
4412 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4413 # override above conditions and always show TOC above first header
4414 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4415 $this->mShowToc
= true;
4423 # Ugh .. the TOC should have neat indentation levels which can be
4424 # passed to the skin functions. These are determined here
4428 $sublevelCount = array();
4429 $levelCount = array();
4434 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4435 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4436 $oldType = $this->mOutputType
;
4437 $this->setOutputType( self
::OT_WIKI
);
4438 $frame = $this->getPreprocessor()->newFrame();
4439 $root = $this->preprocessToDom( $origText );
4440 $node = $root->getFirstChild();
4445 foreach ( $matches[3] as $headline ) {
4446 $isTemplate = false;
4448 $sectionIndex = false;
4450 $markerMatches = array();
4451 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4452 $serial = $markerMatches[1];
4453 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4454 $isTemplate = ( $titleText != $baseTitleText );
4455 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4459 $prevlevel = $level;
4461 $level = $matches[1][$headlineCount];
4463 if ( $level > $prevlevel ) {
4464 # Increase TOC level
4466 $sublevelCount[$toclevel] = 0;
4467 if ( $toclevel < $wgMaxTocLevel ) {
4468 $prevtoclevel = $toclevel;
4469 $toc .= Linker
::tocIndent();
4472 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4473 # Decrease TOC level, find level to jump to
4475 for ( $i = $toclevel; $i > 0; $i-- ) {
4476 if ( $levelCount[$i] == $level ) {
4477 # Found last matching level
4480 } elseif ( $levelCount[$i] < $level ) {
4481 # Found first matching level below current level
4489 if ( $toclevel < $wgMaxTocLevel ) {
4490 if ( $prevtoclevel < $wgMaxTocLevel ) {
4491 # Unindent only if the previous toc level was shown :p
4492 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4493 $prevtoclevel = $toclevel;
4495 $toc .= Linker
::tocLineEnd();
4499 # No change in level, end TOC line
4500 if ( $toclevel < $wgMaxTocLevel ) {
4501 $toc .= Linker
::tocLineEnd();
4505 $levelCount[$toclevel] = $level;
4507 # count number of headlines for each level
4508 $sublevelCount[$toclevel]++
;
4510 for ( $i = 1; $i <= $toclevel; $i++
) {
4511 if ( !empty( $sublevelCount[$i] ) ) {
4515 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4520 # The safe header is a version of the header text safe to use for links
4522 # Remove link placeholders by the link text.
4523 # <!--LINK number-->
4525 # link text with suffix
4526 # Do this before unstrip since link text can contain strip markers
4527 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4529 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4530 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4532 # Strip out HTML (first regex removes any tag not allowed)
4534 # * <sup> and <sub> (bug 8393)
4537 # * <bdi> (bug 72884)
4538 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4540 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4541 # to allow setting directionality in toc items.
4542 $tocline = preg_replace(
4544 '#<(?!/?(span|sup|sub|bdi|i|b)(?: [^>]*)?>).*?>#',
4545 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b))(?: .*?)?>#'
4547 array( '', '<$1>' ),
4550 $tocline = trim( $tocline );
4552 # For the anchor, strip out HTML-y stuff period
4553 $safeHeadline = preg_replace( '/<.*?>/', '', $safeHeadline );
4554 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4556 # Save headline for section edit hint before it's escaped
4557 $headlineHint = $safeHeadline;
4559 if ( $wgExperimentalHtmlIds ) {
4560 # For reverse compatibility, provide an id that's
4561 # HTML4-compatible, like we used to.
4563 # It may be worth noting, academically, that it's possible for
4564 # the legacy anchor to conflict with a non-legacy headline
4565 # anchor on the page. In this case likely the "correct" thing
4566 # would be to either drop the legacy anchors or make sure
4567 # they're numbered first. However, this would require people
4568 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4569 # manually, so let's not bother worrying about it.
4570 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4571 array( 'noninitial', 'legacy' ) );
4572 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4574 if ( $legacyHeadline == $safeHeadline ) {
4575 # No reason to have both (in fact, we can't)
4576 $legacyHeadline = false;
4579 $legacyHeadline = false;
4580 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4584 # HTML names must be case-insensitively unique (bug 10721).
4585 # This does not apply to Unicode characters per
4586 # http://www.w3.org/TR/html5/infrastructure.html#case-sensitivity-and-string-comparison
4587 # @todo FIXME: We may be changing them depending on the current locale.
4588 $arrayKey = strtolower( $safeHeadline );
4589 if ( $legacyHeadline === false ) {
4590 $legacyArrayKey = false;
4592 $legacyArrayKey = strtolower( $legacyHeadline );
4595 # Create the anchor for linking from the TOC to the section
4596 $anchor = $safeHeadline;
4597 $legacyAnchor = $legacyHeadline;
4598 if ( isset( $refers[$arrayKey] ) ) {
4599 for ( $i = 2; isset( $refers["${arrayKey}_$i"] ); ++
$i );
4601 $refers["${arrayKey}_$i"] = true;
4603 $refers[$arrayKey] = true;
4605 if ( $legacyHeadline !== false && isset( $refers[$legacyArrayKey] ) ) {
4606 for ( $i = 2; isset( $refers["${legacyArrayKey}_$i"] ); ++
$i );
4607 $legacyAnchor .= "_$i";
4608 $refers["${legacyArrayKey}_$i"] = true;
4610 $refers[$legacyArrayKey] = true;
4613 # Don't number the heading if it is the only one (looks silly)
4614 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4615 # the two are different if the line contains a link
4616 $headline = Html
::element(
4618 array( 'class' => 'mw-headline-number' ),
4620 ) . ' ' . $headline;
4623 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4624 $toc .= Linker
::tocLine( $anchor, $tocline,
4625 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4628 # Add the section to the section tree
4629 # Find the DOM node for this header
4630 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4631 while ( $node && !$noOffset ) {
4632 if ( $node->getName() === 'h' ) {
4633 $bits = $node->splitHeading();
4634 if ( $bits['i'] == $sectionIndex ) {
4638 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4639 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4640 $node = $node->getNextSibling();
4643 'toclevel' => $toclevel,
4646 'number' => $numbering,
4647 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4648 'fromtitle' => $titleText,
4649 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4650 'anchor' => $anchor,
4653 # give headline the correct <h#> tag
4654 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4655 // Output edit section links as markers with styles that can be customized by skins
4656 if ( $isTemplate ) {
4657 # Put a T flag in the section identifier, to indicate to extractSections()
4658 # that sections inside <includeonly> should be counted.
4659 $editsectionPage = $titleText;
4660 $editsectionSection = "T-$sectionIndex";
4661 $editsectionContent = null;
4663 $editsectionPage = $this->mTitle
->getPrefixedText();
4664 $editsectionSection = $sectionIndex;
4665 $editsectionContent = $headlineHint;
4667 // We use a bit of pesudo-xml for editsection markers. The
4668 // language converter is run later on. Using a UNIQ style marker
4669 // leads to the converter screwing up the tokens when it
4670 // converts stuff. And trying to insert strip tags fails too. At
4671 // this point all real inputted tags have already been escaped,
4672 // so we don't have to worry about a user trying to input one of
4673 // these markers directly. We use a page and section attribute
4674 // to stop the language converter from converting these
4675 // important bits of data, but put the headline hint inside a
4676 // content block because the language converter is supposed to
4677 // be able to convert that piece of data.
4678 // Gets replaced with html in ParserOutput::getText
4679 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4680 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4681 if ( $editsectionContent !== null ) {
4682 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4689 $head[$headlineCount] = Linker
::makeHeadline( $level,
4690 $matches['attrib'][$headlineCount], $anchor, $headline,
4691 $editlink, $legacyAnchor );
4696 $this->setOutputType( $oldType );
4698 # Never ever show TOC if no headers
4699 if ( $numVisible < 1 ) {
4704 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4705 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4707 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4708 $this->mOutput
->setTOCHTML( $toc );
4709 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4710 $this->mOutput
->addModules( 'mediawiki.toc' );
4714 $this->mOutput
->setSections( $tocraw );
4717 # split up and insert constructed headlines
4718 $blocks = preg_split( '/<H[1-6].*?>[\s\S]*?<\/H[1-6]>/i', $text );
4721 // build an array of document sections
4722 $sections = array();
4723 foreach ( $blocks as $block ) {
4724 // $head is zero-based, sections aren't.
4725 if ( empty( $head[$i - 1] ) ) {
4726 $sections[$i] = $block;
4728 $sections[$i] = $head[$i - 1] . $block;
4732 * Send a hook, one per section.
4733 * The idea here is to be able to make section-level DIVs, but to do so in a
4734 * lower-impact, more correct way than r50769
4737 * $section : the section number
4738 * &$sectionContent : ref to the content of the section
4739 * $showEditLinks : boolean describing whether this section has an edit link
4741 Hooks
::run( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4746 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4747 // append the TOC at the beginning
4748 // Top anchor now in skin
4749 $sections[0] = $sections[0] . $toc . "\n";
4752 $full .= join( '', $sections );
4754 if ( $this->mForceTocPosition
) {
4755 return str_replace( '<!--MWTOC-->', $toc, $full );
4762 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4763 * conversion, substituting signatures, {{subst:}} templates, etc.
4765 * @param string $text The text to transform
4766 * @param Title $title The Title object for the current article
4767 * @param User $user The User object describing the current user
4768 * @param ParserOptions $options Parsing options
4769 * @param bool $clearState Whether to clear the parser state first
4770 * @return string The altered wiki markup
4772 public function preSaveTransform( $text, Title
$title, User
$user,
4773 ParserOptions
$options, $clearState = true
4775 if ( $clearState ) {
4776 $magicScopeVariable = $this->lock();
4778 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4779 $this->setUser( $user );
4785 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4786 if ( $options->getPreSaveTransform() ) {
4787 $text = $this->pstPass2( $text, $user );
4789 $text = $this->mStripState
->unstripBoth( $text );
4791 $this->setUser( null ); #Reset
4797 * Pre-save transform helper function
4799 * @param string $text
4804 private function pstPass2( $text, $user ) {
4807 # Note: This is the timestamp saved as hardcoded wikitext to
4808 # the database, we use $wgContLang here in order to give
4809 # everyone the same signature and use the default one rather
4810 # than the one selected in each user's preferences.
4811 # (see also bug 12815)
4812 $ts = $this->mOptions
->getTimestamp();
4813 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4814 $ts = $timestamp->format( 'YmdHis' );
4815 $tzMsg = $timestamp->format( 'T' ); # might vary on DST changeover!
4817 # Allow translation of timezones through wiki. format() can return
4818 # whatever crap the system uses, localised or not, so we cannot
4819 # ship premade translations.
4820 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4821 $msg = wfMessage( $key )->inContentLanguage();
4822 if ( $msg->exists() ) {
4823 $tzMsg = $msg->text();
4826 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4828 # Variable replacement
4829 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4830 $text = $this->replaceVariables( $text );
4832 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4833 # which may corrupt this parser instance via its wfMessage()->text() call-
4836 $sigText = $this->getUserSig( $user );
4837 $text = strtr( $text, array(
4839 '~~~~' => "$sigText $d",
4843 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4844 $tc = '[' . Title
::legalChars() . ']';
4845 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4847 // [[ns:page (context)|]]
4848 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4849 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4850 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4851 // [[ns:page (context), context|]] (using either single or double-width comma)
4852 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4853 // [[|page]] (reverse pipe trick: add context from page title)
4854 $p2 = "/\[\[\\|($tc+)]]/";
4856 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4857 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4858 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4859 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4861 $t = $this->mTitle
->getText();
4863 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4864 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4865 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4866 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4868 # if there's no context, don't bother duplicating the title
4869 $text = preg_replace( $p2, '[[\\1]]', $text );
4872 # Trim trailing whitespace
4873 $text = rtrim( $text );
4879 * Fetch the user's signature text, if any, and normalize to
4880 * validated, ready-to-insert wikitext.
4881 * If you have pre-fetched the nickname or the fancySig option, you can
4882 * specify them here to save a database query.
4883 * Do not reuse this parser instance after calling getUserSig(),
4884 * as it may have changed if it's the $wgParser.
4887 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4888 * @param bool|null $fancySig whether the nicknname is the complete signature
4889 * or null to use default value
4892 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4893 global $wgMaxSigChars;
4895 $username = $user->getName();
4897 # If not given, retrieve from the user object.
4898 if ( $nickname === false ) {
4899 $nickname = $user->getOption( 'nickname' );
4902 if ( is_null( $fancySig ) ) {
4903 $fancySig = $user->getBoolOption( 'fancysig' );
4906 $nickname = $nickname == null ?
$username : $nickname;
4908 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4909 $nickname = $username;
4910 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4911 } elseif ( $fancySig !== false ) {
4912 # Sig. might contain markup; validate this
4913 if ( $this->validateSig( $nickname ) !== false ) {
4914 # Validated; clean up (if needed) and return it
4915 return $this->cleanSig( $nickname, true );
4917 # Failed to validate; fall back to the default
4918 $nickname = $username;
4919 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4923 # Make sure nickname doesnt get a sig in a sig
4924 $nickname = self
::cleanSigInSig( $nickname );
4926 # If we're still here, make it a link to the user page
4927 $userText = wfEscapeWikiText( $username );
4928 $nickText = wfEscapeWikiText( $nickname );
4929 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4931 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4932 ->title( $this->getTitle() )->text();
4936 * Check that the user's signature contains no bad XML
4938 * @param string $text
4939 * @return string|bool An expanded string, or false if invalid.
4941 public function validateSig( $text ) {
4942 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4946 * Clean up signature text
4948 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4949 * 2) Substitute all transclusions
4951 * @param string $text
4952 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4953 * @return string Signature text
4955 public function cleanSig( $text, $parsing = false ) {
4958 $magicScopeVariable = $this->lock();
4959 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4962 # Option to disable this feature
4963 if ( !$this->mOptions
->getCleanSignatures() ) {
4967 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4968 # => Move this logic to braceSubstitution()
4969 $substWord = MagicWord
::get( 'subst' );
4970 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4971 $substText = '{{' . $substWord->getSynonym( 0 );
4973 $text = preg_replace( $substRegex, $substText, $text );
4974 $text = self
::cleanSigInSig( $text );
4975 $dom = $this->preprocessToDom( $text );
4976 $frame = $this->getPreprocessor()->newFrame();
4977 $text = $frame->expand( $dom );
4980 $text = $this->mStripState
->unstripBoth( $text );
4987 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4989 * @param string $text
4990 * @return string Signature text with /~{3,5}/ removed
4992 public static function cleanSigInSig( $text ) {
4993 $text = preg_replace( '/~{3,5}/', '', $text );
4998 * Set up some variables which are usually set up in parse()
4999 * so that an external function can call some class members with confidence
5001 * @param Title|null $title
5002 * @param ParserOptions $options
5003 * @param int $outputType
5004 * @param bool $clearState
5006 public function startExternalParse( Title
$title = null, ParserOptions
$options,
5007 $outputType, $clearState = true
5009 $this->startParse( $title, $options, $outputType, $clearState );
5013 * @param Title|null $title
5014 * @param ParserOptions $options
5015 * @param int $outputType
5016 * @param bool $clearState
5018 private function startParse( Title
$title = null, ParserOptions
$options,
5019 $outputType, $clearState = true
5021 $this->setTitle( $title );
5022 $this->mOptions
= $options;
5023 $this->setOutputType( $outputType );
5024 if ( $clearState ) {
5025 $this->clearState();
5030 * Wrapper for preprocess()
5032 * @param string $text The text to preprocess
5033 * @param ParserOptions $options Options
5034 * @param Title|null $title Title object or null to use $wgTitle
5037 public function transformMsg( $text, $options, $title = null ) {
5038 static $executing = false;
5040 # Guard against infinite recursion
5051 $text = $this->preprocess( $text, $title, $options );
5058 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
5059 * The callback should have the following form:
5060 * function myParserHook( $text, $params, $parser, $frame ) { ... }
5062 * Transform and return $text. Use $parser for any required context, e.g. use
5063 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
5065 * Hooks may return extended information by returning an array, of which the
5066 * first numbered element (index 0) must be the return string, and all other
5067 * entries are extracted into local variables within an internal function
5068 * in the Parser class.
5070 * This interface (introduced r61913) appears to be undocumented, but
5071 * 'markerName' is used by some core tag hooks to override which strip
5072 * array their results are placed in. **Use great caution if attempting
5073 * this interface, as it is not documented and injudicious use could smash
5074 * private variables.**
5076 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5077 * @param callable $callback The callback function (and object) to use for the tag
5078 * @throws MWException
5079 * @return callable|null The old value of the mTagHooks array associated with the hook
5081 public function setHook( $tag, $callback ) {
5082 $tag = strtolower( $tag );
5083 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5084 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
5086 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
5087 $this->mTagHooks
[$tag] = $callback;
5088 if ( !in_array( $tag, $this->mStripList
) ) {
5089 $this->mStripList
[] = $tag;
5096 * As setHook(), but letting the contents be parsed.
5098 * Transparent tag hooks are like regular XML-style tag hooks, except they
5099 * operate late in the transformation sequence, on HTML instead of wikitext.
5101 * This is probably obsoleted by things dealing with parser frames?
5102 * The only extension currently using it is geoserver.
5105 * @todo better document or deprecate this
5107 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5108 * @param callable $callback The callback function (and object) to use for the tag
5109 * @throws MWException
5110 * @return callable|null The old value of the mTagHooks array associated with the hook
5112 public function setTransparentTagHook( $tag, $callback ) {
5113 $tag = strtolower( $tag );
5114 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5115 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
5117 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
5118 $this->mTransparentTagHooks
[$tag] = $callback;
5124 * Remove all tag hooks
5126 public function clearTagHooks() {
5127 $this->mTagHooks
= array();
5128 $this->mFunctionTagHooks
= array();
5129 $this->mStripList
= $this->mDefaultStripList
;
5133 * Create a function, e.g. {{sum:1|2|3}}
5134 * The callback function should have the form:
5135 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
5137 * Or with Parser::SFH_OBJECT_ARGS:
5138 * function myParserFunction( $parser, $frame, $args ) { ... }
5140 * The callback may either return the text result of the function, or an array with the text
5141 * in element 0, and a number of flags in the other elements. The names of the flags are
5142 * specified in the keys. Valid flags are:
5143 * found The text returned is valid, stop processing the template. This
5145 * nowiki Wiki markup in the return value should be escaped
5146 * isHTML The returned text is HTML, armour it against wikitext transformation
5148 * @param string $id The magic word ID
5149 * @param callable $callback The callback function (and object) to use
5150 * @param int $flags A combination of the following flags:
5151 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
5153 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
5154 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
5155 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
5156 * the arguments, and to control the way they are expanded.
5158 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
5159 * arguments, for instance:
5160 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
5162 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
5163 * future versions. Please call $frame->expand() on it anyway so that your code keeps
5164 * working if/when this is changed.
5166 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
5169 * Please read the documentation in includes/parser/Preprocessor.php for more information
5170 * about the methods available in PPFrame and PPNode.
5172 * @throws MWException
5173 * @return string|callable The old callback function for this name, if any
5175 public function setFunctionHook( $id, $callback, $flags = 0 ) {
5178 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
5179 $this->mFunctionHooks
[$id] = array( $callback, $flags );
5181 # Add to function cache
5182 $mw = MagicWord
::get( $id );
5184 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
5187 $synonyms = $mw->getSynonyms();
5188 $sensitive = intval( $mw->isCaseSensitive() );
5190 foreach ( $synonyms as $syn ) {
5192 if ( !$sensitive ) {
5193 $syn = $wgContLang->lc( $syn );
5196 if ( !( $flags & self
::SFH_NO_HASH
) ) {
5199 # Remove trailing colon
5200 if ( substr( $syn, -1, 1 ) === ':' ) {
5201 $syn = substr( $syn, 0, -1 );
5203 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
5209 * Get all registered function hook identifiers
5213 public function getFunctionHooks() {
5214 return array_keys( $this->mFunctionHooks
);
5218 * Create a tag function, e.g. "<test>some stuff</test>".
5219 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5220 * Unlike parser functions, their content is not preprocessed.
5221 * @param string $tag
5222 * @param callable $callback
5224 * @throws MWException
5227 public function setFunctionTagHook( $tag, $callback, $flags ) {
5228 $tag = strtolower( $tag );
5229 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5230 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5232 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
5233 $this->mFunctionTagHooks
[$tag] : null;
5234 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
5236 if ( !in_array( $tag, $this->mStripList
) ) {
5237 $this->mStripList
[] = $tag;
5244 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
5245 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5246 * Placeholders created in Skin::makeLinkObj()
5248 * @param string $text
5249 * @param int $options
5251 public function replaceLinkHolders( &$text, $options = 0 ) {
5252 $this->mLinkHolders
->replace( $text );
5256 * Replace "<!--LINK-->" link placeholders with plain text of links
5257 * (not HTML-formatted).
5259 * @param string $text
5262 public function replaceLinkHoldersText( $text ) {
5263 return $this->mLinkHolders
->replaceText( $text );
5267 * Renders an image gallery from a text with one line per image.
5268 * text labels may be given by using |-style alternative text. E.g.
5269 * Image:one.jpg|The number "1"
5270 * Image:tree.jpg|A tree
5271 * given as text will return the HTML of a gallery with two images,
5272 * labeled 'The number "1"' and
5275 * @param string $text
5276 * @param array $params
5277 * @return string HTML
5279 public function renderImageGallery( $text, $params ) {
5282 if ( isset( $params['mode'] ) ) {
5283 $mode = $params['mode'];
5287 $ig = ImageGalleryBase
::factory( $mode );
5288 } catch ( Exception
$e ) {
5289 // If invalid type set, fallback to default.
5290 $ig = ImageGalleryBase
::factory( false );
5293 $ig->setContextTitle( $this->mTitle
);
5294 $ig->setShowBytes( false );
5295 $ig->setShowFilename( false );
5296 $ig->setParser( $this );
5297 $ig->setHideBadImages();
5298 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
5300 if ( isset( $params['showfilename'] ) ) {
5301 $ig->setShowFilename( true );
5303 $ig->setShowFilename( false );
5305 if ( isset( $params['caption'] ) ) {
5306 $caption = $params['caption'];
5307 $caption = htmlspecialchars( $caption );
5308 $caption = $this->replaceInternalLinks( $caption );
5309 $ig->setCaptionHtml( $caption );
5311 if ( isset( $params['perrow'] ) ) {
5312 $ig->setPerRow( $params['perrow'] );
5314 if ( isset( $params['widths'] ) ) {
5315 $ig->setWidths( $params['widths'] );
5317 if ( isset( $params['heights'] ) ) {
5318 $ig->setHeights( $params['heights'] );
5320 $ig->setAdditionalOptions( $params );
5322 Hooks
::run( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5324 $lines = StringUtils
::explode( "\n", $text );
5325 foreach ( $lines as $line ) {
5326 # match lines like these:
5327 # Image:someimage.jpg|This is some image
5329 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5331 if ( count( $matches ) == 0 ) {
5335 if ( strpos( $matches[0], '%' ) !== false ) {
5336 $matches[1] = rawurldecode( $matches[1] );
5338 $title = Title
::newFromText( $matches[1], NS_FILE
);
5339 if ( is_null( $title ) ) {
5340 # Bogus title. Ignore these so we don't bomb out later.
5344 # We need to get what handler the file uses, to figure out parameters.
5345 # Note, a hook can overide the file name, and chose an entirely different
5346 # file (which potentially could be of a different type and have different handler).
5349 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5350 array( $this, $title, &$options, &$descQuery ) );
5351 # Don't register it now, as ImageGallery does that later.
5352 $file = $this->fetchFileNoRegister( $title, $options );
5353 $handler = $file ?
$file->getHandler() : false;
5356 'img_alt' => 'gallery-internal-alt',
5357 'img_link' => 'gallery-internal-link',
5360 $paramMap = $paramMap +
$handler->getParamMap();
5361 // We don't want people to specify per-image widths.
5362 // Additionally the width parameter would need special casing anyhow.
5363 unset( $paramMap['img_width'] );
5366 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5371 $handlerOptions = array();
5372 if ( isset( $matches[3] ) ) {
5373 // look for an |alt= definition while trying not to break existing
5374 // captions with multiple pipes (|) in it, until a more sensible grammar
5375 // is defined for images in galleries
5377 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5378 // splitting on '|' is a bit odd, and different from makeImage.
5379 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5380 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
5382 foreach ( $parameterMatches as $parameterMatch ) {
5383 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5385 $paramName = $paramMap[$magicName];
5387 switch ( $paramName ) {
5388 case 'gallery-internal-alt':
5389 $alt = $this->stripAltText( $match, false );
5391 case 'gallery-internal-link':
5392 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5393 $chars = self
::EXT_LINK_URL_CLASS
;
5394 $prots = $this->mUrlProtocols
;
5395 //check to see if link matches an absolute url, if not then it must be a wiki link.
5396 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5399 $localLinkTitle = Title
::newFromText( $linkValue );
5400 if ( $localLinkTitle !== null ) {
5401 $link = $localLinkTitle->getLinkURL();
5406 // Must be a handler specific parameter.
5407 if ( $handler->validateParam( $paramName, $match ) ) {
5408 $handlerOptions[$paramName] = $match;
5410 // Guess not. Append it to the caption.
5411 wfDebug( "$parameterMatch failed parameter validation\n" );
5412 $label .= '|' . $parameterMatch;
5417 // concatenate all other pipes
5418 $label .= '|' . $parameterMatch;
5421 // remove the first pipe
5422 $label = substr( $label, 1 );
5425 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5427 $html = $ig->toHTML();
5428 Hooks
::run( 'AfterParserFetchFileAndTitle', array( $this, $ig, &$html ) );
5433 * @param MediaHandler $handler
5436 public function getImageParams( $handler ) {
5438 $handlerClass = get_class( $handler );
5442 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5443 # Initialise static lists
5444 static $internalParamNames = array(
5445 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5446 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5447 'bottom', 'text-bottom' ),
5448 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5449 'upright', 'border', 'link', 'alt', 'class' ),
5451 static $internalParamMap;
5452 if ( !$internalParamMap ) {
5453 $internalParamMap = array();
5454 foreach ( $internalParamNames as $type => $names ) {
5455 foreach ( $names as $name ) {
5456 $magicName = str_replace( '-', '_', "img_$name" );
5457 $internalParamMap[$magicName] = array( $type, $name );
5462 # Add handler params
5463 $paramMap = $internalParamMap;
5465 $handlerParamMap = $handler->getParamMap();
5466 foreach ( $handlerParamMap as $magic => $paramName ) {
5467 $paramMap[$magic] = array( 'handler', $paramName );
5470 $this->mImageParams
[$handlerClass] = $paramMap;
5471 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5473 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5477 * Parse image options text and use it to make an image
5479 * @param Title $title
5480 * @param string $options
5481 * @param LinkHolderArray|bool $holders
5482 * @return string HTML
5484 public function makeImage( $title, $options, $holders = false ) {
5485 # Check if the options text is of the form "options|alt text"
5487 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5488 # * left no resizing, just left align. label is used for alt= only
5489 # * right same, but right aligned
5490 # * none same, but not aligned
5491 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5492 # * center center the image
5493 # * frame Keep original image size, no magnify-button.
5494 # * framed Same as "frame"
5495 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5496 # * upright reduce width for upright images, rounded to full __0 px
5497 # * border draw a 1px border around the image
5498 # * alt Text for HTML alt attribute (defaults to empty)
5499 # * class Set a class for img node
5500 # * link Set the target of the image link. Can be external, interwiki, or local
5501 # vertical-align values (no % or length right now):
5511 $parts = StringUtils
::explode( "|", $options );
5513 # Give extensions a chance to select the file revision for us
5516 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5517 array( $this, $title, &$options, &$descQuery ) );
5518 # Fetch and register the file (file title may be different via hooks)
5519 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5522 $handler = $file ?
$file->getHandler() : false;
5524 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5527 $this->addTrackingCategory( 'broken-file-category' );
5530 # Process the input parameters
5532 $params = array( 'frame' => array(), 'handler' => array(),
5533 'horizAlign' => array(), 'vertAlign' => array() );
5534 $seenformat = false;
5535 foreach ( $parts as $part ) {
5536 $part = trim( $part );
5537 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5539 if ( isset( $paramMap[$magicName] ) ) {
5540 list( $type, $paramName ) = $paramMap[$magicName];
5542 # Special case; width and height come in one variable together
5543 if ( $type === 'handler' && $paramName === 'width' ) {
5544 $parsedWidthParam = $this->parseWidthParam( $value );
5545 if ( isset( $parsedWidthParam['width'] ) ) {
5546 $width = $parsedWidthParam['width'];
5547 if ( $handler->validateParam( 'width', $width ) ) {
5548 $params[$type]['width'] = $width;
5552 if ( isset( $parsedWidthParam['height'] ) ) {
5553 $height = $parsedWidthParam['height'];
5554 if ( $handler->validateParam( 'height', $height ) ) {
5555 $params[$type]['height'] = $height;
5559 # else no validation -- bug 13436
5561 if ( $type === 'handler' ) {
5562 # Validate handler parameter
5563 $validated = $handler->validateParam( $paramName, $value );
5565 # Validate internal parameters
5566 switch ( $paramName ) {
5570 # @todo FIXME: Possibly check validity here for
5571 # manualthumb? downstream behavior seems odd with
5572 # missing manual thumbs.
5574 $value = $this->stripAltText( $value, $holders );
5577 $chars = self
::EXT_LINK_URL_CLASS
;
5578 $prots = $this->mUrlProtocols
;
5579 if ( $value === '' ) {
5580 $paramName = 'no-link';
5583 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5584 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5585 $paramName = 'link-url';
5586 $this->mOutput
->addExternalLink( $value );
5587 if ( $this->mOptions
->getExternalLinkTarget() ) {
5588 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5593 $linkTitle = Title
::newFromText( $value );
5595 $paramName = 'link-title';
5596 $value = $linkTitle;
5597 $this->mOutput
->addLink( $linkTitle );
5605 // use first appearing option, discard others.
5606 $validated = ! $seenformat;
5610 # Most other things appear to be empty or numeric...
5611 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5616 $params[$type][$paramName] = $value;
5620 if ( !$validated ) {
5625 # Process alignment parameters
5626 if ( $params['horizAlign'] ) {
5627 $params['frame']['align'] = key( $params['horizAlign'] );
5629 if ( $params['vertAlign'] ) {
5630 $params['frame']['valign'] = key( $params['vertAlign'] );
5633 $params['frame']['caption'] = $caption;
5635 # Will the image be presented in a frame, with the caption below?
5636 $imageIsFramed = isset( $params['frame']['frame'] )
5637 ||
isset( $params['frame']['framed'] )
5638 ||
isset( $params['frame']['thumbnail'] )
5639 ||
isset( $params['frame']['manualthumb'] );
5641 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5642 # came to also set the caption, ordinary text after the image -- which
5643 # makes no sense, because that just repeats the text multiple times in
5644 # screen readers. It *also* came to set the title attribute.
5646 # Now that we have an alt attribute, we should not set the alt text to
5647 # equal the caption: that's worse than useless, it just repeats the
5648 # text. This is the framed/thumbnail case. If there's no caption, we
5649 # use the unnamed parameter for alt text as well, just for the time be-
5650 # ing, if the unnamed param is set and the alt param is not.
5652 # For the future, we need to figure out if we want to tweak this more,
5653 # e.g., introducing a title= parameter for the title; ignoring the un-
5654 # named parameter entirely for images without a caption; adding an ex-
5655 # plicit caption= parameter and preserving the old magic unnamed para-
5657 if ( $imageIsFramed ) { # Framed image
5658 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5659 # No caption or alt text, add the filename as the alt text so
5660 # that screen readers at least get some description of the image
5661 $params['frame']['alt'] = $title->getText();
5663 # Do not set $params['frame']['title'] because tooltips don't make sense
5665 } else { # Inline image
5666 if ( !isset( $params['frame']['alt'] ) ) {
5667 # No alt text, use the "caption" for the alt text
5668 if ( $caption !== '' ) {
5669 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5671 # No caption, fall back to using the filename for the
5673 $params['frame']['alt'] = $title->getText();
5676 # Use the "caption" for the tooltip text
5677 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5680 Hooks
::run( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5682 # Linker does the rest
5683 $time = isset( $options['time'] ) ?
$options['time'] : false;
5684 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5685 $time, $descQuery, $this->mOptions
->getThumbSize() );
5687 # Give the handler a chance to modify the parser object
5689 $handler->parserTransformHook( $this, $file );
5696 * @param string $caption
5697 * @param LinkHolderArray|bool $holders
5698 * @return mixed|string
5700 protected function stripAltText( $caption, $holders ) {
5701 # Strip bad stuff out of the title (tooltip). We can't just use
5702 # replaceLinkHoldersText() here, because if this function is called
5703 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5705 $tooltip = $holders->replaceText( $caption );
5707 $tooltip = $this->replaceLinkHoldersText( $caption );
5710 # make sure there are no placeholders in thumbnail attributes
5711 # that are later expanded to html- so expand them now and
5713 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5714 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5720 * Set a flag in the output object indicating that the content is dynamic and
5721 * shouldn't be cached.
5723 public function disableCache() {
5724 wfDebug( "Parser output marked as uncacheable.\n" );
5725 if ( !$this->mOutput
) {
5726 throw new MWException( __METHOD__
.
5727 " can only be called when actually parsing something" );
5729 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5730 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5734 * Callback from the Sanitizer for expanding items found in HTML attribute
5735 * values, so they can be safely tested and escaped.
5737 * @param string $text
5738 * @param bool|PPFrame $frame
5741 public function attributeStripCallback( &$text, $frame = false ) {
5742 $text = $this->replaceVariables( $text, $frame );
5743 $text = $this->mStripState
->unstripBoth( $text );
5752 public function getTags() {
5754 array_keys( $this->mTransparentTagHooks
),
5755 array_keys( $this->mTagHooks
),
5756 array_keys( $this->mFunctionTagHooks
)
5761 * Replace transparent tags in $text with the values given by the callbacks.
5763 * Transparent tag hooks are like regular XML-style tag hooks, except they
5764 * operate late in the transformation sequence, on HTML instead of wikitext.
5766 * @param string $text
5770 public function replaceTransparentTags( $text ) {
5772 $elements = array_keys( $this->mTransparentTagHooks
);
5773 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5774 $replacements = array();
5776 foreach ( $matches as $marker => $data ) {
5777 list( $element, $content, $params, $tag ) = $data;
5778 $tagName = strtolower( $element );
5779 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5780 $output = call_user_func_array(
5781 $this->mTransparentTagHooks
[$tagName],
5782 array( $content, $params, $this )
5787 $replacements[$marker] = $output;
5789 return strtr( $text, $replacements );
5793 * Break wikitext input into sections, and either pull or replace
5794 * some particular section's text.
5796 * External callers should use the getSection and replaceSection methods.
5798 * @param string $text Page wikitext
5799 * @param string|number $sectionId A section identifier string of the form:
5800 * "<flag1> - <flag2> - ... - <section number>"
5802 * Currently the only recognised flag is "T", which means the target section number
5803 * was derived during a template inclusion parse, in other words this is a template
5804 * section edit link. If no flags are given, it was an ordinary section edit link.
5805 * This flag is required to avoid a section numbering mismatch when a section is
5806 * enclosed by "<includeonly>" (bug 6563).
5808 * The section number 0 pulls the text before the first heading; other numbers will
5809 * pull the given section along with its lower-level subsections. If the section is
5810 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5812 * Section 0 is always considered to exist, even if it only contains the empty
5813 * string. If $text is the empty string and section 0 is replaced, $newText is
5816 * @param string $mode One of "get" or "replace"
5817 * @param string $newText Replacement text for section data.
5818 * @return string For "get", the extracted section text.
5819 * for "replace", the whole page with the section replaced.
5821 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5822 global $wgTitle; # not generally used but removes an ugly failure mode
5824 $magicScopeVariable = $this->lock();
5825 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5827 $frame = $this->getPreprocessor()->newFrame();
5829 # Process section extraction flags
5831 $sectionParts = explode( '-', $sectionId );
5832 $sectionIndex = array_pop( $sectionParts );
5833 foreach ( $sectionParts as $part ) {
5834 if ( $part === 'T' ) {
5835 $flags |
= self
::PTD_FOR_INCLUSION
;
5839 # Check for empty input
5840 if ( strval( $text ) === '' ) {
5841 # Only sections 0 and T-0 exist in an empty document
5842 if ( $sectionIndex == 0 ) {
5843 if ( $mode === 'get' ) {
5849 if ( $mode === 'get' ) {
5857 # Preprocess the text
5858 $root = $this->preprocessToDom( $text, $flags );
5860 # <h> nodes indicate section breaks
5861 # They can only occur at the top level, so we can find them by iterating the root's children
5862 $node = $root->getFirstChild();
5864 # Find the target section
5865 if ( $sectionIndex == 0 ) {
5866 # Section zero doesn't nest, level=big
5867 $targetLevel = 1000;
5870 if ( $node->getName() === 'h' ) {
5871 $bits = $node->splitHeading();
5872 if ( $bits['i'] == $sectionIndex ) {
5873 $targetLevel = $bits['level'];
5877 if ( $mode === 'replace' ) {
5878 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5880 $node = $node->getNextSibling();
5886 if ( $mode === 'get' ) {
5893 # Find the end of the section, including nested sections
5895 if ( $node->getName() === 'h' ) {
5896 $bits = $node->splitHeading();
5897 $curLevel = $bits['level'];
5898 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5902 if ( $mode === 'get' ) {
5903 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5905 $node = $node->getNextSibling();
5908 # Write out the remainder (in replace mode only)
5909 if ( $mode === 'replace' ) {
5910 # Output the replacement text
5911 # Add two newlines on -- trailing whitespace in $newText is conventionally
5912 # stripped by the editor, so we need both newlines to restore the paragraph gap
5913 # Only add trailing whitespace if there is newText
5914 if ( $newText != "" ) {
5915 $outText .= $newText . "\n\n";
5919 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5920 $node = $node->getNextSibling();
5924 if ( is_string( $outText ) ) {
5925 # Re-insert stripped tags
5926 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5933 * This function returns the text of a section, specified by a number ($section).
5934 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5935 * the first section before any such heading (section 0).
5937 * If a section contains subsections, these are also returned.
5939 * @param string $text Text to look in
5940 * @param string|number $sectionId Section identifier as a number or string
5941 * (e.g. 0, 1 or 'T-1').
5942 * @param string $defaultText Default to return if section is not found
5944 * @return string Text of the requested section
5946 public function getSection( $text, $sectionId, $defaultText = '' ) {
5947 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5951 * This function returns $oldtext after the content of the section
5952 * specified by $section has been replaced with $text. If the target
5953 * section does not exist, $oldtext is returned unchanged.
5955 * @param string $oldText Former text of the article
5956 * @param string|number $sectionId Section identifier as a number or string
5957 * (e.g. 0, 1 or 'T-1').
5958 * @param string $newText Replacing text
5960 * @return string Modified text
5962 public function replaceSection( $oldText, $sectionId, $newText ) {
5963 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5967 * Get the ID of the revision we are parsing
5971 public function getRevisionId() {
5972 return $this->mRevisionId
;
5976 * Get the revision object for $this->mRevisionId
5978 * @return Revision|null Either a Revision object or null
5979 * @since 1.23 (public since 1.23)
5981 public function getRevisionObject() {
5982 if ( !is_null( $this->mRevisionObject
) ) {
5983 return $this->mRevisionObject
;
5985 if ( is_null( $this->mRevisionId
) ) {
5989 $rev = call_user_func(
5990 $this->mOptions
->getCurrentRevisionCallback(), $this->getTitle(), $this
5993 # If the parse is for a new revision, then the callback should have
5994 # already been set to force the object and should match mRevisionId.
5995 # If not, try to fetch by mRevisionId for sanity.
5996 if ( $rev && $rev->getId() != $this->mRevisionId
) {
5997 $rev = Revision
::newFromId( $this->mRevisionId
);
6000 $this->mRevisionObject
= $rev;
6002 return $this->mRevisionObject
;
6006 * Get the timestamp associated with the current revision, adjusted for
6007 * the default server-local timestamp
6010 public function getRevisionTimestamp() {
6011 if ( is_null( $this->mRevisionTimestamp
) ) {
6014 $revObject = $this->getRevisionObject();
6015 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
6017 # The cryptic '' timezone parameter tells to use the site-default
6018 # timezone offset instead of the user settings.
6020 # Since this value will be saved into the parser cache, served
6021 # to other users, and potentially even used inside links and such,
6022 # it needs to be consistent for all visitors.
6023 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
6026 return $this->mRevisionTimestamp
;
6030 * Get the name of the user that edited the last revision
6032 * @return string User name
6034 public function getRevisionUser() {
6035 if ( is_null( $this->mRevisionUser
) ) {
6036 $revObject = $this->getRevisionObject();
6038 # if this template is subst: the revision id will be blank,
6039 # so just use the current user's name
6041 $this->mRevisionUser
= $revObject->getUserText();
6042 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6043 $this->mRevisionUser
= $this->getUser()->getName();
6046 return $this->mRevisionUser
;
6050 * Get the size of the revision
6052 * @return int|null Revision size
6054 public function getRevisionSize() {
6055 if ( is_null( $this->mRevisionSize
) ) {
6056 $revObject = $this->getRevisionObject();
6058 # if this variable is subst: the revision id will be blank,
6059 # so just use the parser input size, because the own substituation
6060 # will change the size.
6062 $this->mRevisionSize
= $revObject->getSize();
6063 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6064 $this->mRevisionSize
= $this->mInputSize
;
6067 return $this->mRevisionSize
;
6071 * Mutator for $mDefaultSort
6073 * @param string $sort New value
6075 public function setDefaultSort( $sort ) {
6076 $this->mDefaultSort
= $sort;
6077 $this->mOutput
->setProperty( 'defaultsort', $sort );
6081 * Accessor for $mDefaultSort
6082 * Will use the empty string if none is set.
6084 * This value is treated as a prefix, so the
6085 * empty string is equivalent to sorting by
6090 public function getDefaultSort() {
6091 if ( $this->mDefaultSort
!== false ) {
6092 return $this->mDefaultSort
;
6099 * Accessor for $mDefaultSort
6100 * Unlike getDefaultSort(), will return false if none is set
6102 * @return string|bool
6104 public function getCustomDefaultSort() {
6105 return $this->mDefaultSort
;
6109 * Try to guess the section anchor name based on a wikitext fragment
6110 * presumably extracted from a heading, for example "Header" from
6113 * @param string $text
6117 public function guessSectionNameFromWikiText( $text ) {
6118 # Strip out wikitext links(they break the anchor)
6119 $text = $this->stripSectionName( $text );
6120 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6121 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
6125 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6126 * instead. For use in redirects, since IE6 interprets Redirect: headers
6127 * as something other than UTF-8 (apparently?), resulting in breakage.
6129 * @param string $text The section name
6130 * @return string An anchor
6132 public function guessLegacySectionNameFromWikiText( $text ) {
6133 # Strip out wikitext links(they break the anchor)
6134 $text = $this->stripSectionName( $text );
6135 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6136 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
6140 * Strips a text string of wikitext for use in a section anchor
6142 * Accepts a text string and then removes all wikitext from the
6143 * string and leaves only the resultant text (i.e. the result of
6144 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6145 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6146 * to create valid section anchors by mimicing the output of the
6147 * parser when headings are parsed.
6149 * @param string $text Text string to be stripped of wikitext
6150 * for use in a Section anchor
6151 * @return string Filtered text string
6153 public function stripSectionName( $text ) {
6154 # Strip internal link markup
6155 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6156 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6158 # Strip external link markup
6159 # @todo FIXME: Not tolerant to blank link text
6160 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6161 # on how many empty links there are on the page - need to figure that out.
6162 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6164 # Parse wikitext quotes (italics & bold)
6165 $text = $this->doQuotes( $text );
6168 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
6173 * strip/replaceVariables/unstrip for preprocessor regression testing
6175 * @param string $text
6176 * @param Title $title
6177 * @param ParserOptions $options
6178 * @param int $outputType
6182 public function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
6183 $magicScopeVariable = $this->lock();
6184 $this->startParse( $title, $options, $outputType, true );
6186 $text = $this->replaceVariables( $text );
6187 $text = $this->mStripState
->unstripBoth( $text );
6188 $text = Sanitizer
::removeHTMLtags( $text );
6193 * @param string $text
6194 * @param Title $title
6195 * @param ParserOptions $options
6198 public function testPst( $text, Title
$title, ParserOptions
$options ) {
6199 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6203 * @param string $text
6204 * @param Title $title
6205 * @param ParserOptions $options
6208 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
6209 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
6213 * Call a callback function on all regions of the given text that are not
6214 * inside strip markers, and replace those regions with the return value
6215 * of the callback. For example, with input:
6219 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6220 * two strings will be replaced with the value returned by the callback in
6224 * @param callable $callback
6228 public function markerSkipCallback( $s, $callback ) {
6231 while ( $i < strlen( $s ) ) {
6232 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
6233 if ( $markerStart === false ) {
6234 $out .= call_user_func( $callback, substr( $s, $i ) );
6237 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6238 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6239 if ( $markerEnd === false ) {
6240 $out .= substr( $s, $markerStart );
6243 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6244 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6253 * Remove any strip markers found in the given text.
6255 * @param string $text Input string
6258 public function killMarkers( $text ) {
6259 return $this->mStripState
->killMarkers( $text );
6263 * Save the parser state required to convert the given half-parsed text to
6264 * HTML. "Half-parsed" in this context means the output of
6265 * recursiveTagParse() or internalParse(). This output has strip markers
6266 * from replaceVariables (extensionSubstitution() etc.), and link
6267 * placeholders from replaceLinkHolders().
6269 * Returns an array which can be serialized and stored persistently. This
6270 * array can later be loaded into another parser instance with
6271 * unserializeHalfParsedText(). The text can then be safely incorporated into
6272 * the return value of a parser hook.
6274 * @param string $text
6278 public function serializeHalfParsedText( $text ) {
6281 'version' => self
::HALF_PARSED_VERSION
,
6282 'stripState' => $this->mStripState
->getSubState( $text ),
6283 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6289 * Load the parser state given in the $data array, which is assumed to
6290 * have been generated by serializeHalfParsedText(). The text contents is
6291 * extracted from the array, and its markers are transformed into markers
6292 * appropriate for the current Parser instance. This transformed text is
6293 * returned, and can be safely included in the return value of a parser
6296 * If the $data array has been stored persistently, the caller should first
6297 * check whether it is still valid, by calling isValidHalfParsedText().
6299 * @param array $data Serialized data
6300 * @throws MWException
6303 public function unserializeHalfParsedText( $data ) {
6304 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6305 throw new MWException( __METHOD__
. ': invalid version' );
6308 # First, extract the strip state.
6309 $texts = array( $data['text'] );
6310 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6312 # Now renumber links
6313 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6315 # Should be good to go.
6320 * Returns true if the given array, presumed to be generated by
6321 * serializeHalfParsedText(), is compatible with the current version of the
6324 * @param array $data
6328 public function isValidHalfParsedText( $data ) {
6329 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6333 * Parsed a width param of imagelink like 300px or 200x300px
6335 * @param string $value
6340 public function parseWidthParam( $value ) {
6341 $parsedWidthParam = array();
6342 if ( $value === '' ) {
6343 return $parsedWidthParam;
6346 # (bug 13500) In both cases (width/height and width only),
6347 # permit trailing "px" for backward compatibility.
6348 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6349 $width = intval( $m[1] );
6350 $height = intval( $m[2] );
6351 $parsedWidthParam['width'] = $width;
6352 $parsedWidthParam['height'] = $height;
6353 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6354 $width = intval( $value );
6355 $parsedWidthParam['width'] = $width;
6357 return $parsedWidthParam;
6361 * Lock the current instance of the parser.
6363 * This is meant to stop someone from calling the parser
6364 * recursively and messing up all the strip state.
6366 * @throws MWException If parser is in a parse
6367 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6369 protected function lock() {
6370 if ( $this->mInParse
) {
6371 throw new MWException( "Parser state cleared while parsing. "
6372 . "Did you call Parser::parse recursively?" );
6374 $this->mInParse
= true;
6377 $recursiveCheck = new ScopedCallback( function() use ( $that ) {
6378 $that->mInParse
= false;
6381 return $recursiveCheck;
6385 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6387 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6388 * or if there is more than one <p/> tag in the input HTML.
6390 * @param string $html
6394 public static function stripOuterParagraph( $html ) {
6396 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6397 if ( strpos( $m[1], '</p>' ) === false ) {
6406 * Return this parser if it is not doing anything, otherwise
6407 * get a fresh parser. You can use this method by doing
6408 * $myParser = $wgParser->getFreshParser(), or more simply
6409 * $wgParser->getFreshParser()->parse( ... );
6410 * if you're unsure if $wgParser is safe to use.
6413 * @return Parser A parser object that is not parsing anything
6415 public function getFreshParser() {
6416 global $wgParserConf;
6417 if ( $this->mInParse
) {
6418 return new $wgParserConf['class']( $wgParserConf );