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 # Also available as global constants from Defines.php
83 const SFH_NO_HASH
= 1;
84 const SFH_OBJECT_ARGS
= 2;
86 # Constants needed for external link processing
87 # Everything except bracket, space, or control characters
88 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
89 # as well as U+3000 is IDEOGRAPHIC SPACE for bug 19052
90 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}]';
91 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F\p{Zs}]+)
92 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
94 # State constants for the definition list colon extraction
95 const COLON_STATE_TEXT
= 0;
96 const COLON_STATE_TAG
= 1;
97 const COLON_STATE_TAGSTART
= 2;
98 const COLON_STATE_CLOSETAG
= 3;
99 const COLON_STATE_TAGSLASH
= 4;
100 const COLON_STATE_COMMENT
= 5;
101 const COLON_STATE_COMMENTDASH
= 6;
102 const COLON_STATE_COMMENTDASHDASH
= 7;
104 # Flags for preprocessToDom
105 const PTD_FOR_INCLUSION
= 1;
107 # Allowed values for $this->mOutputType
108 # Parameter to startExternalParse().
109 const OT_HTML
= 1; # like parse()
110 const OT_WIKI
= 2; # like preSaveTransform()
111 const OT_PREPROCESS
= 3; # like preprocess()
113 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
115 # Marker Suffix needs to be accessible staticly.
116 const MARKER_SUFFIX
= "-QINU\x7f";
118 # Markers used for wrapping the table of contents
119 const TOC_START
= '<mw:toc>';
120 const TOC_END
= '</mw:toc>';
123 var $mTagHooks = array();
124 var $mTransparentTagHooks = array();
125 var $mFunctionHooks = array();
126 var $mFunctionSynonyms = array( 0 => array(), 1 => array() );
127 var $mFunctionTagHooks = array();
128 var $mStripList = array();
129 var $mDefaultStripList = array();
130 var $mVarCache = array();
131 var $mImageParams = array();
132 var $mImageParamsMagicArray = array();
133 var $mMarkerIndex = 0;
134 var $mFirstCall = true;
136 # Initialised by initialiseVariables()
139 * @var MagicWordArray
144 * @var MagicWordArray
147 var $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
149 # Cleared with clearState():
154 var $mAutonumber, $mDTopen;
161 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
163 * @var LinkHolderArray
168 var $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
170 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
171 var $mExpensiveFunctionCount; # number of expensive parser function calls
172 var $mShowToc, $mForceTocPosition;
177 var $mUser; # User object; only used when doing pre-save transform
180 # These are variables reset at least once per parse regardless of $clearState
190 var $mTitle; # Title context, used for self-link rendering and similar things
191 var $mOutputType; # Output type, one of the OT_xxx constants
192 var $ot; # Shortcut alias, see setOutputType()
193 var $mRevisionObject; # The revision object of the specified revision ID
194 var $mRevisionId; # ID to display in {{REVISIONID}} tags
195 var $mRevisionTimestamp; # The timestamp of the specified revision ID
196 var $mRevisionUser; # User to display in {{REVISIONUSER}} tag
197 var $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
198 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp
199 var $mInputSize = false; # For {{PAGESIZE}} on current page.
207 * @var array Array with the language name of each language link (i.e. the
208 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
209 * duplicate language links to the ParserOutput.
211 var $mLangLinkLanguages;
214 * @var boolean Recursive call protection.
215 * This variable should be treated as if it were private.
217 public $mInParse = false;
222 public function __construct( $conf = array() ) {
223 $this->mConf
= $conf;
224 $this->mUrlProtocols
= wfUrlProtocols();
225 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
226 self
::EXT_LINK_URL_CLASS
. '+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
227 if ( isset( $conf['preprocessorClass'] ) ) {
228 $this->mPreprocessorClass
= $conf['preprocessorClass'];
229 } elseif ( defined( 'HPHP_VERSION' ) ) {
230 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
231 $this->mPreprocessorClass
= 'Preprocessor_Hash';
232 } elseif ( extension_loaded( 'domxml' ) ) {
233 # PECL extension that conflicts with the core DOM extension (bug 13770)
234 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
235 $this->mPreprocessorClass
= 'Preprocessor_Hash';
236 } elseif ( extension_loaded( 'dom' ) ) {
237 $this->mPreprocessorClass
= 'Preprocessor_DOM';
239 $this->mPreprocessorClass
= 'Preprocessor_Hash';
241 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
245 * Reduce memory usage to reduce the impact of circular references
247 function __destruct() {
248 if ( isset( $this->mLinkHolders
) ) {
249 unset( $this->mLinkHolders
);
251 foreach ( $this as $name => $value ) {
252 unset( $this->$name );
257 * Allow extensions to clean up when the parser is cloned
260 $this->mInParse
= false;
261 wfRunHooks( 'ParserCloned', array( $this ) );
265 * Do various kinds of initialisation on the first call of the parser
267 function firstCallInit() {
268 if ( !$this->mFirstCall
) {
271 $this->mFirstCall
= false;
273 wfProfileIn( __METHOD__
);
275 CoreParserFunctions
::register( $this );
276 CoreTagHooks
::register( $this );
277 $this->initialiseVariables();
279 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
280 wfProfileOut( __METHOD__
);
288 function clearState() {
289 wfProfileIn( __METHOD__
);
290 if ( $this->mFirstCall
) {
291 $this->firstCallInit();
293 $this->mOutput
= new ParserOutput
;
294 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
295 $this->mAutonumber
= 0;
296 $this->mLastSection
= '';
297 $this->mDTopen
= false;
298 $this->mIncludeCount
= array();
299 $this->mArgStack
= false;
300 $this->mInPre
= false;
301 $this->mLinkHolders
= new LinkHolderArray( $this );
303 $this->mRevisionObject
= $this->mRevisionTimestamp
=
304 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
305 $this->mVarCache
= array();
307 $this->mLangLinkLanguages
= array();
310 * Prefix for temporary replacement strings for the multipass parser.
311 * \x07 should never appear in input as it's disallowed in XML.
312 * Using it at the front also gives us a little extra robustness
313 * since it shouldn't match when butted up against identifier-like
316 * Must not consist of all title characters, or else it will change
317 * the behavior of <nowiki> in a link.
319 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
320 $this->mStripState
= new StripState( $this->mUniqPrefix
);
322 # Clear these on every parse, bug 4549
323 $this->mTplRedirCache
= $this->mTplDomCache
= array();
325 $this->mShowToc
= true;
326 $this->mForceTocPosition
= false;
327 $this->mIncludeSizes
= array(
331 $this->mPPNodeCount
= 0;
332 $this->mGeneratedPPNodeCount
= 0;
333 $this->mHighestExpansionDepth
= 0;
334 $this->mDefaultSort
= false;
335 $this->mHeadings
= array();
336 $this->mDoubleUnderscores
= array();
337 $this->mExpensiveFunctionCount
= 0;
340 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
341 $this->mPreprocessor
= null;
344 wfRunHooks( 'ParserClearState', array( &$this ) );
345 wfProfileOut( __METHOD__
);
349 * Convert wikitext to HTML
350 * Do not call this function recursively.
352 * @param string $text text we want to parse
353 * @param Title $title
354 * @param ParserOptions $options
355 * @param bool $linestart
356 * @param bool $clearState
357 * @param int $revid Number to pass in {{REVISIONID}}
358 * @return ParserOutput A ParserOutput
360 public function parse( $text, Title
$title, ParserOptions
$options,
361 $linestart = true, $clearState = true, $revid = null
364 * First pass--just handle <nowiki> sections, pass the rest off
365 * to internalParse() which does all the real work.
368 global $wgUseTidy, $wgAlwaysUseTidy, $wgShowHostnames;
369 $fname = __METHOD__
. '-' . wfGetCaller();
370 wfProfileIn( __METHOD__
);
371 wfProfileIn( $fname );
374 $magicScopeVariable = $this->lock();
377 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
379 $this->mInputSize
= strlen( $text );
380 if ( $this->mOptions
->getEnableLimitReport() ) {
381 $this->mOutput
->resetParseStartTime();
384 # Remove the strip marker tag prefix from the input, if present.
386 $text = str_replace( $this->mUniqPrefix
, '', $text );
389 $oldRevisionId = $this->mRevisionId
;
390 $oldRevisionObject = $this->mRevisionObject
;
391 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
392 $oldRevisionUser = $this->mRevisionUser
;
393 $oldRevisionSize = $this->mRevisionSize
;
394 if ( $revid !== null ) {
395 $this->mRevisionId
= $revid;
396 $this->mRevisionObject
= null;
397 $this->mRevisionTimestamp
= null;
398 $this->mRevisionUser
= null;
399 $this->mRevisionSize
= null;
402 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
404 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
405 $text = $this->internalParse( $text );
406 wfRunHooks( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
408 $text = $this->mStripState
->unstripGeneral( $text );
410 # Clean up special characters, only run once, next-to-last before doBlockLevels
412 # french spaces, last one Guillemet-left
413 # only if there is something before the space
414 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
415 # french spaces, Guillemet-right
416 '/(\\302\\253) /' => '\\1 ',
417 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
419 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
421 $text = $this->doBlockLevels( $text, $linestart );
423 $this->replaceLinkHolders( $text );
426 * The input doesn't get language converted if
428 * b) Content isn't converted
429 * c) It's a conversion table
430 * d) it is an interface message (which is in the user language)
432 if ( !( $options->getDisableContentConversion()
433 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
435 if ( !$this->mOptions
->getInterfaceMessage() ) {
436 # The position of the convert() call should not be changed. it
437 # assumes that the links are all replaced and the only thing left
438 # is the <nowiki> mark.
439 $text = $this->getConverterLanguage()->convert( $text );
444 * A converted title will be provided in the output object if title and
445 * content conversion are enabled, the article text does not contain
446 * a conversion-suppressing double-underscore tag, and no
447 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
448 * automatic link conversion.
450 if ( !( $options->getDisableTitleConversion()
451 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
452 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
453 ||
$this->mOutput
->getDisplayTitle() !== false )
455 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
456 if ( $convruletitle ) {
457 $this->mOutput
->setTitleText( $convruletitle );
459 $titleText = $this->getConverterLanguage()->convertTitle( $title );
460 $this->mOutput
->setTitleText( $titleText );
464 $text = $this->mStripState
->unstripNoWiki( $text );
466 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
468 $text = $this->replaceTransparentTags( $text );
469 $text = $this->mStripState
->unstripGeneral( $text );
471 $text = Sanitizer
::normalizeCharReferences( $text );
473 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
474 $text = MWTidy
::tidy( $text );
476 # attempt to sanitize at least some nesting problems
477 # (bug #2702 and quite a few others)
479 # ''Something [http://www.cool.com cool''] -->
480 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
481 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
482 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
483 # fix up an anchor inside another anchor, only
484 # at least for a single single nested link (bug 3695)
485 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
486 '\\1\\2</a>\\3</a>\\1\\4</a>',
487 # fix div inside inline elements- doBlockLevels won't wrap a line which
488 # contains a div, so fix it up here; replace
489 # div with escaped text
490 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
491 '\\1\\3<div\\5>\\6</div>\\8\\9',
492 # remove empty italic or bold tag pairs, some
493 # introduced by rules above
494 '/<([bi])><\/\\1>/' => '',
497 $text = preg_replace(
498 array_keys( $tidyregs ),
499 array_values( $tidyregs ),
503 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
504 $this->limitationWarn( 'expensive-parserfunction',
505 $this->mExpensiveFunctionCount
,
506 $this->mOptions
->getExpensiveParserFunctionLimit()
510 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
512 # Information on include size limits, for the benefit of users who try to skirt them
513 if ( $this->mOptions
->getEnableLimitReport() ) {
514 $max = $this->mOptions
->getMaxIncludeSize();
516 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
517 if ( $cpuTime !== null ) {
518 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
519 sprintf( "%.3f", $cpuTime )
523 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
524 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
525 sprintf( "%.3f", $wallTime )
528 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
529 array( $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() )
531 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
532 array( $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() )
534 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
535 array( $this->mIncludeSizes
['post-expand'], $max )
537 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
538 array( $this->mIncludeSizes
['arg'], $max )
540 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
541 array( $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() )
543 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
544 array( $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() )
546 wfRunHooks( 'ParserLimitReportPrepare', array( $this, $this->mOutput
) );
548 $limitReport = "NewPP limit report\n";
549 if ( $wgShowHostnames ) {
550 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
552 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
553 if ( wfRunHooks( 'ParserLimitReportFormat',
554 array( $key, &$value, &$limitReport, false, false )
556 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
557 $valueMsg = wfMessage( array( "$key-value-text", "$key-value" ) )
558 ->inLanguage( 'en' )->useDatabase( false );
559 if ( !$valueMsg->exists() ) {
560 $valueMsg = new RawMessage( '$1' );
562 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
563 $valueMsg->params( $value );
564 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
568 // Since we're not really outputting HTML, decode the entities and
569 // then re-encode the things that need hiding inside HTML comments.
570 $limitReport = htmlspecialchars_decode( $limitReport );
571 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
573 // Sanitize for comment. Note '‐' in the replacement is U+2010,
574 // which looks much like the problematic '-'.
575 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&' ), $limitReport );
576 $text .= "\n<!-- \n$limitReport-->\n";
578 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
579 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
580 $this->mTitle
->getPrefixedDBkey() );
583 $this->mOutput
->setText( $text );
585 $this->mRevisionId
= $oldRevisionId;
586 $this->mRevisionObject
= $oldRevisionObject;
587 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
588 $this->mRevisionUser
= $oldRevisionUser;
589 $this->mRevisionSize
= $oldRevisionSize;
590 $this->mInputSize
= false;
591 wfProfileOut( $fname );
592 wfProfileOut( __METHOD__
);
594 return $this->mOutput
;
598 * Recursive parser entry point that can be called from an extension tag
601 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
603 * @param string $text Text extension wants to have parsed
604 * @param bool|PPFrame $frame The frame to use for expanding any template variables
608 function recursiveTagParse( $text, $frame = false ) {
609 wfProfileIn( __METHOD__
);
610 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
611 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
612 $text = $this->internalParse( $text, false, $frame );
613 wfProfileOut( __METHOD__
);
618 * Expand templates and variables in the text, producing valid, static wikitext.
619 * Also removes comments.
620 * Do not call this function recursively.
621 * @param string $text
622 * @param Title $title
623 * @param ParserOptions $options
624 * @param int|null $revid
625 * @param bool|PPFrame $frame
626 * @return mixed|string
628 function preprocess( $text, Title
$title = null, ParserOptions
$options, $revid = null, $frame = false ) {
629 wfProfileIn( __METHOD__
);
630 $magicScopeVariable = $this->lock();
631 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
632 if ( $revid !== null ) {
633 $this->mRevisionId
= $revid;
635 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
636 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
637 $text = $this->replaceVariables( $text, $frame );
638 $text = $this->mStripState
->unstripBoth( $text );
639 wfProfileOut( __METHOD__
);
644 * Recursive parser entry point that can be called from an extension tag
647 * @param string $text Text to be expanded
648 * @param bool|PPFrame $frame The frame to use for expanding any template variables
652 public function recursivePreprocess( $text, $frame = false ) {
653 wfProfileIn( __METHOD__
);
654 $text = $this->replaceVariables( $text, $frame );
655 $text = $this->mStripState
->unstripBoth( $text );
656 wfProfileOut( __METHOD__
);
661 * Process the wikitext for the "?preload=" feature. (bug 5210)
663 * "<noinclude>", "<includeonly>" etc. are parsed as for template
664 * transclusion, comments, templates, arguments, tags hooks and parser
665 * functions are untouched.
667 * @param string $text
668 * @param Title $title
669 * @param ParserOptions $options
670 * @param array $params
673 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = array() ) {
674 $msg = new RawMessage( $text );
675 $text = $msg->params( $params )->plain();
677 # Parser (re)initialisation
678 $magicScopeVariable = $this->lock();
679 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
681 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
682 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
683 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
684 $text = $this->mStripState
->unstripBoth( $text );
689 * Get a random string
693 public static function getRandomString() {
694 return wfRandomString( 16 );
698 * Set the current user.
699 * Should only be used when doing pre-save transform.
701 * @param User|null $user User object or null (to reset)
703 function setUser( $user ) {
704 $this->mUser
= $user;
708 * Accessor for mUniqPrefix.
712 public function uniqPrefix() {
713 if ( !isset( $this->mUniqPrefix
) ) {
714 # @todo FIXME: This is probably *horribly wrong*
715 # LanguageConverter seems to want $wgParser's uniqPrefix, however
716 # if this is called for a parser cache hit, the parser may not
717 # have ever been initialized in the first place.
718 # Not really sure what the heck is supposed to be going on here.
720 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
722 return $this->mUniqPrefix
;
726 * Set the context title
730 function setTitle( $t ) {
732 $t = Title
::newFromText( 'NO TITLE' );
735 if ( $t->hasFragment() ) {
736 # Strip the fragment to avoid various odd effects
737 $this->mTitle
= clone $t;
738 $this->mTitle
->setFragment( '' );
745 * Accessor for the Title object
749 function getTitle() {
750 return $this->mTitle
;
754 * Accessor/mutator for the Title object
756 * @param Title $x Title object or null to just get the current one
759 function Title( $x = null ) {
760 return wfSetVar( $this->mTitle
, $x );
764 * Set the output type
766 * @param int $ot New value
768 function setOutputType( $ot ) {
769 $this->mOutputType
= $ot;
772 'html' => $ot == self
::OT_HTML
,
773 'wiki' => $ot == self
::OT_WIKI
,
774 'pre' => $ot == self
::OT_PREPROCESS
,
775 'plain' => $ot == self
::OT_PLAIN
,
780 * Accessor/mutator for the output type
782 * @param int|null $x New value or null to just get the current one
785 function OutputType( $x = null ) {
786 return wfSetVar( $this->mOutputType
, $x );
790 * Get the ParserOutput object
792 * @return ParserOutput
794 function getOutput() {
795 return $this->mOutput
;
799 * Get the ParserOptions object
801 * @return ParserOptions object
803 function getOptions() {
804 return $this->mOptions
;
808 * Accessor/mutator for the ParserOptions object
810 * @param ParserOptions $x New value or null to just get the current one
811 * @return ParserOptions Current ParserOptions object
813 function Options( $x = null ) {
814 return wfSetVar( $this->mOptions
, $x );
820 function nextLinkID() {
821 return $this->mLinkID++
;
827 function setLinkID( $id ) {
828 $this->mLinkID
= $id;
832 * Get a language object for use in parser functions such as {{FORMATNUM:}}
835 function getFunctionLang() {
836 return $this->getTargetLanguage();
840 * Get the target language for the content being parsed. This is usually the
841 * language that the content is in.
845 * @throws MWException
846 * @return Language|null
848 public function getTargetLanguage() {
849 $target = $this->mOptions
->getTargetLanguage();
851 if ( $target !== null ) {
853 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
854 return $this->mOptions
->getUserLangObj();
855 } elseif ( is_null( $this->mTitle
) ) {
856 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
859 return $this->mTitle
->getPageLanguage();
863 * Get the language object for language conversion
864 * @return Language|null
866 function getConverterLanguage() {
867 return $this->getTargetLanguage();
871 * Get a User object either from $this->mUser, if set, or from the
872 * ParserOptions object otherwise
877 if ( !is_null( $this->mUser
) ) {
880 return $this->mOptions
->getUser();
884 * Get a preprocessor object
886 * @return Preprocessor
888 function getPreprocessor() {
889 if ( !isset( $this->mPreprocessor
) ) {
890 $class = $this->mPreprocessorClass
;
891 $this->mPreprocessor
= new $class( $this );
893 return $this->mPreprocessor
;
897 * Replaces all occurrences of HTML-style comments and the given tags
898 * in the text with a random marker and returns the next text. The output
899 * parameter $matches will be an associative array filled with data in
903 * 'UNIQ-xxxxx' => array(
906 * array( 'param' => 'x' ),
907 * '<element param="x">tag content</element>' ) )
910 * @param array $elements List of element names. Comments are always extracted.
911 * @param string $text Source text string.
912 * @param array $matches Out parameter, Array: extracted tags
913 * @param string $uniq_prefix
914 * @return string Stripped text
916 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
921 $taglist = implode( '|', $elements );
922 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
924 while ( $text != '' ) {
925 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
927 if ( count( $p ) < 5 ) {
930 if ( count( $p ) > 5 ) {
944 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
945 $stripped .= $marker;
947 if ( $close === '/>' ) {
948 # Empty element tag, <tag />
953 if ( $element === '!--' ) {
956 $end = "/(<\\/$element\\s*>)/i";
958 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
960 if ( count( $q ) < 3 ) {
961 # No end tag -- let it run out to the end of the text.
970 $matches[$marker] = array( $element,
972 Sanitizer
::decodeTagAttributes( $attributes ),
973 "<$element$attributes$close$content$tail" );
979 * Get a list of strippable XML-like elements
983 function getStripList() {
984 return $this->mStripList
;
988 * Add an item to the strip state
989 * Returns the unique tag which must be inserted into the stripped text
990 * The tag will be replaced with the original text in unstrip()
992 * @param string $text
996 function insertStripItem( $text ) {
997 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
998 $this->mMarkerIndex++
;
999 $this->mStripState
->addGeneral( $rnd, $text );
1004 * parse the wiki syntax used to render tables
1007 * @param string $text
1010 function doTableStuff( $text ) {
1011 wfProfileIn( __METHOD__
);
1013 $lines = StringUtils
::explode( "\n", $text );
1015 $td_history = array(); # Is currently a td tag open?
1016 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
1017 $tr_history = array(); # Is currently a tr tag open?
1018 $tr_attributes = array(); # history of tr attributes
1019 $has_opened_tr = array(); # Did this table open a <tr> element?
1020 $indent_level = 0; # indent level of the table
1022 foreach ( $lines as $outLine ) {
1023 $line = trim( $outLine );
1025 if ( $line === '' ) { # empty line, go to next line
1026 $out .= $outLine . "\n";
1030 $first_character = $line[0];
1033 if ( preg_match( '/^(:*)\{\|(.*)$/', $line, $matches ) ) {
1034 # First check if we are starting a new table
1035 $indent_level = strlen( $matches[1] );
1037 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1038 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1040 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1041 array_push( $td_history, false );
1042 array_push( $last_tag_history, '' );
1043 array_push( $tr_history, false );
1044 array_push( $tr_attributes, '' );
1045 array_push( $has_opened_tr, false );
1046 } elseif ( count( $td_history ) == 0 ) {
1047 # Don't do any of the following
1048 $out .= $outLine . "\n";
1050 } elseif ( substr( $line, 0, 2 ) === '|}' ) {
1051 # We are ending a table
1052 $line = '</table>' . substr( $line, 2 );
1053 $last_tag = array_pop( $last_tag_history );
1055 if ( !array_pop( $has_opened_tr ) ) {
1056 $line = "<tr><td></td></tr>{$line}";
1059 if ( array_pop( $tr_history ) ) {
1060 $line = "</tr>{$line}";
1063 if ( array_pop( $td_history ) ) {
1064 $line = "</{$last_tag}>{$line}";
1066 array_pop( $tr_attributes );
1067 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
1068 } elseif ( substr( $line, 0, 2 ) === '|-' ) {
1069 # Now we have a table row
1070 $line = preg_replace( '#^\|-+#', '', $line );
1072 # Whats after the tag is now only attributes
1073 $attributes = $this->mStripState
->unstripBoth( $line );
1074 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1075 array_pop( $tr_attributes );
1076 array_push( $tr_attributes, $attributes );
1079 $last_tag = array_pop( $last_tag_history );
1080 array_pop( $has_opened_tr );
1081 array_push( $has_opened_tr, true );
1083 if ( array_pop( $tr_history ) ) {
1087 if ( array_pop( $td_history ) ) {
1088 $line = "</{$last_tag}>{$line}";
1092 array_push( $tr_history, false );
1093 array_push( $td_history, false );
1094 array_push( $last_tag_history, '' );
1095 } elseif ( $first_character === '|'
1096 ||
$first_character === '!'
1097 ||
substr( $line, 0, 2 ) === '|+'
1099 # This might be cell elements, td, th or captions
1100 if ( substr( $line, 0, 2 ) === '|+' ) {
1101 $first_character = '+';
1102 $line = substr( $line, 1 );
1105 $line = substr( $line, 1 );
1107 if ( $first_character === '!' ) {
1108 $line = str_replace( '!!', '||', $line );
1111 # Split up multiple cells on the same line.
1112 # FIXME : This can result in improper nesting of tags processed
1113 # by earlier parser steps, but should avoid splitting up eg
1114 # attribute values containing literal "||".
1115 $cells = StringUtils
::explodeMarkup( '||', $line );
1119 # Loop through each table cell
1120 foreach ( $cells as $cell ) {
1122 if ( $first_character !== '+' ) {
1123 $tr_after = array_pop( $tr_attributes );
1124 if ( !array_pop( $tr_history ) ) {
1125 $previous = "<tr{$tr_after}>\n";
1127 array_push( $tr_history, true );
1128 array_push( $tr_attributes, '' );
1129 array_pop( $has_opened_tr );
1130 array_push( $has_opened_tr, true );
1133 $last_tag = array_pop( $last_tag_history );
1135 if ( array_pop( $td_history ) ) {
1136 $previous = "</{$last_tag}>\n{$previous}";
1139 if ( $first_character === '|' ) {
1141 } elseif ( $first_character === '!' ) {
1143 } elseif ( $first_character === '+' ) {
1144 $last_tag = 'caption';
1149 array_push( $last_tag_history, $last_tag );
1151 # A cell could contain both parameters and data
1152 $cell_data = explode( '|', $cell, 2 );
1154 # Bug 553: Note that a '|' inside an invalid link should not
1155 # be mistaken as delimiting cell parameters
1156 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1157 $cell = "{$previous}<{$last_tag}>{$cell}";
1158 } elseif ( count( $cell_data ) == 1 ) {
1159 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1161 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1162 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1163 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1167 array_push( $td_history, true );
1170 $out .= $outLine . "\n";
1173 # Closing open td, tr && table
1174 while ( count( $td_history ) > 0 ) {
1175 if ( array_pop( $td_history ) ) {
1178 if ( array_pop( $tr_history ) ) {
1181 if ( !array_pop( $has_opened_tr ) ) {
1182 $out .= "<tr><td></td></tr>\n";
1185 $out .= "</table>\n";
1188 # Remove trailing line-ending (b/c)
1189 if ( substr( $out, -1 ) === "\n" ) {
1190 $out = substr( $out, 0, -1 );
1193 # special case: don't return empty table
1194 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1198 wfProfileOut( __METHOD__
);
1204 * Helper function for parse() that transforms wiki markup into
1205 * HTML. Only called for $mOutputType == self::OT_HTML.
1209 * @param string $text
1210 * @param bool $isMain
1211 * @param bool $frame
1215 function internalParse( $text, $isMain = true, $frame = false ) {
1216 wfProfileIn( __METHOD__
);
1220 # Hook to suspend the parser in this state
1221 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1222 wfProfileOut( __METHOD__
);
1226 # if $frame is provided, then use $frame for replacing any variables
1228 # use frame depth to infer how include/noinclude tags should be handled
1229 # depth=0 means this is the top-level document; otherwise it's an included document
1230 if ( !$frame->depth
) {
1233 $flag = Parser
::PTD_FOR_INCLUSION
;
1235 $dom = $this->preprocessToDom( $text, $flag );
1236 $text = $frame->expand( $dom );
1238 # if $frame is not provided, then use old-style replaceVariables
1239 $text = $this->replaceVariables( $text );
1242 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1243 $text = Sanitizer
::removeHTMLtags(
1245 array( &$this, 'attributeStripCallback' ),
1247 array_keys( $this->mTransparentTagHooks
)
1249 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1251 # Tables need to come after variable replacement for things to work
1252 # properly; putting them before other transformations should keep
1253 # exciting things like link expansions from showing up in surprising
1255 $text = $this->doTableStuff( $text );
1257 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1259 $text = $this->doDoubleUnderscore( $text );
1261 $text = $this->doHeadings( $text );
1262 $text = $this->replaceInternalLinks( $text );
1263 $text = $this->doAllQuotes( $text );
1264 $text = $this->replaceExternalLinks( $text );
1266 # replaceInternalLinks may sometimes leave behind
1267 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1268 $text = str_replace( $this->mUniqPrefix
. 'NOPARSE', '', $text );
1270 $text = $this->doMagicLinks( $text );
1271 $text = $this->formatHeadings( $text, $origText, $isMain );
1273 wfProfileOut( __METHOD__
);
1278 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1279 * magic external links.
1284 * @param string $text
1288 function doMagicLinks( $text ) {
1289 wfProfileIn( __METHOD__
);
1290 $prots = wfUrlProtocolsWithoutProtRel();
1291 $urlChar = self
::EXT_LINK_URL_CLASS
;
1292 $text = preg_replace_callback(
1294 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1295 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1296 (\\b(?i:$prots)$urlChar+) | # m[3]: Free external links" . '
1297 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1298 ISBN\s+(\b # m[5]: ISBN, capture number
1299 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1300 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1301 [0-9Xx] # check digit
1303 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1304 wfProfileOut( __METHOD__
);
1309 * @throws MWException
1311 * @return HTML|string
1313 function magicLinkCallback( $m ) {
1314 if ( isset( $m[1] ) && $m[1] !== '' ) {
1317 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1320 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1321 # Free external link
1322 return $this->makeFreeExternalLink( $m[0] );
1323 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1325 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1328 $cssClass = 'mw-magiclink-rfc';
1330 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1332 $urlmsg = 'pubmedurl';
1333 $cssClass = 'mw-magiclink-pmid';
1336 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1337 substr( $m[0], 0, 20 ) . '"' );
1339 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1340 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass );
1341 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1344 $num = strtr( $isbn, array(
1349 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1350 return '<a href="' .
1351 htmlspecialchars( $titleObj->getLocalURL() ) .
1352 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1359 * Make a free external link, given a user-supplied URL
1361 * @param string $url
1363 * @return string HTML
1366 function makeFreeExternalLink( $url ) {
1367 wfProfileIn( __METHOD__
);
1371 # The characters '<' and '>' (which were escaped by
1372 # removeHTMLtags()) should not be included in
1373 # URLs, per RFC 2396.
1375 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1376 $trail = substr( $url, $m2[0][1] ) . $trail;
1377 $url = substr( $url, 0, $m2[0][1] );
1380 # Move trailing punctuation to $trail
1382 # If there is no left bracket, then consider right brackets fair game too
1383 if ( strpos( $url, '(' ) === false ) {
1387 $numSepChars = strspn( strrev( $url ), $sep );
1388 if ( $numSepChars ) {
1389 $trail = substr( $url, -$numSepChars ) . $trail;
1390 $url = substr( $url, 0, -$numSepChars );
1393 $url = Sanitizer
::cleanUrl( $url );
1395 # Is this an external image?
1396 $text = $this->maybeMakeExternalImage( $url );
1397 if ( $text === false ) {
1398 # Not an image, make a link
1399 $text = Linker
::makeExternalLink( $url,
1400 $this->getConverterLanguage()->markNoConversion( $url, true ),
1402 $this->getExternalLinkAttribs( $url ) );
1403 # Register it in the output object...
1404 # Replace unnecessary URL escape codes with their equivalent characters
1405 $pasteurized = self
::replaceUnusualEscapes( $url );
1406 $this->mOutput
->addExternalLink( $pasteurized );
1408 wfProfileOut( __METHOD__
);
1409 return $text . $trail;
1413 * Parse headers and return html
1417 * @param string $text
1421 function doHeadings( $text ) {
1422 wfProfileIn( __METHOD__
);
1423 for ( $i = 6; $i >= 1; --$i ) {
1424 $h = str_repeat( '=', $i );
1425 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1427 wfProfileOut( __METHOD__
);
1432 * Replace single quotes with HTML markup
1435 * @param string $text
1437 * @return string the altered text
1439 function doAllQuotes( $text ) {
1440 wfProfileIn( __METHOD__
);
1442 $lines = StringUtils
::explode( "\n", $text );
1443 foreach ( $lines as $line ) {
1444 $outtext .= $this->doQuotes( $line ) . "\n";
1446 $outtext = substr( $outtext, 0, -1 );
1447 wfProfileOut( __METHOD__
);
1452 * Helper function for doAllQuotes()
1454 * @param string $text
1458 public function doQuotes( $text ) {
1459 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1460 $countarr = count( $arr );
1461 if ( $countarr == 1 ) {
1465 // First, do some preliminary work. This may shift some apostrophes from
1466 // being mark-up to being text. It also counts the number of occurrences
1467 // of bold and italics mark-ups.
1470 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1471 $thislen = strlen( $arr[$i] );
1472 // If there are ever four apostrophes, assume the first is supposed to
1473 // be text, and the remaining three constitute mark-up for bold text.
1474 // (bug 13227: ''''foo'''' turns into ' ''' foo ' ''')
1475 if ( $thislen == 4 ) {
1476 $arr[$i - 1] .= "'";
1479 } elseif ( $thislen > 5 ) {
1480 // If there are more than 5 apostrophes in a row, assume they're all
1481 // text except for the last 5.
1482 // (bug 13227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1483 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1487 // Count the number of occurrences of bold and italics mark-ups.
1488 if ( $thislen == 2 ) {
1490 } elseif ( $thislen == 3 ) {
1492 } elseif ( $thislen == 5 ) {
1498 // If there is an odd number of both bold and italics, it is likely
1499 // that one of the bold ones was meant to be an apostrophe followed
1500 // by italics. Which one we cannot know for certain, but it is more
1501 // likely to be one that has a single-letter word before it.
1502 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1503 $firstsingleletterword = -1;
1504 $firstmultiletterword = -1;
1506 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1507 if ( strlen( $arr[$i] ) == 3 ) {
1508 $x1 = substr( $arr[$i - 1], -1 );
1509 $x2 = substr( $arr[$i - 1], -2, 1 );
1510 if ( $x1 === ' ' ) {
1511 if ( $firstspace == -1 ) {
1514 } elseif ( $x2 === ' ' ) {
1515 if ( $firstsingleletterword == -1 ) {
1516 $firstsingleletterword = $i;
1517 // if $firstsingleletterword is set, we don't
1518 // look at the other options, so we can bail early.
1522 if ( $firstmultiletterword == -1 ) {
1523 $firstmultiletterword = $i;
1529 // If there is a single-letter word, use it!
1530 if ( $firstsingleletterword > -1 ) {
1531 $arr[$firstsingleletterword] = "''";
1532 $arr[$firstsingleletterword - 1] .= "'";
1533 } elseif ( $firstmultiletterword > -1 ) {
1534 // If not, but there's a multi-letter word, use that one.
1535 $arr[$firstmultiletterword] = "''";
1536 $arr[$firstmultiletterword - 1] .= "'";
1537 } elseif ( $firstspace > -1 ) {
1538 // ... otherwise use the first one that has neither.
1539 // (notice that it is possible for all three to be -1 if, for example,
1540 // there is only one pentuple-apostrophe in the line)
1541 $arr[$firstspace] = "''";
1542 $arr[$firstspace - 1] .= "'";
1546 // Now let's actually convert our apostrophic mush to HTML!
1551 foreach ( $arr as $r ) {
1552 if ( ( $i %
2 ) == 0 ) {
1553 if ( $state === 'both' ) {
1559 $thislen = strlen( $r );
1560 if ( $thislen == 2 ) {
1561 if ( $state === 'i' ) {
1564 } elseif ( $state === 'bi' ) {
1567 } elseif ( $state === 'ib' ) {
1568 $output .= '</b></i><b>';
1570 } elseif ( $state === 'both' ) {
1571 $output .= '<b><i>' . $buffer . '</i>';
1573 } else { // $state can be 'b' or ''
1577 } elseif ( $thislen == 3 ) {
1578 if ( $state === 'b' ) {
1581 } elseif ( $state === 'bi' ) {
1582 $output .= '</i></b><i>';
1584 } elseif ( $state === 'ib' ) {
1587 } elseif ( $state === 'both' ) {
1588 $output .= '<i><b>' . $buffer . '</b>';
1590 } else { // $state can be 'i' or ''
1594 } elseif ( $thislen == 5 ) {
1595 if ( $state === 'b' ) {
1596 $output .= '</b><i>';
1598 } elseif ( $state === 'i' ) {
1599 $output .= '</i><b>';
1601 } elseif ( $state === 'bi' ) {
1602 $output .= '</i></b>';
1604 } elseif ( $state === 'ib' ) {
1605 $output .= '</b></i>';
1607 } elseif ( $state === 'both' ) {
1608 $output .= '<i><b>' . $buffer . '</b></i>';
1610 } else { // ($state == '')
1618 // Now close all remaining tags. Notice that the order is important.
1619 if ( $state === 'b' ||
$state === 'ib' ) {
1622 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1625 if ( $state === 'bi' ) {
1628 // There might be lonely ''''', so make sure we have a buffer
1629 if ( $state === 'both' && $buffer ) {
1630 $output .= '<b><i>' . $buffer . '</i></b>';
1636 * Replace external links (REL)
1638 * Note: this is all very hackish and the order of execution matters a lot.
1639 * Make sure to run tests/parserTests.php if you change this code.
1643 * @param string $text
1645 * @throws MWException
1648 function replaceExternalLinks( $text ) {
1649 wfProfileIn( __METHOD__
);
1651 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1652 if ( $bits === false ) {
1653 wfProfileOut( __METHOD__
);
1654 throw new MWException( "PCRE needs to be compiled with "
1655 . "--enable-unicode-properties in order for MediaWiki to function" );
1657 $s = array_shift( $bits );
1660 while ( $i < count( $bits ) ) {
1663 $text = $bits[$i++
];
1664 $trail = $bits[$i++
];
1666 # The characters '<' and '>' (which were escaped by
1667 # removeHTMLtags()) should not be included in
1668 # URLs, per RFC 2396.
1670 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1671 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1672 $url = substr( $url, 0, $m2[0][1] );
1675 # If the link text is an image URL, replace it with an <img> tag
1676 # This happened by accident in the original parser, but some people used it extensively
1677 $img = $this->maybeMakeExternalImage( $text );
1678 if ( $img !== false ) {
1684 # Set linktype for CSS - if URL==text, link is essentially free
1685 $linktype = ( $text === $url ) ?
'free' : 'text';
1687 # No link text, e.g. [http://domain.tld/some.link]
1688 if ( $text == '' ) {
1690 $langObj = $this->getTargetLanguage();
1691 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1692 $linktype = 'autonumber';
1694 # Have link text, e.g. [http://domain.tld/some.link text]s
1696 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1699 $text = $this->getConverterLanguage()->markNoConversion( $text );
1701 $url = Sanitizer
::cleanUrl( $url );
1703 # Use the encoded URL
1704 # This means that users can paste URLs directly into the text
1705 # Funny characters like ö aren't valid in URLs anyway
1706 # This was changed in August 2004
1707 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1708 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1710 # Register link in the output object.
1711 # Replace unnecessary URL escape codes with the referenced character
1712 # This prevents spammers from hiding links from the filters
1713 $pasteurized = self
::replaceUnusualEscapes( $url );
1714 $this->mOutput
->addExternalLink( $pasteurized );
1717 wfProfileOut( __METHOD__
);
1722 * Get the rel attribute for a particular external link.
1725 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1726 * nofollow if appropriate
1727 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1728 * @return string|null Rel attribute for $url
1730 public static function getExternalLinkRel( $url = false, $title = null ) {
1731 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1732 $ns = $title ?
$title->getNamespace() : false;
1733 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1734 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1742 * Get an associative array of additional HTML attributes appropriate for a
1743 * particular external link. This currently may include rel => nofollow
1744 * (depending on configuration, namespace, and the URL's domain) and/or a
1745 * target attribute (depending on configuration).
1747 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1748 * nofollow if appropriate
1749 * @return array Associative array of HTML attributes
1751 function getExternalLinkAttribs( $url = false ) {
1753 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1755 if ( $this->mOptions
->getExternalLinkTarget() ) {
1756 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1762 * Replace unusual URL escape codes with their equivalent characters
1764 * @param string $url
1767 * @todo This can merge genuinely required bits in the path or query string,
1768 * breaking legit URLs. A proper fix would treat the various parts of
1769 * the URL differently; as a workaround, just use the output for
1770 * statistical records, not for actual linking/output.
1772 static function replaceUnusualEscapes( $url ) {
1773 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1774 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1778 * Callback function used in replaceUnusualEscapes().
1779 * Replaces unusual URL escape codes with their equivalent character
1781 * @param array $matches
1785 private static function replaceUnusualEscapesCallback( $matches ) {
1786 $char = urldecode( $matches[0] );
1787 $ord = ord( $char );
1788 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1789 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1790 # No, shouldn't be escaped
1793 # Yes, leave it escaped
1799 * make an image if it's allowed, either through the global
1800 * option, through the exception, or through the on-wiki whitelist
1802 * @param string $url
1806 private function maybeMakeExternalImage( $url ) {
1807 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1808 $imagesexception = !empty( $imagesfrom );
1810 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1811 if ( $imagesexception && is_array( $imagesfrom ) ) {
1812 $imagematch = false;
1813 foreach ( $imagesfrom as $match ) {
1814 if ( strpos( $url, $match ) === 0 ) {
1819 } elseif ( $imagesexception ) {
1820 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1822 $imagematch = false;
1825 if ( $this->mOptions
->getAllowExternalImages()
1826 ||
( $imagesexception && $imagematch )
1828 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1830 $text = Linker
::makeExternalImage( $url );
1833 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1834 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
1836 $whitelist = explode(
1838 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
1841 foreach ( $whitelist as $entry ) {
1842 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1843 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1846 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1847 # Image matches a whitelist entry
1848 $text = Linker
::makeExternalImage( $url );
1857 * Process [[ ]] wikilinks
1861 * @return string Processed text
1865 function replaceInternalLinks( $s ) {
1866 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1871 * Process [[ ]] wikilinks (RIL)
1873 * @throws MWException
1874 * @return LinkHolderArray
1878 function replaceInternalLinks2( &$s ) {
1879 global $wgExtraInterlanguageLinkPrefixes;
1880 wfProfileIn( __METHOD__
);
1882 wfProfileIn( __METHOD__
. '-setup' );
1883 static $tc = false, $e1, $e1_img;
1884 # the % is needed to support urlencoded titles as well
1886 $tc = Title
::legalChars() . '#%';
1887 # Match a link having the form [[namespace:link|alternate]]trail
1888 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1889 # Match cases where there is no "]]", which might still be images
1890 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1893 $holders = new LinkHolderArray( $this );
1895 # split the entire text string on occurrences of [[
1896 $a = StringUtils
::explode( '[[', ' ' . $s );
1897 # get the first element (all text up to first [[), and remove the space we added
1900 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1901 $s = substr( $s, 1 );
1903 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1905 if ( $useLinkPrefixExtension ) {
1906 # Match the end of a line for a word that's not followed by whitespace,
1907 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1909 $charset = $wgContLang->linkPrefixCharset();
1910 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
1913 if ( is_null( $this->mTitle
) ) {
1914 wfProfileOut( __METHOD__
. '-setup' );
1915 wfProfileOut( __METHOD__
);
1916 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
1918 $nottalk = !$this->mTitle
->isTalkPage();
1920 if ( $useLinkPrefixExtension ) {
1922 if ( preg_match( $e2, $s, $m ) ) {
1923 $first_prefix = $m[2];
1925 $first_prefix = false;
1931 $useSubpages = $this->areSubpagesAllowed();
1932 wfProfileOut( __METHOD__
. '-setup' );
1934 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
1935 # Loop for each link
1936 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
1937 // @codingStandardsIgnoreStart
1939 # Check for excessive memory usage
1940 if ( $holders->isBig() ) {
1942 # Do the existence check, replace the link holders and clear the array
1943 $holders->replace( $s );
1947 if ( $useLinkPrefixExtension ) {
1948 wfProfileIn( __METHOD__
. '-prefixhandling' );
1949 if ( preg_match( $e2, $s, $m ) ) {
1956 if ( $first_prefix ) {
1957 $prefix = $first_prefix;
1958 $first_prefix = false;
1960 wfProfileOut( __METHOD__
. '-prefixhandling' );
1963 $might_be_img = false;
1965 wfProfileIn( __METHOD__
. "-e1" );
1966 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1968 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1969 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1970 # the real problem is with the $e1 regex
1973 # Still some problems for cases where the ] is meant to be outside punctuation,
1974 # and no image is in sight. See bug 2095.
1977 && substr( $m[3], 0, 1 ) === ']'
1978 && strpos( $text, '[' ) !== false
1980 $text .= ']'; # so that replaceExternalLinks($text) works later
1981 $m[3] = substr( $m[3], 1 );
1983 # fix up urlencoded title texts
1984 if ( strpos( $m[1], '%' ) !== false ) {
1985 # Should anchors '#' also be rejected?
1986 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) );
1989 } elseif ( preg_match( $e1_img, $line, $m ) ) {
1990 # Invalid, but might be an image with a link in its caption
1991 $might_be_img = true;
1993 if ( strpos( $m[1], '%' ) !== false ) {
1994 $m[1] = rawurldecode( $m[1] );
1997 } else { # Invalid form; output directly
1998 $s .= $prefix . '[[' . $line;
1999 wfProfileOut( __METHOD__
. "-e1" );
2002 wfProfileOut( __METHOD__
. "-e1" );
2003 wfProfileIn( __METHOD__
. "-misc" );
2005 # Don't allow internal links to pages containing
2006 # PROTO: where PROTO is a valid URL protocol; these
2007 # should be external links.
2008 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $m[1] ) ) {
2009 $s .= $prefix . '[[' . $line;
2010 wfProfileOut( __METHOD__
. "-misc" );
2014 # Make subpage if necessary
2015 if ( $useSubpages ) {
2016 $link = $this->maybeDoSubpageLink( $m[1], $text );
2021 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
2023 # Strip off leading ':'
2024 $link = substr( $link, 1 );
2027 wfProfileOut( __METHOD__
. "-misc" );
2028 wfProfileIn( __METHOD__
. "-title" );
2029 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
2030 if ( $nt === null ) {
2031 $s .= $prefix . '[[' . $line;
2032 wfProfileOut( __METHOD__
. "-title" );
2036 $ns = $nt->getNamespace();
2037 $iw = $nt->getInterwiki();
2038 wfProfileOut( __METHOD__
. "-title" );
2040 if ( $might_be_img ) { # if this is actually an invalid link
2041 wfProfileIn( __METHOD__
. "-might_be_img" );
2042 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2045 # look at the next 'line' to see if we can close it there
2047 $next_line = $a->current();
2048 if ( $next_line === false ||
$next_line === null ) {
2051 $m = explode( ']]', $next_line, 3 );
2052 if ( count( $m ) == 3 ) {
2053 # the first ]] closes the inner link, the second the image
2055 $text .= "[[{$m[0]}]]{$m[1]}";
2058 } elseif ( count( $m ) == 2 ) {
2059 # if there's exactly one ]] that's fine, we'll keep looking
2060 $text .= "[[{$m[0]}]]{$m[1]}";
2062 # if $next_line is invalid too, we need look no further
2063 $text .= '[[' . $next_line;
2068 # we couldn't find the end of this imageLink, so output it raw
2069 # but don't ignore what might be perfectly normal links in the text we've examined
2070 $holders->merge( $this->replaceInternalLinks2( $text ) );
2071 $s .= "{$prefix}[[$link|$text";
2072 # note: no $trail, because without an end, there *is* no trail
2073 wfProfileOut( __METHOD__
. "-might_be_img" );
2076 } else { # it's not an image, so output it raw
2077 $s .= "{$prefix}[[$link|$text";
2078 # note: no $trail, because without an end, there *is* no trail
2079 wfProfileOut( __METHOD__
. "-might_be_img" );
2082 wfProfileOut( __METHOD__
. "-might_be_img" );
2085 $wasblank = ( $text == '' );
2089 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
2090 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2091 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2092 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2093 $text = $this->doQuotes( $text );
2096 # Link not escaped by : , create the various objects
2099 wfProfileIn( __METHOD__
. "-interwiki" );
2101 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2102 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2103 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2106 # Bug 24502: filter duplicates
2107 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2108 $this->mLangLinkLanguages
[$iw] = true;
2109 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2112 $s = rtrim( $s . $prefix );
2113 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2114 wfProfileOut( __METHOD__
. "-interwiki" );
2117 wfProfileOut( __METHOD__
. "-interwiki" );
2119 if ( $ns == NS_FILE
) {
2120 wfProfileIn( __METHOD__
. "-image" );
2121 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2123 # if no parameters were passed, $text
2124 # becomes something like "File:Foo.png",
2125 # which we don't want to pass on to the
2129 # recursively parse links inside the image caption
2130 # actually, this will parse them in any other parameters, too,
2131 # but it might be hard to fix that, and it doesn't matter ATM
2132 $text = $this->replaceExternalLinks( $text );
2133 $holders->merge( $this->replaceInternalLinks2( $text ) );
2135 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2136 $s .= $prefix . $this->armorLinks(
2137 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2139 $s .= $prefix . $trail;
2141 wfProfileOut( __METHOD__
. "-image" );
2145 if ( $ns == NS_CATEGORY
) {
2146 wfProfileIn( __METHOD__
. "-category" );
2147 $s = rtrim( $s . "\n" ); # bug 87
2150 $sortkey = $this->getDefaultSort();
2154 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2155 $sortkey = str_replace( "\n", '', $sortkey );
2156 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2157 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2160 * Strip the whitespace Category links produce, see bug 87
2162 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2164 wfProfileOut( __METHOD__
. "-category" );
2169 # Self-link checking. For some languages, variants of the title are checked in
2170 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2171 # for linking to a different variant.
2172 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2173 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2177 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2178 # @todo FIXME: Should do batch file existence checks, see comment below
2179 if ( $ns == NS_MEDIA
) {
2180 wfProfileIn( __METHOD__
. "-media" );
2181 # Give extensions a chance to select the file revision for us
2184 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2185 array( $this, $nt, &$options, &$descQuery ) );
2186 # Fetch and register the file (file title may be different via hooks)
2187 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2188 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2189 $s .= $prefix . $this->armorLinks(
2190 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2191 wfProfileOut( __METHOD__
. "-media" );
2195 wfProfileIn( __METHOD__
. "-always_known" );
2196 # Some titles, such as valid special pages or files in foreign repos, should
2197 # be shown as bluelinks even though they're not included in the page table
2199 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2200 # batch file existence checks for NS_FILE and NS_MEDIA
2201 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2202 $this->mOutput
->addLink( $nt );
2203 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2205 # Links will be added to the output link list after checking
2206 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2208 wfProfileOut( __METHOD__
. "-always_known" );
2210 wfProfileOut( __METHOD__
);
2215 * Render a forced-blue link inline; protect against double expansion of
2216 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2217 * Since this little disaster has to split off the trail text to avoid
2218 * breaking URLs in the following text without breaking trails on the
2219 * wiki links, it's been made into a horrible function.
2222 * @param string $text
2223 * @param array|string $query
2224 * @param string $trail
2225 * @param string $prefix
2226 * @return string HTML-wikitext mix oh yuck
2228 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2229 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2231 if ( is_string( $query ) ) {
2232 $query = wfCgiToArray( $query );
2234 if ( $text == '' ) {
2235 $text = htmlspecialchars( $nt->getPrefixedText() );
2238 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2240 return $this->armorLinks( $link ) . $trail;
2244 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2245 * going to go through further parsing steps before inline URL expansion.
2247 * Not needed quite as much as it used to be since free links are a bit
2248 * more sensible these days. But bracketed links are still an issue.
2250 * @param string $text More-or-less HTML
2251 * @return string Less-or-more HTML with NOPARSE bits
2253 function armorLinks( $text ) {
2254 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2255 "{$this->mUniqPrefix}NOPARSE$1", $text );
2259 * Return true if subpage links should be expanded on this page.
2262 function areSubpagesAllowed() {
2263 # Some namespaces don't allow subpages
2264 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2268 * Handle link to subpage if necessary
2270 * @param string $target The source of the link
2271 * @param string &$text The link text, modified as necessary
2272 * @return string The full name of the link
2275 function maybeDoSubpageLink( $target, &$text ) {
2276 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2280 * Used by doBlockLevels()
2285 function closeParagraph() {
2287 if ( $this->mLastSection
!= '' ) {
2288 $result = '</' . $this->mLastSection
. ">\n";
2290 $this->mInPre
= false;
2291 $this->mLastSection
= '';
2296 * getCommon() returns the length of the longest common substring
2297 * of both arguments, starting at the beginning of both.
2300 * @param string $st1
2301 * @param string $st2
2305 function getCommon( $st1, $st2 ) {
2306 $fl = strlen( $st1 );
2307 $shorter = strlen( $st2 );
2308 if ( $fl < $shorter ) {
2312 for ( $i = 0; $i < $shorter; ++
$i ) {
2313 if ( $st1[$i] != $st2[$i] ) {
2321 * These next three functions open, continue, and close the list
2322 * element appropriate to the prefix character passed into them.
2325 * @param string $char
2329 function openList( $char ) {
2330 $result = $this->closeParagraph();
2332 if ( '*' === $char ) {
2333 $result .= "<ul><li>";
2334 } elseif ( '#' === $char ) {
2335 $result .= "<ol><li>";
2336 } elseif ( ':' === $char ) {
2337 $result .= "<dl><dd>";
2338 } elseif ( ';' === $char ) {
2339 $result .= "<dl><dt>";
2340 $this->mDTopen
= true;
2342 $result = '<!-- ERR 1 -->';
2350 * @param string $char
2355 function nextItem( $char ) {
2356 if ( '*' === $char ||
'#' === $char ) {
2357 return "</li>\n<li>";
2358 } elseif ( ':' === $char ||
';' === $char ) {
2360 if ( $this->mDTopen
) {
2363 if ( ';' === $char ) {
2364 $this->mDTopen
= true;
2365 return $close . '<dt>';
2367 $this->mDTopen
= false;
2368 return $close . '<dd>';
2371 return '<!-- ERR 2 -->';
2376 * @param string $char
2381 function closeList( $char ) {
2382 if ( '*' === $char ) {
2383 $text = "</li></ul>";
2384 } elseif ( '#' === $char ) {
2385 $text = "</li></ol>";
2386 } elseif ( ':' === $char ) {
2387 if ( $this->mDTopen
) {
2388 $this->mDTopen
= false;
2389 $text = "</dt></dl>";
2391 $text = "</dd></dl>";
2394 return '<!-- ERR 3 -->';
2401 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2403 * @param string $text
2404 * @param bool $linestart Whether or not this is at the start of a line.
2406 * @return string The lists rendered as HTML
2408 function doBlockLevels( $text, $linestart ) {
2409 wfProfileIn( __METHOD__
);
2411 # Parsing through the text line by line. The main thing
2412 # happening here is handling of block-level elements p, pre,
2413 # and making lists from lines starting with * # : etc.
2415 $textLines = StringUtils
::explode( "\n", $text );
2417 $lastPrefix = $output = '';
2418 $this->mDTopen
= $inBlockElem = false;
2420 $paragraphStack = false;
2421 $inBlockquote = false;
2423 foreach ( $textLines as $oLine ) {
2425 if ( !$linestart ) {
2435 $lastPrefixLength = strlen( $lastPrefix );
2436 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2437 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2438 # If not in a <pre> element, scan for and figure out what prefixes are there.
2439 if ( !$this->mInPre
) {
2440 # Multiple prefixes may abut each other for nested lists.
2441 $prefixLength = strspn( $oLine, '*#:;' );
2442 $prefix = substr( $oLine, 0, $prefixLength );
2445 # ; and : are both from definition-lists, so they're equivalent
2446 # for the purposes of determining whether or not we need to open/close
2448 $prefix2 = str_replace( ';', ':', $prefix );
2449 $t = substr( $oLine, $prefixLength );
2450 $this->mInPre
= (bool)$preOpenMatch;
2452 # Don't interpret any other prefixes in preformatted text
2454 $prefix = $prefix2 = '';
2459 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2460 # Same as the last item, so no need to deal with nesting or opening stuff
2461 $output .= $this->nextItem( substr( $prefix, -1 ) );
2462 $paragraphStack = false;
2464 if ( substr( $prefix, -1 ) === ';' ) {
2465 # The one nasty exception: definition lists work like this:
2466 # ; title : definition text
2467 # So we check for : in the remainder text to split up the
2468 # title and definition, without b0rking links.
2470 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2472 $output .= $term . $this->nextItem( ':' );
2475 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2476 # We need to open or close prefixes, or both.
2478 # Either open or close a level...
2479 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2480 $paragraphStack = false;
2482 # Close all the prefixes which aren't shared.
2483 while ( $commonPrefixLength < $lastPrefixLength ) {
2484 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2485 --$lastPrefixLength;
2488 # Continue the current prefix if appropriate.
2489 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2490 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2493 # Open prefixes where appropriate.
2494 if ( $lastPrefix && $prefixLength > $commonPrefixLength ) {
2497 while ( $prefixLength > $commonPrefixLength ) {
2498 $char = substr( $prefix, $commonPrefixLength, 1 );
2499 $output .= $this->openList( $char );
2501 if ( ';' === $char ) {
2502 # @todo FIXME: This is dupe of code above
2503 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2505 $output .= $term . $this->nextItem( ':' );
2508 ++
$commonPrefixLength;
2510 if ( !$prefixLength && $lastPrefix ) {
2513 $lastPrefix = $prefix2;
2516 # If we have no prefixes, go to paragraph mode.
2517 if ( 0 == $prefixLength ) {
2518 wfProfileIn( __METHOD__
. "-paragraph" );
2519 # No prefix (not in list)--go to paragraph mode
2520 # XXX: use a stack for nestable elements like span, table and div
2521 $openmatch = preg_match(
2522 '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|'
2523 . '<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS',
2526 $closematch = preg_match(
2527 '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'
2528 . '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|<\\/mw:|'
2529 . $this->mUniqPrefix
2530 . '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS',
2534 if ( $openmatch or $closematch ) {
2535 $paragraphStack = false;
2536 # @todo bug 5718: paragraph closed
2537 $output .= $this->closeParagraph();
2538 if ( $preOpenMatch and !$preCloseMatch ) {
2539 $this->mInPre
= true;
2542 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t, $bqMatch, PREG_OFFSET_CAPTURE
, $bqOffset ) ) {
2543 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
2544 $bqOffset = $bqMatch[0][1] +
strlen( $bqMatch[0][0] );
2546 $inBlockElem = !$closematch;
2547 } elseif ( !$inBlockElem && !$this->mInPre
) {
2548 if ( ' ' == substr( $t, 0, 1 )
2549 && ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' )
2553 if ( $this->mLastSection
!== 'pre' ) {
2554 $paragraphStack = false;
2555 $output .= $this->closeParagraph() . '<pre>';
2556 $this->mLastSection
= 'pre';
2558 $t = substr( $t, 1 );
2561 if ( trim( $t ) === '' ) {
2562 if ( $paragraphStack ) {
2563 $output .= $paragraphStack . '<br />';
2564 $paragraphStack = false;
2565 $this->mLastSection
= 'p';
2567 if ( $this->mLastSection
!== 'p' ) {
2568 $output .= $this->closeParagraph();
2569 $this->mLastSection
= '';
2570 $paragraphStack = '<p>';
2572 $paragraphStack = '</p><p>';
2576 if ( $paragraphStack ) {
2577 $output .= $paragraphStack;
2578 $paragraphStack = false;
2579 $this->mLastSection
= 'p';
2580 } elseif ( $this->mLastSection
!== 'p' ) {
2581 $output .= $this->closeParagraph() . '<p>';
2582 $this->mLastSection
= 'p';
2587 wfProfileOut( __METHOD__
. "-paragraph" );
2589 # somewhere above we forget to get out of pre block (bug 785)
2590 if ( $preCloseMatch && $this->mInPre
) {
2591 $this->mInPre
= false;
2593 if ( $paragraphStack === false ) {
2595 if ( $prefixLength === 0 ) {
2600 while ( $prefixLength ) {
2601 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2603 if ( !$prefixLength ) {
2607 if ( $this->mLastSection
!= '' ) {
2608 $output .= '</' . $this->mLastSection
. '>';
2609 $this->mLastSection
= '';
2612 wfProfileOut( __METHOD__
);
2617 * Split up a string on ':', ignoring any occurrences inside tags
2618 * to prevent illegal overlapping.
2620 * @param string $str The string to split
2621 * @param string &$before Set to everything before the ':'
2622 * @param string &$after Set to everything after the ':'
2623 * @throws MWException
2624 * @return string The position of the ':', or false if none found
2626 function findColonNoLinks( $str, &$before, &$after ) {
2627 wfProfileIn( __METHOD__
);
2629 $pos = strpos( $str, ':' );
2630 if ( $pos === false ) {
2632 wfProfileOut( __METHOD__
);
2636 $lt = strpos( $str, '<' );
2637 if ( $lt === false ||
$lt > $pos ) {
2638 # Easy; no tag nesting to worry about
2639 $before = substr( $str, 0, $pos );
2640 $after = substr( $str, $pos +
1 );
2641 wfProfileOut( __METHOD__
);
2645 # Ugly state machine to walk through avoiding tags.
2646 $state = self
::COLON_STATE_TEXT
;
2648 $len = strlen( $str );
2649 for ( $i = 0; $i < $len; $i++
) {
2653 # (Using the number is a performance hack for common cases)
2654 case 0: # self::COLON_STATE_TEXT:
2657 # Could be either a <start> tag or an </end> tag
2658 $state = self
::COLON_STATE_TAGSTART
;
2661 if ( $stack == 0 ) {
2663 $before = substr( $str, 0, $i );
2664 $after = substr( $str, $i +
1 );
2665 wfProfileOut( __METHOD__
);
2668 # Embedded in a tag; don't break it.
2671 # Skip ahead looking for something interesting
2672 $colon = strpos( $str, ':', $i );
2673 if ( $colon === false ) {
2674 # Nothing else interesting
2675 wfProfileOut( __METHOD__
);
2678 $lt = strpos( $str, '<', $i );
2679 if ( $stack === 0 ) {
2680 if ( $lt === false ||
$colon < $lt ) {
2682 $before = substr( $str, 0, $colon );
2683 $after = substr( $str, $colon +
1 );
2684 wfProfileOut( __METHOD__
);
2688 if ( $lt === false ) {
2689 # Nothing else interesting to find; abort!
2690 # We're nested, but there's no close tags left. Abort!
2693 # Skip ahead to next tag start
2695 $state = self
::COLON_STATE_TAGSTART
;
2698 case 1: # self::COLON_STATE_TAG:
2703 $state = self
::COLON_STATE_TEXT
;
2706 # Slash may be followed by >?
2707 $state = self
::COLON_STATE_TAGSLASH
;
2713 case 2: # self::COLON_STATE_TAGSTART:
2716 $state = self
::COLON_STATE_CLOSETAG
;
2719 $state = self
::COLON_STATE_COMMENT
;
2722 # Illegal early close? This shouldn't happen D:
2723 $state = self
::COLON_STATE_TEXT
;
2726 $state = self
::COLON_STATE_TAG
;
2729 case 3: # self::COLON_STATE_CLOSETAG:
2734 wfDebug( __METHOD__
. ": Invalid input; too many close tags\n" );
2735 wfProfileOut( __METHOD__
);
2738 $state = self
::COLON_STATE_TEXT
;
2741 case self
::COLON_STATE_TAGSLASH
:
2743 # Yes, a self-closed tag <blah/>
2744 $state = self
::COLON_STATE_TEXT
;
2746 # Probably we're jumping the gun, and this is an attribute
2747 $state = self
::COLON_STATE_TAG
;
2750 case 5: # self::COLON_STATE_COMMENT:
2752 $state = self
::COLON_STATE_COMMENTDASH
;
2755 case self
::COLON_STATE_COMMENTDASH
:
2757 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2759 $state = self
::COLON_STATE_COMMENT
;
2762 case self
::COLON_STATE_COMMENTDASHDASH
:
2764 $state = self
::COLON_STATE_TEXT
;
2766 $state = self
::COLON_STATE_COMMENT
;
2770 wfProfileOut( __METHOD__
);
2771 throw new MWException( "State machine error in " . __METHOD__
);
2775 wfDebug( __METHOD__
. ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2776 wfProfileOut( __METHOD__
);
2779 wfProfileOut( __METHOD__
);
2784 * Return value of a magic variable (like PAGENAME)
2789 * @param bool|PPFrame $frame
2791 * @throws MWException
2794 function getVariableValue( $index, $frame = false ) {
2795 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2796 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2798 if ( is_null( $this->mTitle
) ) {
2799 // If no title set, bad things are going to happen
2800 // later. Title should always be set since this
2801 // should only be called in the middle of a parse
2802 // operation (but the unit-tests do funky stuff)
2803 throw new MWException( __METHOD__
. ' Should only be '
2804 . ' called while parsing (no title set)' );
2808 * Some of these require message or data lookups and can be
2809 * expensive to check many times.
2811 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2812 if ( isset( $this->mVarCache
[$index] ) ) {
2813 return $this->mVarCache
[$index];
2817 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2818 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2820 $pageLang = $this->getFunctionLang();
2826 case 'currentmonth':
2827 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ) );
2829 case 'currentmonth1':
2830 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2832 case 'currentmonthname':
2833 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2835 case 'currentmonthnamegen':
2836 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2838 case 'currentmonthabbrev':
2839 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2842 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ) );
2845 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ) );
2848 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ) );
2851 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2853 case 'localmonthname':
2854 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2856 case 'localmonthnamegen':
2857 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2859 case 'localmonthabbrev':
2860 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2863 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ) );
2866 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ) );
2869 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2872 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2874 case 'fullpagename':
2875 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2877 case 'fullpagenamee':
2878 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2881 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2883 case 'subpagenamee':
2884 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2886 case 'rootpagename':
2887 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2889 case 'rootpagenamee':
2890 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
2893 $this->mTitle
->getRootText()
2896 case 'basepagename':
2897 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2899 case 'basepagenamee':
2900 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
2903 $this->mTitle
->getBaseText()
2906 case 'talkpagename':
2907 if ( $this->mTitle
->canTalk() ) {
2908 $talkPage = $this->mTitle
->getTalkPage();
2909 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2914 case 'talkpagenamee':
2915 if ( $this->mTitle
->canTalk() ) {
2916 $talkPage = $this->mTitle
->getTalkPage();
2917 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2922 case 'subjectpagename':
2923 $subjPage = $this->mTitle
->getSubjectPage();
2924 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2926 case 'subjectpagenamee':
2927 $subjPage = $this->mTitle
->getSubjectPage();
2928 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2930 case 'pageid': // requested in bug 23427
2931 $pageid = $this->getTitle()->getArticleID();
2932 if ( $pageid == 0 ) {
2933 # 0 means the page doesn't exist in the database,
2934 # which means the user is previewing a new page.
2935 # The vary-revision flag must be set, because the magic word
2936 # will have a different value once the page is saved.
2937 $this->mOutput
->setFlag( 'vary-revision' );
2938 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2940 $value = $pageid ?
$pageid : null;
2943 # Let the edit saving system know we should parse the page
2944 # *after* a revision ID has been assigned.
2945 $this->mOutput
->setFlag( 'vary-revision' );
2946 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2947 $value = $this->mRevisionId
;
2950 # Let the edit saving system know we should parse the page
2951 # *after* a revision ID has been assigned. This is for null edits.
2952 $this->mOutput
->setFlag( 'vary-revision' );
2953 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2954 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2956 case 'revisionday2':
2957 # Let the edit saving system know we should parse the page
2958 # *after* a revision ID has been assigned. This is for null edits.
2959 $this->mOutput
->setFlag( 'vary-revision' );
2960 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2961 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2963 case 'revisionmonth':
2964 # Let the edit saving system know we should parse the page
2965 # *after* a revision ID has been assigned. This is for null edits.
2966 $this->mOutput
->setFlag( 'vary-revision' );
2967 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2968 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2970 case 'revisionmonth1':
2971 # Let the edit saving system know we should parse the page
2972 # *after* a revision ID has been assigned. This is for null edits.
2973 $this->mOutput
->setFlag( 'vary-revision' );
2974 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2975 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2977 case 'revisionyear':
2978 # Let the edit saving system know we should parse the page
2979 # *after* a revision ID has been assigned. This is for null edits.
2980 $this->mOutput
->setFlag( 'vary-revision' );
2981 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2982 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2984 case 'revisiontimestamp':
2985 # Let the edit saving system know we should parse the page
2986 # *after* a revision ID has been assigned. This is for null edits.
2987 $this->mOutput
->setFlag( 'vary-revision' );
2988 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2989 $value = $this->getRevisionTimestamp();
2991 case 'revisionuser':
2992 # Let the edit saving system know we should parse the page
2993 # *after* a revision ID has been assigned. This is for null edits.
2994 $this->mOutput
->setFlag( 'vary-revision' );
2995 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2996 $value = $this->getRevisionUser();
2998 case 'revisionsize':
2999 # Let the edit saving system know we should parse the page
3000 # *after* a revision ID has been assigned. This is for null edits.
3001 $this->mOutput
->setFlag( 'vary-revision' );
3002 wfDebug( __METHOD__
. ": {{REVISIONSIZE}} used, setting vary-revision...\n" );
3003 $value = $this->getRevisionSize();
3006 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3009 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3011 case 'namespacenumber':
3012 $value = $this->mTitle
->getNamespace();
3015 $value = $this->mTitle
->canTalk()
3016 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
3020 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
3022 case 'subjectspace':
3023 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
3025 case 'subjectspacee':
3026 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
3028 case 'currentdayname':
3029 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
3032 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
3035 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
3038 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
3041 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3042 # int to remove the padding
3043 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
3046 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
3048 case 'localdayname':
3049 $value = $pageLang->getWeekdayName(
3050 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
3054 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
3057 $value = $pageLang->time(
3058 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
3064 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
3067 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3068 # int to remove the padding
3069 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
3072 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
3074 case 'numberofarticles':
3075 $value = $pageLang->formatNum( SiteStats
::articles() );
3077 case 'numberoffiles':
3078 $value = $pageLang->formatNum( SiteStats
::images() );
3080 case 'numberofusers':
3081 $value = $pageLang->formatNum( SiteStats
::users() );
3083 case 'numberofactiveusers':
3084 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
3086 case 'numberofpages':
3087 $value = $pageLang->formatNum( SiteStats
::pages() );
3089 case 'numberofadmins':
3090 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
3092 case 'numberofedits':
3093 $value = $pageLang->formatNum( SiteStats
::edits() );
3095 case 'numberofviews':
3096 global $wgDisableCounters;
3097 $value = !$wgDisableCounters ?
$pageLang->formatNum( SiteStats
::views() ) : '';
3099 case 'currenttimestamp':
3100 $value = wfTimestamp( TS_MW
, $ts );
3102 case 'localtimestamp':
3103 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
3105 case 'currentversion':
3106 $value = SpecialVersion
::getVersion();
3109 return $wgArticlePath;
3115 return $wgServerName;
3117 return $wgScriptPath;
3119 return $wgStylePath;
3120 case 'directionmark':
3121 return $pageLang->getDirMark();
3122 case 'contentlanguage':
3123 global $wgLanguageCode;
3124 return $wgLanguageCode;
3125 case 'cascadingsources':
3126 $value = CoreParserFunctions
::cascadingsources( $this );
3131 'ParserGetVariableValueSwitch',
3132 array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame )
3139 $this->mVarCache
[$index] = $value;
3146 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3150 function initialiseVariables() {
3151 wfProfileIn( __METHOD__
);
3152 $variableIDs = MagicWord
::getVariableIDs();
3153 $substIDs = MagicWord
::getSubstIDs();
3155 $this->mVariables
= new MagicWordArray( $variableIDs );
3156 $this->mSubstWords
= new MagicWordArray( $substIDs );
3157 wfProfileOut( __METHOD__
);
3161 * Preprocess some wikitext and return the document tree.
3162 * This is the ghost of replace_variables().
3164 * @param string $text The text to parse
3165 * @param int $flags Bitwise combination of:
3166 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
3167 * included. Default is to assume a direct page view.
3169 * The generated DOM tree must depend only on the input text and the flags.
3170 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3172 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3173 * change in the DOM tree for a given text, must be passed through the section identifier
3174 * in the section edit link and thus back to extractSections().
3176 * The output of this function is currently only cached in process memory, but a persistent
3177 * cache may be implemented at a later date which takes further advantage of these strict
3178 * dependency requirements.
3182 function preprocessToDom( $text, $flags = 0 ) {
3183 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3188 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3194 public static function splitWhitespace( $s ) {
3195 $ltrimmed = ltrim( $s );
3196 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3197 $trimmed = rtrim( $ltrimmed );
3198 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3200 $w2 = substr( $ltrimmed, -$diff );
3204 return array( $w1, $trimmed, $w2 );
3208 * Replace magic variables, templates, and template arguments
3209 * with the appropriate text. Templates are substituted recursively,
3210 * taking care to avoid infinite loops.
3212 * Note that the substitution depends on value of $mOutputType:
3213 * self::OT_WIKI: only {{subst:}} templates
3214 * self::OT_PREPROCESS: templates but not extension tags
3215 * self::OT_HTML: all templates and extension tags
3217 * @param string $text The text to transform
3218 * @param bool|PPFrame $frame Object describing the arguments passed to the
3219 * template. Arguments may also be provided as an associative array, as
3220 * was the usual case before MW1.12. Providing arguments this way may be
3221 * useful for extensions wishing to perform variable replacement
3223 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3224 * double-brace expansion.
3227 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3228 # Is there any text? Also, Prevent too big inclusions!
3229 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3232 wfProfileIn( __METHOD__
);
3234 if ( $frame === false ) {
3235 $frame = $this->getPreprocessor()->newFrame();
3236 } elseif ( !( $frame instanceof PPFrame
) ) {
3237 wfDebug( __METHOD__
. " called using plain parameters instead of "
3238 . "a PPFrame instance. Creating custom frame.\n" );
3239 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3242 $dom = $this->preprocessToDom( $text );
3243 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3244 $text = $frame->expand( $dom, $flags );
3246 wfProfileOut( __METHOD__
);
3251 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3253 * @param array $args
3257 static function createAssocArgs( $args ) {
3258 $assocArgs = array();
3260 foreach ( $args as $arg ) {
3261 $eqpos = strpos( $arg, '=' );
3262 if ( $eqpos === false ) {
3263 $assocArgs[$index++
] = $arg;
3265 $name = trim( substr( $arg, 0, $eqpos ) );
3266 $value = trim( substr( $arg, $eqpos +
1 ) );
3267 if ( $value === false ) {
3270 if ( $name !== false ) {
3271 $assocArgs[$name] = $value;
3280 * Warn the user when a parser limitation is reached
3281 * Will warn at most once the user per limitation type
3283 * @param string $limitationType Should be one of:
3284 * 'expensive-parserfunction' (corresponding messages:
3285 * 'expensive-parserfunction-warning',
3286 * 'expensive-parserfunction-category')
3287 * 'post-expand-template-argument' (corresponding messages:
3288 * 'post-expand-template-argument-warning',
3289 * 'post-expand-template-argument-category')
3290 * 'post-expand-template-inclusion' (corresponding messages:
3291 * 'post-expand-template-inclusion-warning',
3292 * 'post-expand-template-inclusion-category')
3293 * 'node-count-exceeded' (corresponding messages:
3294 * 'node-count-exceeded-warning',
3295 * 'node-count-exceeded-category')
3296 * 'expansion-depth-exceeded' (corresponding messages:
3297 * 'expansion-depth-exceeded-warning',
3298 * 'expansion-depth-exceeded-category')
3299 * @param string|int|null $current Current value
3300 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3301 * exceeded, provide the values (optional)
3303 function limitationWarn( $limitationType, $current = '', $max = '' ) {
3304 # does no harm if $current and $max are present but are unnecessary for the message
3305 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3306 ->inLanguage( $this->mOptions
->getUserLangObj() )->text();
3307 $this->mOutput
->addWarning( $warning );
3308 $this->addTrackingCategory( "$limitationType-category" );
3312 * Return the text of a template, after recursively
3313 * replacing any variables or templates within the template.
3315 * @param array $piece The parts of the template
3316 * $piece['title']: the title, i.e. the part before the |
3317 * $piece['parts']: the parameter array
3318 * $piece['lineStart']: whether the brace was at the start of a line
3319 * @param PPFrame $frame The current frame, contains template arguments
3321 * @return string The text of the template
3323 public function braceSubstitution( $piece, $frame ) {
3324 wfProfileIn( __METHOD__
);
3325 wfProfileIn( __METHOD__
. '-setup' );
3329 // $text has been filled
3331 // wiki markup in $text should be escaped
3333 // $text is HTML, armour it against wikitext transformation
3335 // Force interwiki transclusion to be done in raw mode not rendered
3336 $forceRawInterwiki = false;
3337 // $text is a DOM node needing expansion in a child frame
3338 $isChildObj = false;
3339 // $text is a DOM node needing expansion in the current frame
3340 $isLocalObj = false;
3342 # Title object, where $text came from
3345 # $part1 is the bit before the first |, and must contain only title characters.
3346 # Various prefixes will be stripped from it later.
3347 $titleWithSpaces = $frame->expand( $piece['title'] );
3348 $part1 = trim( $titleWithSpaces );
3351 # Original title text preserved for various purposes
3352 $originalTitle = $part1;
3354 # $args is a list of argument nodes, starting from index 0, not including $part1
3355 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3356 # below won't work b/c this $args isn't an object
3357 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3358 wfProfileOut( __METHOD__
. '-setup' );
3360 $titleProfileIn = null; // profile templates
3363 wfProfileIn( __METHOD__
. '-modifiers' );
3366 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3368 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3369 # Decide whether to expand template or keep wikitext as-is.
3370 if ( $this->ot
['wiki'] ) {
3371 if ( $substMatch === false ) {
3372 $literal = true; # literal when in PST with no prefix
3374 $literal = false; # expand when in PST with subst: or safesubst:
3377 if ( $substMatch == 'subst' ) {
3378 $literal = true; # literal when not in PST with plain subst:
3380 $literal = false; # expand when not in PST with safesubst: or no prefix
3384 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3391 if ( !$found && $args->getLength() == 0 ) {
3392 $id = $this->mVariables
->matchStartToEnd( $part1 );
3393 if ( $id !== false ) {
3394 $text = $this->getVariableValue( $id, $frame );
3395 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3396 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3402 # MSG, MSGNW and RAW
3405 $mwMsgnw = MagicWord
::get( 'msgnw' );
3406 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3409 # Remove obsolete MSG:
3410 $mwMsg = MagicWord
::get( 'msg' );
3411 $mwMsg->matchStartAndRemove( $part1 );
3415 $mwRaw = MagicWord
::get( 'raw' );
3416 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3417 $forceRawInterwiki = true;
3420 wfProfileOut( __METHOD__
. '-modifiers' );
3424 wfProfileIn( __METHOD__
. '-pfunc' );
3426 $colonPos = strpos( $part1, ':' );
3427 if ( $colonPos !== false ) {
3428 $func = substr( $part1, 0, $colonPos );
3429 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3430 for ( $i = 0; $i < $args->getLength(); $i++
) {
3431 $funcArgs[] = $args->item( $i );
3434 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3435 } catch ( Exception
$ex ) {
3436 wfProfileOut( __METHOD__
. '-pfunc' );
3437 wfProfileOut( __METHOD__
);
3441 # The interface for parser functions allows for extracting
3442 # flags into the local scope. Extract any forwarded flags
3446 wfProfileOut( __METHOD__
. '-pfunc' );
3449 # Finish mangling title and then check for loops.
3450 # Set $title to a Title object and $titleText to the PDBK
3453 # Split the title into page and subpage
3455 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3456 if ( $part1 !== $relative ) {
3458 $ns = $this->mTitle
->getNamespace();
3460 $title = Title
::newFromText( $part1, $ns );
3462 $titleText = $title->getPrefixedText();
3463 # Check for language variants if the template is not found
3464 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3465 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3467 # Do recursion depth check
3468 $limit = $this->mOptions
->getMaxTemplateDepth();
3469 if ( $frame->depth
>= $limit ) {
3471 $text = '<span class="error">'
3472 . wfMessage( 'parser-template-recursion-depth-warning' )
3473 ->numParams( $limit )->inContentLanguage()->text()
3479 # Load from database
3480 if ( !$found && $title ) {
3481 if ( !Profiler
::instance()->isPersistent() ) {
3482 # Too many unique items can kill profiling DBs/collectors
3483 $titleProfileIn = __METHOD__
. "-title-" . $title->getPrefixedDBkey();
3484 wfProfileIn( $titleProfileIn ); // template in
3486 wfProfileIn( __METHOD__
. '-loadtpl' );
3487 if ( !$title->isExternal() ) {
3488 if ( $title->isSpecialPage()
3489 && $this->mOptions
->getAllowSpecialInclusion()
3490 && $this->ot
['html']
3492 // Pass the template arguments as URL parameters.
3493 // "uselang" will have no effect since the Language object
3494 // is forced to the one defined in ParserOptions.
3495 $pageArgs = array();
3496 $argsLength = $args->getLength();
3497 for ( $i = 0; $i < $argsLength; $i++
) {
3498 $bits = $args->item( $i )->splitArg();
3499 if ( strval( $bits['index'] ) === '' ) {
3500 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3501 $value = trim( $frame->expand( $bits['value'] ) );
3502 $pageArgs[$name] = $value;
3506 // Create a new context to execute the special page
3507 $context = new RequestContext
;
3508 $context->setTitle( $title );
3509 $context->setRequest( new FauxRequest( $pageArgs ) );
3510 $context->setUser( $this->getUser() );
3511 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3512 $ret = SpecialPageFactory
::capturePath( $title, $context );
3514 $text = $context->getOutput()->getHTML();
3515 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3518 $this->disableCache();
3520 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3521 $found = false; # access denied
3522 wfDebug( __METHOD__
. ": template inclusion denied for " .
3523 $title->getPrefixedDBkey() . "\n" );
3525 list( $text, $title ) = $this->getTemplateDom( $title );
3526 if ( $text !== false ) {
3532 # If the title is valid but undisplayable, make a link to it
3533 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3534 $text = "[[:$titleText]]";
3537 } elseif ( $title->isTrans() ) {
3538 # Interwiki transclusion
3539 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3540 $text = $this->interwikiTransclude( $title, 'render' );
3543 $text = $this->interwikiTransclude( $title, 'raw' );
3544 # Preprocess it like a template
3545 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3551 # Do infinite loop check
3552 # This has to be done after redirect resolution to avoid infinite loops via redirects
3553 if ( !$frame->loopCheck( $title ) ) {
3555 $text = '<span class="error">'
3556 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3558 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3560 wfProfileOut( __METHOD__
. '-loadtpl' );
3563 # If we haven't found text to substitute by now, we're done
3564 # Recover the source wikitext and return it
3566 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3567 if ( $titleProfileIn ) {
3568 wfProfileOut( $titleProfileIn ); // template out
3570 wfProfileOut( __METHOD__
);
3571 return array( 'object' => $text );
3574 # Expand DOM-style return values in a child frame
3575 if ( $isChildObj ) {
3576 # Clean up argument array
3577 $newFrame = $frame->newChild( $args, $title );
3580 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3581 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3582 # Expansion is eligible for the empty-frame cache
3583 $text = $newFrame->cachedExpand( $titleText, $text );
3585 # Uncached expansion
3586 $text = $newFrame->expand( $text );
3589 if ( $isLocalObj && $nowiki ) {
3590 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3591 $isLocalObj = false;
3594 if ( $titleProfileIn ) {
3595 wfProfileOut( $titleProfileIn ); // template out
3598 # Replace raw HTML by a placeholder
3600 $text = $this->insertStripItem( $text );
3601 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3602 # Escape nowiki-style return values
3603 $text = wfEscapeWikiText( $text );
3604 } elseif ( is_string( $text )
3605 && !$piece['lineStart']
3606 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3608 # Bug 529: if the template begins with a table or block-level
3609 # element, it should be treated as beginning a new line.
3610 # This behavior is somewhat controversial.
3611 $text = "\n" . $text;
3614 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3615 # Error, oversize inclusion
3616 if ( $titleText !== false ) {
3617 # Make a working, properly escaped link if possible (bug 23588)
3618 $text = "[[:$titleText]]";
3620 # This will probably not be a working link, but at least it may
3621 # provide some hint of where the problem is
3622 preg_replace( '/^:/', '', $originalTitle );
3623 $text = "[[:$originalTitle]]";
3625 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3626 . 'post-expand include size too large -->' );
3627 $this->limitationWarn( 'post-expand-template-inclusion' );
3630 if ( $isLocalObj ) {
3631 $ret = array( 'object' => $text );
3633 $ret = array( 'text' => $text );
3636 wfProfileOut( __METHOD__
);
3641 * Call a parser function and return an array with text and flags.
3643 * The returned array will always contain a boolean 'found', indicating
3644 * whether the parser function was found or not. It may also contain the
3646 * text: string|object, resulting wikitext or PP DOM object
3647 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3648 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3649 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3650 * nowiki: bool, wiki markup in $text should be escaped
3653 * @param PPFrame $frame The current frame, contains template arguments
3654 * @param string $function Function name
3655 * @param array $args Arguments to the function
3656 * @throws MWException
3659 public function callParserFunction( $frame, $function, array $args = array() ) {
3662 wfProfileIn( __METHOD__
);
3664 # Case sensitive functions
3665 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3666 $function = $this->mFunctionSynonyms
[1][$function];
3668 # Case insensitive functions
3669 $function = $wgContLang->lc( $function );
3670 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3671 $function = $this->mFunctionSynonyms
[0][$function];
3673 wfProfileOut( __METHOD__
);
3674 return array( 'found' => false );
3678 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3679 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3681 # Workaround for PHP bug 35229 and similar
3682 if ( !is_callable( $callback ) ) {
3683 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3684 wfProfileOut( __METHOD__
);
3685 throw new MWException( "Tag hook for $function is not callable\n" );
3688 $allArgs = array( &$this );
3689 if ( $flags & SFH_OBJECT_ARGS
) {
3690 # Convert arguments to PPNodes and collect for appending to $allArgs
3691 $funcArgs = array();
3692 foreach ( $args as $k => $v ) {
3693 if ( $v instanceof PPNode ||
$k === 0 ) {
3696 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( array( $k => $v ) )->item( 0 );
3700 # Add a frame parameter, and pass the arguments as an array
3701 $allArgs[] = $frame;
3702 $allArgs[] = $funcArgs;
3704 # Convert arguments to plain text and append to $allArgs
3705 foreach ( $args as $k => $v ) {
3706 if ( $v instanceof PPNode
) {
3707 $allArgs[] = trim( $frame->expand( $v ) );
3708 } elseif ( is_int( $k ) && $k >= 0 ) {
3709 $allArgs[] = trim( $v );
3711 $allArgs[] = trim( "$k=$v" );
3716 $result = call_user_func_array( $callback, $allArgs );
3718 # The interface for function hooks allows them to return a wikitext
3719 # string or an array containing the string and any flags. This mungs
3720 # things around to match what this method should return.
3721 if ( !is_array( $result ) ) {
3727 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3728 $result['text'] = $result[0];
3730 unset( $result[0] );
3737 $preprocessFlags = 0;
3738 if ( isset( $result['noparse'] ) ) {
3739 $noparse = $result['noparse'];
3741 if ( isset( $result['preprocessFlags'] ) ) {
3742 $preprocessFlags = $result['preprocessFlags'];
3746 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3747 $result['isChildObj'] = true;
3749 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3750 wfProfileOut( __METHOD__
);
3756 * Get the semi-parsed DOM representation of a template with a given title,
3757 * and its redirect destination title. Cached.
3759 * @param Title $title
3763 function getTemplateDom( $title ) {
3764 $cacheTitle = $title;
3765 $titleText = $title->getPrefixedDBkey();
3767 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3768 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3769 $title = Title
::makeTitle( $ns, $dbk );
3770 $titleText = $title->getPrefixedDBkey();
3772 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3773 return array( $this->mTplDomCache
[$titleText], $title );
3776 # Cache miss, go to the database
3777 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3779 if ( $text === false ) {
3780 $this->mTplDomCache
[$titleText] = false;
3781 return array( false, $title );
3784 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3785 $this->mTplDomCache
[$titleText] = $dom;
3787 if ( !$title->equals( $cacheTitle ) ) {
3788 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3789 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3792 return array( $dom, $title );
3796 * Fetch the unparsed text of a template and register a reference to it.
3797 * @param Title $title
3798 * @return array ( string or false, Title )
3800 function fetchTemplateAndTitle( $title ) {
3801 // Defaults to Parser::statelessFetchTemplate()
3802 $templateCb = $this->mOptions
->getTemplateCallback();
3803 $stuff = call_user_func( $templateCb, $title, $this );
3804 $text = $stuff['text'];
3805 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3806 if ( isset( $stuff['deps'] ) ) {
3807 foreach ( $stuff['deps'] as $dep ) {
3808 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3809 if ( $dep['title']->equals( $this->getTitle() ) ) {
3810 // If we transclude ourselves, the final result
3811 // will change based on the new version of the page
3812 $this->mOutput
->setFlag( 'vary-revision' );
3816 return array( $text, $finalTitle );
3820 * Fetch the unparsed text of a template and register a reference to it.
3821 * @param Title $title
3822 * @return string|bool
3824 function fetchTemplate( $title ) {
3825 $rv = $this->fetchTemplateAndTitle( $title );
3830 * Static function to get a template
3831 * Can be overridden via ParserOptions::setTemplateCallback().
3833 * @param Title $title
3834 * @param bool|Parser $parser
3838 static function statelessFetchTemplate( $title, $parser = false ) {
3839 $text = $skip = false;
3840 $finalTitle = $title;
3843 # Loop to fetch the article, with up to 1 redirect
3844 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3845 # Give extensions a chance to select the revision instead
3846 $id = false; # Assume current
3847 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3848 array( $parser, $title, &$skip, &$id ) );
3854 'page_id' => $title->getArticleID(),
3861 ? Revision
::newFromId( $id )
3862 : Revision
::newFromTitle( $title, false, Revision
::READ_NORMAL
);
3863 $rev_id = $rev ?
$rev->getId() : 0;
3864 # If there is no current revision, there is no page
3865 if ( $id === false && !$rev ) {
3866 $linkCache = LinkCache
::singleton();
3867 $linkCache->addBadLinkObj( $title );
3872 'page_id' => $title->getArticleID(),
3873 'rev_id' => $rev_id );
3874 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3875 # We fetched a rev from a different title; register it too...
3877 'title' => $rev->getTitle(),
3878 'page_id' => $rev->getPage(),
3879 'rev_id' => $rev_id );
3883 $content = $rev->getContent();
3884 $text = $content ?
$content->getWikitextForTransclusion() : null;
3886 if ( $text === false ||
$text === null ) {
3890 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3892 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3893 if ( !$message->exists() ) {
3897 $content = $message->content();
3898 $text = $message->plain();
3906 $finalTitle = $title;
3907 $title = $content->getRedirectTarget();
3911 'finalTitle' => $finalTitle,
3916 * Fetch a file and its title and register a reference to it.
3917 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3918 * @param Title $title
3919 * @param array $options Array of options to RepoGroup::findFile
3922 function fetchFile( $title, $options = array() ) {
3923 $res = $this->fetchFileAndTitle( $title, $options );
3928 * Fetch a file and its title and register a reference to it.
3929 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3930 * @param Title $title
3931 * @param array $options Array of options to RepoGroup::findFile
3932 * @return array ( File or false, Title of file )
3934 function fetchFileAndTitle( $title, $options = array() ) {
3935 $file = $this->fetchFileNoRegister( $title, $options );
3937 $time = $file ?
$file->getTimestamp() : false;
3938 $sha1 = $file ?
$file->getSha1() : false;
3939 # Register the file as a dependency...
3940 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3941 if ( $file && !$title->equals( $file->getTitle() ) ) {
3942 # Update fetched file title
3943 $title = $file->getTitle();
3944 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3946 return array( $file, $title );
3950 * Helper function for fetchFileAndTitle.
3952 * Also useful if you need to fetch a file but not use it yet,
3953 * for example to get the file's handler.
3955 * @param Title $title
3956 * @param array $options Array of options to RepoGroup::findFile
3959 protected function fetchFileNoRegister( $title, $options = array() ) {
3960 if ( isset( $options['broken'] ) ) {
3961 $file = false; // broken thumbnail forced by hook
3962 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3963 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3964 } else { // get by (name,timestamp)
3965 $file = wfFindFile( $title, $options );
3971 * Transclude an interwiki link.
3973 * @param Title $title
3974 * @param string $action
3978 function interwikiTransclude( $title, $action ) {
3979 global $wgEnableScaryTranscluding;
3981 if ( !$wgEnableScaryTranscluding ) {
3982 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3985 $url = $title->getFullURL( array( 'action' => $action ) );
3987 if ( strlen( $url ) > 255 ) {
3988 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3990 return $this->fetchScaryTemplateMaybeFromCache( $url );
3994 * @param string $url
3995 * @return mixed|string
3997 function fetchScaryTemplateMaybeFromCache( $url ) {
3998 global $wgTranscludeCacheExpiry;
3999 $dbr = wfGetDB( DB_SLAVE
);
4000 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
4001 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
4002 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
4004 return $obj->tc_contents
;
4007 $req = MWHttpRequest
::factory( $url );
4008 $status = $req->execute(); // Status object
4009 if ( $status->isOK() ) {
4010 $text = $req->getContent();
4011 } elseif ( $req->getStatus() != 200 ) {
4012 // Though we failed to fetch the content, this status is useless.
4013 return wfMessage( 'scarytranscludefailed-httpstatus' )
4014 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
4016 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
4019 $dbw = wfGetDB( DB_MASTER
);
4020 $dbw->replace( 'transcache', array( 'tc_url' ), array(
4022 'tc_time' => $dbw->timestamp( time() ),
4023 'tc_contents' => $text
4029 * Triple brace replacement -- used for template arguments
4032 * @param array $piece
4033 * @param PPFrame $frame
4037 function argSubstitution( $piece, $frame ) {
4038 wfProfileIn( __METHOD__
);
4041 $parts = $piece['parts'];
4042 $nameWithSpaces = $frame->expand( $piece['title'] );
4043 $argName = trim( $nameWithSpaces );
4045 $text = $frame->getArgument( $argName );
4046 if ( $text === false && $parts->getLength() > 0
4047 && ( $this->ot
['html']
4049 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
4052 # No match in frame, use the supplied default
4053 $object = $parts->item( 0 )->getChildren();
4055 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
4056 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
4057 $this->limitationWarn( 'post-expand-template-argument' );
4060 if ( $text === false && $object === false ) {
4062 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
4064 if ( $error !== false ) {
4067 if ( $object !== false ) {
4068 $ret = array( 'object' => $object );
4070 $ret = array( 'text' => $text );
4073 wfProfileOut( __METHOD__
);
4078 * Return the text to be used for a given extension tag.
4079 * This is the ghost of strip().
4081 * @param array $params Associative array of parameters:
4082 * name PPNode for the tag name
4083 * attr PPNode for unparsed text where tag attributes are thought to be
4084 * attributes Optional associative array of parsed attributes
4085 * inner Contents of extension element
4086 * noClose Original text did not have a close tag
4087 * @param PPFrame $frame
4089 * @throws MWException
4092 function extensionSubstitution( $params, $frame ) {
4093 $name = $frame->expand( $params['name'] );
4094 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
4095 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
4096 $marker = "{$this->mUniqPrefix}-$name-"
4097 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
4099 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
4100 ( $this->ot
['html'] ||
$this->ot
['pre'] );
4101 if ( $isFunctionTag ) {
4102 $markerType = 'none';
4104 $markerType = 'general';
4106 if ( $this->ot
['html'] ||
$isFunctionTag ) {
4107 $name = strtolower( $name );
4108 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
4109 if ( isset( $params['attributes'] ) ) {
4110 $attributes = $attributes +
$params['attributes'];
4113 if ( isset( $this->mTagHooks
[$name] ) ) {
4114 # Workaround for PHP bug 35229 and similar
4115 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
4116 throw new MWException( "Tag hook for $name is not callable\n" );
4118 $output = call_user_func_array( $this->mTagHooks
[$name],
4119 array( $content, $attributes, $this, $frame ) );
4120 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
4121 list( $callback, ) = $this->mFunctionTagHooks
[$name];
4122 if ( !is_callable( $callback ) ) {
4123 throw new MWException( "Tag hook for $name is not callable\n" );
4126 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
4128 $output = '<span class="error">Invalid tag extension name: ' .
4129 htmlspecialchars( $name ) . '</span>';
4132 if ( is_array( $output ) ) {
4133 # Extract flags to local scope (to override $markerType)
4135 $output = $flags[0];
4140 if ( is_null( $attrText ) ) {
4143 if ( isset( $params['attributes'] ) ) {
4144 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4145 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4146 htmlspecialchars( $attrValue ) . '"';
4149 if ( $content === null ) {
4150 $output = "<$name$attrText/>";
4152 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4153 $output = "<$name$attrText>$content$close";
4157 if ( $markerType === 'none' ) {
4159 } elseif ( $markerType === 'nowiki' ) {
4160 $this->mStripState
->addNoWiki( $marker, $output );
4161 } elseif ( $markerType === 'general' ) {
4162 $this->mStripState
->addGeneral( $marker, $output );
4164 throw new MWException( __METHOD__
. ': invalid marker type' );
4170 * Increment an include size counter
4172 * @param string $type The type of expansion
4173 * @param int $size The size of the text
4174 * @return bool False if this inclusion would take it over the maximum, true otherwise
4176 function incrementIncludeSize( $type, $size ) {
4177 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4180 $this->mIncludeSizes
[$type] +
= $size;
4186 * Increment the expensive function count
4188 * @return bool False if the limit has been exceeded
4190 function incrementExpensiveFunctionCount() {
4191 $this->mExpensiveFunctionCount++
;
4192 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4196 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4197 * Fills $this->mDoubleUnderscores, returns the modified text
4199 * @param string $text
4203 function doDoubleUnderscore( $text ) {
4204 wfProfileIn( __METHOD__
);
4206 # The position of __TOC__ needs to be recorded
4207 $mw = MagicWord
::get( 'toc' );
4208 if ( $mw->match( $text ) ) {
4209 $this->mShowToc
= true;
4210 $this->mForceTocPosition
= true;
4212 # Set a placeholder. At the end we'll fill it in with the TOC.
4213 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4215 # Only keep the first one.
4216 $text = $mw->replace( '', $text );
4219 # Now match and remove the rest of them
4220 $mwa = MagicWord
::getDoubleUnderscoreArray();
4221 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4223 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4224 $this->mOutput
->mNoGallery
= true;
4226 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4227 $this->mShowToc
= false;
4229 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4230 && $this->mTitle
->getNamespace() == NS_CATEGORY
4232 $this->addTrackingCategory( 'hidden-category-category' );
4234 # (bug 8068) Allow control over whether robots index a page.
4236 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4237 # is not desirable, the last one on the page should win.
4238 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4239 $this->mOutput
->setIndexPolicy( 'noindex' );
4240 $this->addTrackingCategory( 'noindex-category' );
4242 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4243 $this->mOutput
->setIndexPolicy( 'index' );
4244 $this->addTrackingCategory( 'index-category' );
4247 # Cache all double underscores in the database
4248 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4249 $this->mOutput
->setProperty( $key, '' );
4252 wfProfileOut( __METHOD__
);
4257 * Add a tracking category, getting the title from a system message,
4258 * or print a debug message if the title is invalid.
4260 * Please add any message that you use with this function to
4261 * $wgTrackingCategories. That way they will be listed on
4262 * Special:TrackingCategories.
4264 * @param string $msg Message key
4265 * @return bool Whether the addition was successful
4267 public function addTrackingCategory( $msg ) {
4268 if ( $this->mTitle
->getNamespace() === NS_SPECIAL
) {
4269 wfDebug( __METHOD__
. ": Not adding tracking category $msg to special page!\n" );
4272 // Important to parse with correct title (bug 31469)
4273 $cat = wfMessage( $msg )
4274 ->title( $this->getTitle() )
4275 ->inContentLanguage()
4278 # Allow tracking categories to be disabled by setting them to "-"
4279 if ( $cat === '-' ) {
4283 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
4284 if ( $containerCategory ) {
4285 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
4288 wfDebug( __METHOD__
. ": [[MediaWiki:$msg]] is not a valid title!\n" );
4294 * This function accomplishes several tasks:
4295 * 1) Auto-number headings if that option is enabled
4296 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4297 * 3) Add a Table of contents on the top for users who have enabled the option
4298 * 4) Auto-anchor headings
4300 * It loops through all headlines, collects the necessary data, then splits up the
4301 * string and re-inserts the newly formatted headlines.
4303 * @param string $text
4304 * @param string $origText Original, untouched wikitext
4305 * @param bool $isMain
4306 * @return mixed|string
4309 function formatHeadings( $text, $origText, $isMain = true ) {
4310 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4312 # Inhibit editsection links if requested in the page
4313 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4314 $maybeShowEditLink = $showEditLink = false;
4316 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4317 $showEditLink = $this->mOptions
->getEditSection();
4319 if ( $showEditLink ) {
4320 $this->mOutput
->setEditSectionTokens( true );
4323 # Get all headlines for numbering them and adding funky stuff like [edit]
4324 # links - this is for later, but we need the number of headlines right now
4326 $numMatches = preg_match_all(
4327 '/<H(?P<level>[1-6])(?P<attrib>.*?' . '>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i',
4332 # if there are fewer than 4 headlines in the article, do not show TOC
4333 # unless it's been explicitly enabled.
4334 $enoughToc = $this->mShowToc
&&
4335 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4337 # Allow user to stipulate that a page should have a "new section"
4338 # link added via __NEWSECTIONLINK__
4339 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4340 $this->mOutput
->setNewSection( true );
4343 # Allow user to remove the "new section"
4344 # link via __NONEWSECTIONLINK__
4345 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4346 $this->mOutput
->hideNewSection( true );
4349 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4350 # override above conditions and always show TOC above first header
4351 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4352 $this->mShowToc
= true;
4360 # Ugh .. the TOC should have neat indentation levels which can be
4361 # passed to the skin functions. These are determined here
4365 $sublevelCount = array();
4366 $levelCount = array();
4371 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4372 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4373 $oldType = $this->mOutputType
;
4374 $this->setOutputType( self
::OT_WIKI
);
4375 $frame = $this->getPreprocessor()->newFrame();
4376 $root = $this->preprocessToDom( $origText );
4377 $node = $root->getFirstChild();
4382 foreach ( $matches[3] as $headline ) {
4383 $isTemplate = false;
4385 $sectionIndex = false;
4387 $markerMatches = array();
4388 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4389 $serial = $markerMatches[1];
4390 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4391 $isTemplate = ( $titleText != $baseTitleText );
4392 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4396 $prevlevel = $level;
4398 $level = $matches[1][$headlineCount];
4400 if ( $level > $prevlevel ) {
4401 # Increase TOC level
4403 $sublevelCount[$toclevel] = 0;
4404 if ( $toclevel < $wgMaxTocLevel ) {
4405 $prevtoclevel = $toclevel;
4406 $toc .= Linker
::tocIndent();
4409 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4410 # Decrease TOC level, find level to jump to
4412 for ( $i = $toclevel; $i > 0; $i-- ) {
4413 if ( $levelCount[$i] == $level ) {
4414 # Found last matching level
4417 } elseif ( $levelCount[$i] < $level ) {
4418 # Found first matching level below current level
4426 if ( $toclevel < $wgMaxTocLevel ) {
4427 if ( $prevtoclevel < $wgMaxTocLevel ) {
4428 # Unindent only if the previous toc level was shown :p
4429 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4430 $prevtoclevel = $toclevel;
4432 $toc .= Linker
::tocLineEnd();
4436 # No change in level, end TOC line
4437 if ( $toclevel < $wgMaxTocLevel ) {
4438 $toc .= Linker
::tocLineEnd();
4442 $levelCount[$toclevel] = $level;
4444 # count number of headlines for each level
4445 $sublevelCount[$toclevel]++
;
4447 for ( $i = 1; $i <= $toclevel; $i++
) {
4448 if ( !empty( $sublevelCount[$i] ) ) {
4452 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4457 # The safe header is a version of the header text safe to use for links
4459 # Remove link placeholders by the link text.
4460 # <!--LINK number-->
4462 # link text with suffix
4463 # Do this before unstrip since link text can contain strip markers
4464 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4466 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4467 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4469 # Strip out HTML (first regex removes any tag not allowed)
4471 # * <sup> and <sub> (bug 8393)
4474 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4476 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4477 # to allow setting directionality in toc items.
4478 $tocline = preg_replace(
4480 '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?' . '>#',
4481 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?' . '>#'
4483 array( '', '<$1>' ),
4486 $tocline = trim( $tocline );
4488 # For the anchor, strip out HTML-y stuff period
4489 $safeHeadline = preg_replace( '/<.*?' . '>/', '', $safeHeadline );
4490 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4492 # Save headline for section edit hint before it's escaped
4493 $headlineHint = $safeHeadline;
4495 if ( $wgExperimentalHtmlIds ) {
4496 # For reverse compatibility, provide an id that's
4497 # HTML4-compatible, like we used to.
4499 # It may be worth noting, academically, that it's possible for
4500 # the legacy anchor to conflict with a non-legacy headline
4501 # anchor on the page. In this case likely the "correct" thing
4502 # would be to either drop the legacy anchors or make sure
4503 # they're numbered first. However, this would require people
4504 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4505 # manually, so let's not bother worrying about it.
4506 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4507 array( 'noninitial', 'legacy' ) );
4508 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4510 if ( $legacyHeadline == $safeHeadline ) {
4511 # No reason to have both (in fact, we can't)
4512 $legacyHeadline = false;
4515 $legacyHeadline = false;
4516 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4520 # HTML names must be case-insensitively unique (bug 10721).
4521 # This does not apply to Unicode characters per
4522 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4523 # @todo FIXME: We may be changing them depending on the current locale.
4524 $arrayKey = strtolower( $safeHeadline );
4525 if ( $legacyHeadline === false ) {
4526 $legacyArrayKey = false;
4528 $legacyArrayKey = strtolower( $legacyHeadline );
4531 # count how many in assoc. array so we can track dupes in anchors
4532 if ( isset( $refers[$arrayKey] ) ) {
4533 $refers[$arrayKey]++
;
4535 $refers[$arrayKey] = 1;
4537 if ( isset( $refers[$legacyArrayKey] ) ) {
4538 $refers[$legacyArrayKey]++
;
4540 $refers[$legacyArrayKey] = 1;
4543 # Don't number the heading if it is the only one (looks silly)
4544 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4545 # the two are different if the line contains a link
4546 $headline = Html
::element(
4548 array( 'class' => 'mw-headline-number' ),
4550 ) . ' ' . $headline;
4553 # Create the anchor for linking from the TOC to the section
4554 $anchor = $safeHeadline;
4555 $legacyAnchor = $legacyHeadline;
4556 if ( $refers[$arrayKey] > 1 ) {
4557 $anchor .= '_' . $refers[$arrayKey];
4559 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4560 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4562 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4563 $toc .= Linker
::tocLine( $anchor, $tocline,
4564 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4567 # Add the section to the section tree
4568 # Find the DOM node for this header
4569 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4570 while ( $node && !$noOffset ) {
4571 if ( $node->getName() === 'h' ) {
4572 $bits = $node->splitHeading();
4573 if ( $bits['i'] == $sectionIndex ) {
4577 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4578 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4579 $node = $node->getNextSibling();
4582 'toclevel' => $toclevel,
4585 'number' => $numbering,
4586 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4587 'fromtitle' => $titleText,
4588 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4589 'anchor' => $anchor,
4592 # give headline the correct <h#> tag
4593 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4594 // Output edit section links as markers with styles that can be customized by skins
4595 if ( $isTemplate ) {
4596 # Put a T flag in the section identifier, to indicate to extractSections()
4597 # that sections inside <includeonly> should be counted.
4598 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4600 $editlinkArgs = array(
4601 $this->mTitle
->getPrefixedText(),
4606 // We use a bit of pesudo-xml for editsection markers. The
4607 // language converter is run later on. Using a UNIQ style marker
4608 // leads to the converter screwing up the tokens when it
4609 // converts stuff. And trying to insert strip tags fails too. At
4610 // this point all real inputted tags have already been escaped,
4611 // so we don't have to worry about a user trying to input one of
4612 // these markers directly. We use a page and section attribute
4613 // to stop the language converter from converting these
4614 // important bits of data, but put the headline hint inside a
4615 // content block because the language converter is supposed to
4616 // be able to convert that piece of data.
4617 $editlink = '<mw:editsection page="' . htmlspecialchars( $editlinkArgs[0] );
4618 $editlink .= '" section="' . htmlspecialchars( $editlinkArgs[1] ) . '"';
4619 if ( isset( $editlinkArgs[2] ) ) {
4620 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4627 $head[$headlineCount] = Linker
::makeHeadline( $level,
4628 $matches['attrib'][$headlineCount], $anchor, $headline,
4629 $editlink, $legacyAnchor );
4634 $this->setOutputType( $oldType );
4636 # Never ever show TOC if no headers
4637 if ( $numVisible < 1 ) {
4642 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4643 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4645 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4646 $this->mOutput
->setTOCHTML( $toc );
4647 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4648 $this->mOutput
->addModules( 'mediawiki.toc' );
4652 $this->mOutput
->setSections( $tocraw );
4655 # split up and insert constructed headlines
4656 $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text );
4659 // build an array of document sections
4660 $sections = array();
4661 foreach ( $blocks as $block ) {
4662 // $head is zero-based, sections aren't.
4663 if ( empty( $head[$i - 1] ) ) {
4664 $sections[$i] = $block;
4666 $sections[$i] = $head[$i - 1] . $block;
4670 * Send a hook, one per section.
4671 * The idea here is to be able to make section-level DIVs, but to do so in a
4672 * lower-impact, more correct way than r50769
4675 * $section : the section number
4676 * &$sectionContent : ref to the content of the section
4677 * $showEditLinks : boolean describing whether this section has an edit link
4679 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4684 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4685 // append the TOC at the beginning
4686 // Top anchor now in skin
4687 $sections[0] = $sections[0] . $toc . "\n";
4690 $full .= join( '', $sections );
4692 if ( $this->mForceTocPosition
) {
4693 return str_replace( '<!--MWTOC-->', $toc, $full );
4700 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4701 * conversion, substitting signatures, {{subst:}} templates, etc.
4703 * @param string $text The text to transform
4704 * @param Title $title The Title object for the current article
4705 * @param User $user The User object describing the current user
4706 * @param ParserOptions $options Parsing options
4707 * @param bool $clearState Whether to clear the parser state first
4708 * @return string The altered wiki markup
4710 public function preSaveTransform( $text, Title
$title, User
$user,
4711 ParserOptions
$options, $clearState = true
4713 if ( $clearState ) {
4714 $magicScopeVariable = $this->lock();
4716 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4717 $this->setUser( $user );
4722 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4723 if ( $options->getPreSaveTransform() ) {
4724 $text = $this->pstPass2( $text, $user );
4726 $text = $this->mStripState
->unstripBoth( $text );
4728 $this->setUser( null ); #Reset
4734 * Pre-save transform helper function
4736 * @param string $text
4741 private function pstPass2( $text, $user ) {
4744 # Note: This is the timestamp saved as hardcoded wikitext to
4745 # the database, we use $wgContLang here in order to give
4746 # everyone the same signature and use the default one rather
4747 # than the one selected in each user's preferences.
4748 # (see also bug 12815)
4749 $ts = $this->mOptions
->getTimestamp();
4750 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4751 $ts = $timestamp->format( 'YmdHis' );
4752 $tzMsg = $timestamp->format( 'T' ); # might vary on DST changeover!
4754 # Allow translation of timezones through wiki. format() can return
4755 # whatever crap the system uses, localised or not, so we cannot
4756 # ship premade translations.
4757 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4758 $msg = wfMessage( $key )->inContentLanguage();
4759 if ( $msg->exists() ) {
4760 $tzMsg = $msg->text();
4763 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4765 # Variable replacement
4766 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4767 $text = $this->replaceVariables( $text );
4769 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4770 # which may corrupt this parser instance via its wfMessage()->text() call-
4773 $sigText = $this->getUserSig( $user );
4774 $text = strtr( $text, array(
4776 '~~~~' => "$sigText $d",
4780 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4781 $tc = '[' . Title
::legalChars() . ']';
4782 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4784 // [[ns:page (context)|]]
4785 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4786 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4787 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4788 // [[ns:page (context), context|]] (using either single or double-width comma)
4789 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4790 // [[|page]] (reverse pipe trick: add context from page title)
4791 $p2 = "/\[\[\\|($tc+)]]/";
4793 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4794 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4795 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4796 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4798 $t = $this->mTitle
->getText();
4800 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4801 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4802 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4803 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4805 # if there's no context, don't bother duplicating the title
4806 $text = preg_replace( $p2, '[[\\1]]', $text );
4809 # Trim trailing whitespace
4810 $text = rtrim( $text );
4816 * Fetch the user's signature text, if any, and normalize to
4817 * validated, ready-to-insert wikitext.
4818 * If you have pre-fetched the nickname or the fancySig option, you can
4819 * specify them here to save a database query.
4820 * Do not reuse this parser instance after calling getUserSig(),
4821 * as it may have changed if it's the $wgParser.
4824 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4825 * @param bool|null $fancySig whether the nicknname is the complete signature
4826 * or null to use default value
4829 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4830 global $wgMaxSigChars;
4832 $username = $user->getName();
4834 # If not given, retrieve from the user object.
4835 if ( $nickname === false ) {
4836 $nickname = $user->getOption( 'nickname' );
4839 if ( is_null( $fancySig ) ) {
4840 $fancySig = $user->getBoolOption( 'fancysig' );
4843 $nickname = $nickname == null ?
$username : $nickname;
4845 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4846 $nickname = $username;
4847 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4848 } elseif ( $fancySig !== false ) {
4849 # Sig. might contain markup; validate this
4850 if ( $this->validateSig( $nickname ) !== false ) {
4851 # Validated; clean up (if needed) and return it
4852 return $this->cleanSig( $nickname, true );
4854 # Failed to validate; fall back to the default
4855 $nickname = $username;
4856 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4860 # Make sure nickname doesnt get a sig in a sig
4861 $nickname = self
::cleanSigInSig( $nickname );
4863 # If we're still here, make it a link to the user page
4864 $userText = wfEscapeWikiText( $username );
4865 $nickText = wfEscapeWikiText( $nickname );
4866 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4868 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4869 ->title( $this->getTitle() )->text();
4873 * Check that the user's signature contains no bad XML
4875 * @param string $text
4876 * @return string|bool An expanded string, or false if invalid.
4878 function validateSig( $text ) {
4879 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4883 * Clean up signature text
4885 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4886 * 2) Substitute all transclusions
4888 * @param string $text
4889 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4890 * @return string Signature text
4892 public function cleanSig( $text, $parsing = false ) {
4895 $magicScopeVariable = $this->lock();
4896 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4899 # Option to disable this feature
4900 if ( !$this->mOptions
->getCleanSignatures() ) {
4904 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4905 # => Move this logic to braceSubstitution()
4906 $substWord = MagicWord
::get( 'subst' );
4907 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4908 $substText = '{{' . $substWord->getSynonym( 0 );
4910 $text = preg_replace( $substRegex, $substText, $text );
4911 $text = self
::cleanSigInSig( $text );
4912 $dom = $this->preprocessToDom( $text );
4913 $frame = $this->getPreprocessor()->newFrame();
4914 $text = $frame->expand( $dom );
4917 $text = $this->mStripState
->unstripBoth( $text );
4924 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4926 * @param string $text
4927 * @return string Signature text with /~{3,5}/ removed
4929 public static function cleanSigInSig( $text ) {
4930 $text = preg_replace( '/~{3,5}/', '', $text );
4935 * Set up some variables which are usually set up in parse()
4936 * so that an external function can call some class members with confidence
4938 * @param Title|null $title
4939 * @param ParserOptions $options
4940 * @param int $outputType
4941 * @param bool $clearState
4943 public function startExternalParse( Title
$title = null, ParserOptions
$options,
4944 $outputType, $clearState = true
4946 $this->startParse( $title, $options, $outputType, $clearState );
4950 * @param Title|null $title
4951 * @param ParserOptions $options
4952 * @param int $outputType
4953 * @param bool $clearState
4955 private function startParse( Title
$title = null, ParserOptions
$options,
4956 $outputType, $clearState = true
4958 $this->setTitle( $title );
4959 $this->mOptions
= $options;
4960 $this->setOutputType( $outputType );
4961 if ( $clearState ) {
4962 $this->clearState();
4967 * Wrapper for preprocess()
4969 * @param string $text The text to preprocess
4970 * @param ParserOptions $options Options
4971 * @param Title|null $title Title object or null to use $wgTitle
4974 public function transformMsg( $text, $options, $title = null ) {
4975 static $executing = false;
4977 # Guard against infinite recursion
4983 wfProfileIn( __METHOD__
);
4989 $text = $this->preprocess( $text, $title, $options );
4992 wfProfileOut( __METHOD__
);
4997 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4998 * The callback should have the following form:
4999 * function myParserHook( $text, $params, $parser, $frame ) { ... }
5001 * Transform and return $text. Use $parser for any required context, e.g. use
5002 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
5004 * Hooks may return extended information by returning an array, of which the
5005 * first numbered element (index 0) must be the return string, and all other
5006 * entries are extracted into local variables within an internal function
5007 * in the Parser class.
5009 * This interface (introduced r61913) appears to be undocumented, but
5010 * 'markerName' is used by some core tag hooks to override which strip
5011 * array their results are placed in. **Use great caution if attempting
5012 * this interface, as it is not documented and injudicious use could smash
5013 * private variables.**
5015 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5016 * @param mixed $callback The callback function (and object) to use for the tag
5017 * @throws MWException
5018 * @return mixed|null The old value of the mTagHooks array associated with the hook
5020 public function setHook( $tag, $callback ) {
5021 $tag = strtolower( $tag );
5022 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5023 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
5025 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
5026 $this->mTagHooks
[$tag] = $callback;
5027 if ( !in_array( $tag, $this->mStripList
) ) {
5028 $this->mStripList
[] = $tag;
5035 * As setHook(), but letting the contents be parsed.
5037 * Transparent tag hooks are like regular XML-style tag hooks, except they
5038 * operate late in the transformation sequence, on HTML instead of wikitext.
5040 * This is probably obsoleted by things dealing with parser frames?
5041 * The only extension currently using it is geoserver.
5044 * @todo better document or deprecate this
5046 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5047 * @param mixed $callback The callback function (and object) to use for the tag
5048 * @throws MWException
5049 * @return mixed|null The old value of the mTagHooks array associated with the hook
5051 function setTransparentTagHook( $tag, $callback ) {
5052 $tag = strtolower( $tag );
5053 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5054 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
5056 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
5057 $this->mTransparentTagHooks
[$tag] = $callback;
5063 * Remove all tag hooks
5065 function clearTagHooks() {
5066 $this->mTagHooks
= array();
5067 $this->mFunctionTagHooks
= array();
5068 $this->mStripList
= $this->mDefaultStripList
;
5072 * Create a function, e.g. {{sum:1|2|3}}
5073 * The callback function should have the form:
5074 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
5076 * Or with SFH_OBJECT_ARGS:
5077 * function myParserFunction( $parser, $frame, $args ) { ... }
5079 * The callback may either return the text result of the function, or an array with the text
5080 * in element 0, and a number of flags in the other elements. The names of the flags are
5081 * specified in the keys. Valid flags are:
5082 * found The text returned is valid, stop processing the template. This
5084 * nowiki Wiki markup in the return value should be escaped
5085 * isHTML The returned text is HTML, armour it against wikitext transformation
5087 * @param string $id The magic word ID
5088 * @param mixed $callback The callback function (and object) to use
5089 * @param int $flags A combination of the following flags:
5090 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
5092 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
5093 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
5094 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
5095 * the arguments, and to control the way they are expanded.
5097 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
5098 * arguments, for instance:
5099 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
5101 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
5102 * future versions. Please call $frame->expand() on it anyway so that your code keeps
5103 * working if/when this is changed.
5105 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
5108 * Please read the documentation in includes/parser/Preprocessor.php for more information
5109 * about the methods available in PPFrame and PPNode.
5111 * @throws MWException
5112 * @return string|callable The old callback function for this name, if any
5114 public function setFunctionHook( $id, $callback, $flags = 0 ) {
5117 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
5118 $this->mFunctionHooks
[$id] = array( $callback, $flags );
5120 # Add to function cache
5121 $mw = MagicWord
::get( $id );
5123 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
5126 $synonyms = $mw->getSynonyms();
5127 $sensitive = intval( $mw->isCaseSensitive() );
5129 foreach ( $synonyms as $syn ) {
5131 if ( !$sensitive ) {
5132 $syn = $wgContLang->lc( $syn );
5135 if ( !( $flags & SFH_NO_HASH
) ) {
5138 # Remove trailing colon
5139 if ( substr( $syn, -1, 1 ) === ':' ) {
5140 $syn = substr( $syn, 0, -1 );
5142 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
5148 * Get all registered function hook identifiers
5152 function getFunctionHooks() {
5153 return array_keys( $this->mFunctionHooks
);
5157 * Create a tag function, e.g. "<test>some stuff</test>".
5158 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5159 * Unlike parser functions, their content is not preprocessed.
5160 * @param string $tag
5161 * @param callable $callback
5163 * @throws MWException
5166 function setFunctionTagHook( $tag, $callback, $flags ) {
5167 $tag = strtolower( $tag );
5168 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5169 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5171 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
5172 $this->mFunctionTagHooks
[$tag] : null;
5173 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
5175 if ( !in_array( $tag, $this->mStripList
) ) {
5176 $this->mStripList
[] = $tag;
5183 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
5184 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5185 * Placeholders created in Skin::makeLinkObj()
5187 * @param string $text
5188 * @param int $options
5190 * @return array Array of link CSS classes, indexed by PDBK.
5192 function replaceLinkHolders( &$text, $options = 0 ) {
5193 return $this->mLinkHolders
->replace( $text );
5197 * Replace "<!--LINK-->" link placeholders with plain text of links
5198 * (not HTML-formatted).
5200 * @param string $text
5203 function replaceLinkHoldersText( $text ) {
5204 return $this->mLinkHolders
->replaceText( $text );
5208 * Renders an image gallery from a text with one line per image.
5209 * text labels may be given by using |-style alternative text. E.g.
5210 * Image:one.jpg|The number "1"
5211 * Image:tree.jpg|A tree
5212 * given as text will return the HTML of a gallery with two images,
5213 * labeled 'The number "1"' and
5216 * @param string $text
5217 * @param array $params
5218 * @return string HTML
5220 function renderImageGallery( $text, $params ) {
5221 wfProfileIn( __METHOD__
);
5224 if ( isset( $params['mode'] ) ) {
5225 $mode = $params['mode'];
5229 $ig = ImageGalleryBase
::factory( $mode );
5230 } catch ( MWException
$e ) {
5231 // If invalid type set, fallback to default.
5232 $ig = ImageGalleryBase
::factory( false );
5235 $ig->setContextTitle( $this->mTitle
);
5236 $ig->setShowBytes( false );
5237 $ig->setShowFilename( false );
5238 $ig->setParser( $this );
5239 $ig->setHideBadImages();
5240 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
5242 if ( isset( $params['showfilename'] ) ) {
5243 $ig->setShowFilename( true );
5245 $ig->setShowFilename( false );
5247 if ( isset( $params['caption'] ) ) {
5248 $caption = $params['caption'];
5249 $caption = htmlspecialchars( $caption );
5250 $caption = $this->replaceInternalLinks( $caption );
5251 $ig->setCaptionHtml( $caption );
5253 if ( isset( $params['perrow'] ) ) {
5254 $ig->setPerRow( $params['perrow'] );
5256 if ( isset( $params['widths'] ) ) {
5257 $ig->setWidths( $params['widths'] );
5259 if ( isset( $params['heights'] ) ) {
5260 $ig->setHeights( $params['heights'] );
5262 $ig->setAdditionalOptions( $params );
5264 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5266 $lines = StringUtils
::explode( "\n", $text );
5267 foreach ( $lines as $line ) {
5268 # match lines like these:
5269 # Image:someimage.jpg|This is some image
5271 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5273 if ( count( $matches ) == 0 ) {
5277 if ( strpos( $matches[0], '%' ) !== false ) {
5278 $matches[1] = rawurldecode( $matches[1] );
5280 $title = Title
::newFromText( $matches[1], NS_FILE
);
5281 if ( is_null( $title ) ) {
5282 # Bogus title. Ignore these so we don't bomb out later.
5286 # We need to get what handler the file uses, to figure out parameters.
5287 # Note, a hook can overide the file name, and chose an entirely different
5288 # file (which potentially could be of a different type and have different handler).
5291 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5292 array( $this, $title, &$options, &$descQuery ) );
5293 # Don't register it now, as ImageGallery does that later.
5294 $file = $this->fetchFileNoRegister( $title, $options );
5295 $handler = $file ?
$file->getHandler() : false;
5297 wfProfileIn( __METHOD__
. '-getMagicWord' );
5299 'img_alt' => 'gallery-internal-alt',
5300 'img_link' => 'gallery-internal-link',
5303 $paramMap = $paramMap +
$handler->getParamMap();
5304 // We don't want people to specify per-image widths.
5305 // Additionally the width parameter would need special casing anyhow.
5306 unset( $paramMap['img_width'] );
5309 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5310 wfProfileOut( __METHOD__
. '-getMagicWord' );
5315 $handlerOptions = array();
5316 if ( isset( $matches[3] ) ) {
5317 // look for an |alt= definition while trying not to break existing
5318 // captions with multiple pipes (|) in it, until a more sensible grammar
5319 // is defined for images in galleries
5321 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5322 // splitting on '|' is a bit odd, and different from makeImage.
5323 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5324 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
5326 foreach ( $parameterMatches as $parameterMatch ) {
5327 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5329 $paramName = $paramMap[$magicName];
5331 switch ( $paramName ) {
5332 case 'gallery-internal-alt':
5333 $alt = $this->stripAltText( $match, false );
5335 case 'gallery-internal-link':
5336 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5337 $chars = self
::EXT_LINK_URL_CLASS
;
5338 $prots = $this->mUrlProtocols
;
5339 //check to see if link matches an absolute url, if not then it must be a wiki link.
5340 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5343 $localLinkTitle = Title
::newFromText( $linkValue );
5344 if ( $localLinkTitle !== null ) {
5345 $link = $localLinkTitle->getLinkURL();
5350 // Must be a handler specific parameter.
5351 if ( $handler->validateParam( $paramName, $match ) ) {
5352 $handlerOptions[$paramName] = $match;
5354 // Guess not. Append it to the caption.
5355 wfDebug( "$parameterMatch failed parameter validation\n" );
5356 $label .= '|' . $parameterMatch;
5361 // concatenate all other pipes
5362 $label .= '|' . $parameterMatch;
5365 // remove the first pipe
5366 $label = substr( $label, 1 );
5369 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5371 $html = $ig->toHTML();
5372 wfProfileOut( __METHOD__
);
5377 * @param string $handler
5380 function getImageParams( $handler ) {
5382 $handlerClass = get_class( $handler );
5386 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5387 # Initialise static lists
5388 static $internalParamNames = array(
5389 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5390 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5391 'bottom', 'text-bottom' ),
5392 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5393 'upright', 'border', 'link', 'alt', 'class' ),
5395 static $internalParamMap;
5396 if ( !$internalParamMap ) {
5397 $internalParamMap = array();
5398 foreach ( $internalParamNames as $type => $names ) {
5399 foreach ( $names as $name ) {
5400 $magicName = str_replace( '-', '_', "img_$name" );
5401 $internalParamMap[$magicName] = array( $type, $name );
5406 # Add handler params
5407 $paramMap = $internalParamMap;
5409 $handlerParamMap = $handler->getParamMap();
5410 foreach ( $handlerParamMap as $magic => $paramName ) {
5411 $paramMap[$magic] = array( 'handler', $paramName );
5414 $this->mImageParams
[$handlerClass] = $paramMap;
5415 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5417 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5421 * Parse image options text and use it to make an image
5423 * @param Title $title
5424 * @param string $options
5425 * @param LinkHolderArray|bool $holders
5426 * @return string HTML
5428 function makeImage( $title, $options, $holders = false ) {
5429 # Check if the options text is of the form "options|alt text"
5431 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5432 # * left no resizing, just left align. label is used for alt= only
5433 # * right same, but right aligned
5434 # * none same, but not aligned
5435 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5436 # * center center the image
5437 # * frame Keep original image size, no magnify-button.
5438 # * framed Same as "frame"
5439 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5440 # * upright reduce width for upright images, rounded to full __0 px
5441 # * border draw a 1px border around the image
5442 # * alt Text for HTML alt attribute (defaults to empty)
5443 # * class Set a class for img node
5444 # * link Set the target of the image link. Can be external, interwiki, or local
5445 # vertical-align values (no % or length right now):
5455 $parts = StringUtils
::explode( "|", $options );
5457 # Give extensions a chance to select the file revision for us
5460 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5461 array( $this, $title, &$options, &$descQuery ) );
5462 # Fetch and register the file (file title may be different via hooks)
5463 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5466 $handler = $file ?
$file->getHandler() : false;
5468 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5471 $this->addTrackingCategory( 'broken-file-category' );
5474 # Process the input parameters
5476 $params = array( 'frame' => array(), 'handler' => array(),
5477 'horizAlign' => array(), 'vertAlign' => array() );
5478 $seenformat = false;
5479 foreach ( $parts as $part ) {
5480 $part = trim( $part );
5481 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5483 if ( isset( $paramMap[$magicName] ) ) {
5484 list( $type, $paramName ) = $paramMap[$magicName];
5486 # Special case; width and height come in one variable together
5487 if ( $type === 'handler' && $paramName === 'width' ) {
5488 $parsedWidthParam = $this->parseWidthParam( $value );
5489 if ( isset( $parsedWidthParam['width'] ) ) {
5490 $width = $parsedWidthParam['width'];
5491 if ( $handler->validateParam( 'width', $width ) ) {
5492 $params[$type]['width'] = $width;
5496 if ( isset( $parsedWidthParam['height'] ) ) {
5497 $height = $parsedWidthParam['height'];
5498 if ( $handler->validateParam( 'height', $height ) ) {
5499 $params[$type]['height'] = $height;
5503 # else no validation -- bug 13436
5505 if ( $type === 'handler' ) {
5506 # Validate handler parameter
5507 $validated = $handler->validateParam( $paramName, $value );
5509 # Validate internal parameters
5510 switch ( $paramName ) {
5514 # @todo FIXME: Possibly check validity here for
5515 # manualthumb? downstream behavior seems odd with
5516 # missing manual thumbs.
5518 $value = $this->stripAltText( $value, $holders );
5521 $chars = self
::EXT_LINK_URL_CLASS
;
5522 $prots = $this->mUrlProtocols
;
5523 if ( $value === '' ) {
5524 $paramName = 'no-link';
5527 } elseif ( preg_match( "/^(?i)$prots/", $value ) ) {
5528 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5529 $paramName = 'link-url';
5530 $this->mOutput
->addExternalLink( $value );
5531 if ( $this->mOptions
->getExternalLinkTarget() ) {
5532 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5537 $linkTitle = Title
::newFromText( $value );
5539 $paramName = 'link-title';
5540 $value = $linkTitle;
5541 $this->mOutput
->addLink( $linkTitle );
5549 // use first appearing option, discard others.
5550 $validated = ! $seenformat;
5554 # Most other things appear to be empty or numeric...
5555 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5560 $params[$type][$paramName] = $value;
5564 if ( !$validated ) {
5569 # Process alignment parameters
5570 if ( $params['horizAlign'] ) {
5571 $params['frame']['align'] = key( $params['horizAlign'] );
5573 if ( $params['vertAlign'] ) {
5574 $params['frame']['valign'] = key( $params['vertAlign'] );
5577 $params['frame']['caption'] = $caption;
5579 # Will the image be presented in a frame, with the caption below?
5580 $imageIsFramed = isset( $params['frame']['frame'] )
5581 ||
isset( $params['frame']['framed'] )
5582 ||
isset( $params['frame']['thumbnail'] )
5583 ||
isset( $params['frame']['manualthumb'] );
5585 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5586 # came to also set the caption, ordinary text after the image -- which
5587 # makes no sense, because that just repeats the text multiple times in
5588 # screen readers. It *also* came to set the title attribute.
5590 # Now that we have an alt attribute, we should not set the alt text to
5591 # equal the caption: that's worse than useless, it just repeats the
5592 # text. This is the framed/thumbnail case. If there's no caption, we
5593 # use the unnamed parameter for alt text as well, just for the time be-
5594 # ing, if the unnamed param is set and the alt param is not.
5596 # For the future, we need to figure out if we want to tweak this more,
5597 # e.g., introducing a title= parameter for the title; ignoring the un-
5598 # named parameter entirely for images without a caption; adding an ex-
5599 # plicit caption= parameter and preserving the old magic unnamed para-
5601 if ( $imageIsFramed ) { # Framed image
5602 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5603 # No caption or alt text, add the filename as the alt text so
5604 # that screen readers at least get some description of the image
5605 $params['frame']['alt'] = $title->getText();
5607 # Do not set $params['frame']['title'] because tooltips don't make sense
5609 } else { # Inline image
5610 if ( !isset( $params['frame']['alt'] ) ) {
5611 # No alt text, use the "caption" for the alt text
5612 if ( $caption !== '' ) {
5613 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5615 # No caption, fall back to using the filename for the
5617 $params['frame']['alt'] = $title->getText();
5620 # Use the "caption" for the tooltip text
5621 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5624 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5626 # Linker does the rest
5627 $time = isset( $options['time'] ) ?
$options['time'] : false;
5628 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5629 $time, $descQuery, $this->mOptions
->getThumbSize() );
5631 # Give the handler a chance to modify the parser object
5633 $handler->parserTransformHook( $this, $file );
5640 * @param string $caption
5641 * @param LinkHolderArray|bool $holders
5642 * @return mixed|string
5644 protected function stripAltText( $caption, $holders ) {
5645 # Strip bad stuff out of the title (tooltip). We can't just use
5646 # replaceLinkHoldersText() here, because if this function is called
5647 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5649 $tooltip = $holders->replaceText( $caption );
5651 $tooltip = $this->replaceLinkHoldersText( $caption );
5654 # make sure there are no placeholders in thumbnail attributes
5655 # that are later expanded to html- so expand them now and
5657 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5658 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5664 * Set a flag in the output object indicating that the content is dynamic and
5665 * shouldn't be cached.
5667 function disableCache() {
5668 wfDebug( "Parser output marked as uncacheable.\n" );
5669 if ( !$this->mOutput
) {
5670 throw new MWException( __METHOD__
.
5671 " can only be called when actually parsing something" );
5673 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5674 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5678 * Callback from the Sanitizer for expanding items found in HTML attribute
5679 * values, so they can be safely tested and escaped.
5681 * @param string $text
5682 * @param bool|PPFrame $frame
5685 function attributeStripCallback( &$text, $frame = false ) {
5686 $text = $this->replaceVariables( $text, $frame );
5687 $text = $this->mStripState
->unstripBoth( $text );
5696 function getTags() {
5698 array_keys( $this->mTransparentTagHooks
),
5699 array_keys( $this->mTagHooks
),
5700 array_keys( $this->mFunctionTagHooks
)
5705 * Replace transparent tags in $text with the values given by the callbacks.
5707 * Transparent tag hooks are like regular XML-style tag hooks, except they
5708 * operate late in the transformation sequence, on HTML instead of wikitext.
5710 * @param string $text
5714 function replaceTransparentTags( $text ) {
5716 $elements = array_keys( $this->mTransparentTagHooks
);
5717 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5718 $replacements = array();
5720 foreach ( $matches as $marker => $data ) {
5721 list( $element, $content, $params, $tag ) = $data;
5722 $tagName = strtolower( $element );
5723 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5724 $output = call_user_func_array(
5725 $this->mTransparentTagHooks
[$tagName],
5726 array( $content, $params, $this )
5731 $replacements[$marker] = $output;
5733 return strtr( $text, $replacements );
5737 * Break wikitext input into sections, and either pull or replace
5738 * some particular section's text.
5740 * External callers should use the getSection and replaceSection methods.
5742 * @param string $text Page wikitext
5743 * @param string|number $sectionId A section identifier string of the form:
5744 * "<flag1> - <flag2> - ... - <section number>"
5746 * Currently the only recognised flag is "T", which means the target section number
5747 * was derived during a template inclusion parse, in other words this is a template
5748 * section edit link. If no flags are given, it was an ordinary section edit link.
5749 * This flag is required to avoid a section numbering mismatch when a section is
5750 * enclosed by "<includeonly>" (bug 6563).
5752 * The section number 0 pulls the text before the first heading; other numbers will
5753 * pull the given section along with its lower-level subsections. If the section is
5754 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5756 * Section 0 is always considered to exist, even if it only contains the empty
5757 * string. If $text is the empty string and section 0 is replaced, $newText is
5760 * @param string $mode One of "get" or "replace"
5761 * @param string $newText Replacement text for section data.
5762 * @return string For "get", the extracted section text.
5763 * for "replace", the whole page with the section replaced.
5765 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5766 global $wgTitle; # not generally used but removes an ugly failure mode
5768 $magicScopeVariable = $this->lock();
5769 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5771 $frame = $this->getPreprocessor()->newFrame();
5773 # Process section extraction flags
5775 $sectionParts = explode( '-', $sectionId );
5776 $sectionIndex = array_pop( $sectionParts );
5777 foreach ( $sectionParts as $part ) {
5778 if ( $part === 'T' ) {
5779 $flags |
= self
::PTD_FOR_INCLUSION
;
5783 # Check for empty input
5784 if ( strval( $text ) === '' ) {
5785 # Only sections 0 and T-0 exist in an empty document
5786 if ( $sectionIndex == 0 ) {
5787 if ( $mode === 'get' ) {
5793 if ( $mode === 'get' ) {
5801 # Preprocess the text
5802 $root = $this->preprocessToDom( $text, $flags );
5804 # <h> nodes indicate section breaks
5805 # They can only occur at the top level, so we can find them by iterating the root's children
5806 $node = $root->getFirstChild();
5808 # Find the target section
5809 if ( $sectionIndex == 0 ) {
5810 # Section zero doesn't nest, level=big
5811 $targetLevel = 1000;
5814 if ( $node->getName() === 'h' ) {
5815 $bits = $node->splitHeading();
5816 if ( $bits['i'] == $sectionIndex ) {
5817 $targetLevel = $bits['level'];
5821 if ( $mode === 'replace' ) {
5822 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5824 $node = $node->getNextSibling();
5830 if ( $mode === 'get' ) {
5837 # Find the end of the section, including nested sections
5839 if ( $node->getName() === 'h' ) {
5840 $bits = $node->splitHeading();
5841 $curLevel = $bits['level'];
5842 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5846 if ( $mode === 'get' ) {
5847 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5849 $node = $node->getNextSibling();
5852 # Write out the remainder (in replace mode only)
5853 if ( $mode === 'replace' ) {
5854 # Output the replacement text
5855 # Add two newlines on -- trailing whitespace in $newText is conventionally
5856 # stripped by the editor, so we need both newlines to restore the paragraph gap
5857 # Only add trailing whitespace if there is newText
5858 if ( $newText != "" ) {
5859 $outText .= $newText . "\n\n";
5863 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5864 $node = $node->getNextSibling();
5868 if ( is_string( $outText ) ) {
5869 # Re-insert stripped tags
5870 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5877 * This function returns the text of a section, specified by a number ($section).
5878 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5879 * the first section before any such heading (section 0).
5881 * If a section contains subsections, these are also returned.
5883 * @param string $text Text to look in
5884 * @param string|number $sectionId Section identifier as a number or string
5885 * (e.g. 0, 1 or 'T-1').
5886 * @param string $defaultText Default to return if section is not found
5888 * @return string Text of the requested section
5890 public function getSection( $text, $sectionId, $defaultText = '' ) {
5891 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5895 * This function returns $oldtext after the content of the section
5896 * specified by $section has been replaced with $text. If the target
5897 * section does not exist, $oldtext is returned unchanged.
5899 * @param string $oldText Former text of the article
5900 * @param string|number $sectionId Section identifier as a number or string
5901 * (e.g. 0, 1 or 'T-1').
5902 * @param string $newText Replacing text
5904 * @return string Modified text
5906 public function replaceSection( $oldText, $sectionId, $newText ) {
5907 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5911 * Get the ID of the revision we are parsing
5915 function getRevisionId() {
5916 return $this->mRevisionId
;
5920 * Get the revision object for $this->mRevisionId
5922 * @return Revision|null Either a Revision object or null
5923 * @since 1.23 (public since 1.23)
5925 public function getRevisionObject() {
5926 if ( !is_null( $this->mRevisionObject
) ) {
5927 return $this->mRevisionObject
;
5929 if ( is_null( $this->mRevisionId
) ) {
5933 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5934 return $this->mRevisionObject
;
5938 * Get the timestamp associated with the current revision, adjusted for
5939 * the default server-local timestamp
5942 function getRevisionTimestamp() {
5943 if ( is_null( $this->mRevisionTimestamp
) ) {
5944 wfProfileIn( __METHOD__
);
5948 $revObject = $this->getRevisionObject();
5949 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5951 # The cryptic '' timezone parameter tells to use the site-default
5952 # timezone offset instead of the user settings.
5954 # Since this value will be saved into the parser cache, served
5955 # to other users, and potentially even used inside links and such,
5956 # it needs to be consistent for all visitors.
5957 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5959 wfProfileOut( __METHOD__
);
5961 return $this->mRevisionTimestamp
;
5965 * Get the name of the user that edited the last revision
5967 * @return string User name
5969 function getRevisionUser() {
5970 if ( is_null( $this->mRevisionUser
) ) {
5971 $revObject = $this->getRevisionObject();
5973 # if this template is subst: the revision id will be blank,
5974 # so just use the current user's name
5976 $this->mRevisionUser
= $revObject->getUserText();
5977 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5978 $this->mRevisionUser
= $this->getUser()->getName();
5981 return $this->mRevisionUser
;
5985 * Get the size of the revision
5987 * @return int|null Revision size
5989 function getRevisionSize() {
5990 if ( is_null( $this->mRevisionSize
) ) {
5991 $revObject = $this->getRevisionObject();
5993 # if this variable is subst: the revision id will be blank,
5994 # so just use the parser input size, because the own substituation
5995 # will change the size.
5997 $this->mRevisionSize
= $revObject->getSize();
5998 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5999 $this->mRevisionSize
= $this->mInputSize
;
6002 return $this->mRevisionSize
;
6006 * Mutator for $mDefaultSort
6008 * @param string $sort New value
6010 public function setDefaultSort( $sort ) {
6011 $this->mDefaultSort
= $sort;
6012 $this->mOutput
->setProperty( 'defaultsort', $sort );
6016 * Accessor for $mDefaultSort
6017 * Will use the empty string if none is set.
6019 * This value is treated as a prefix, so the
6020 * empty string is equivalent to sorting by
6025 public function getDefaultSort() {
6026 if ( $this->mDefaultSort
!== false ) {
6027 return $this->mDefaultSort
;
6034 * Accessor for $mDefaultSort
6035 * Unlike getDefaultSort(), will return false if none is set
6037 * @return string|bool
6039 public function getCustomDefaultSort() {
6040 return $this->mDefaultSort
;
6044 * Try to guess the section anchor name based on a wikitext fragment
6045 * presumably extracted from a heading, for example "Header" from
6048 * @param string $text
6052 public function guessSectionNameFromWikiText( $text ) {
6053 # Strip out wikitext links(they break the anchor)
6054 $text = $this->stripSectionName( $text );
6055 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6056 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
6060 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6061 * instead. For use in redirects, since IE6 interprets Redirect: headers
6062 * as something other than UTF-8 (apparently?), resulting in breakage.
6064 * @param string $text The section name
6065 * @return string An anchor
6067 public function guessLegacySectionNameFromWikiText( $text ) {
6068 # Strip out wikitext links(they break the anchor)
6069 $text = $this->stripSectionName( $text );
6070 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6071 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
6075 * Strips a text string of wikitext for use in a section anchor
6077 * Accepts a text string and then removes all wikitext from the
6078 * string and leaves only the resultant text (i.e. the result of
6079 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6080 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6081 * to create valid section anchors by mimicing the output of the
6082 * parser when headings are parsed.
6084 * @param string $text Text string to be stripped of wikitext
6085 * for use in a Section anchor
6086 * @return string Filtered text string
6088 public function stripSectionName( $text ) {
6089 # Strip internal link markup
6090 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6091 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6093 # Strip external link markup
6094 # @todo FIXME: Not tolerant to blank link text
6095 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6096 # on how many empty links there are on the page - need to figure that out.
6097 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6099 # Parse wikitext quotes (italics & bold)
6100 $text = $this->doQuotes( $text );
6103 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
6108 * strip/replaceVariables/unstrip for preprocessor regression testing
6110 * @param string $text
6111 * @param Title $title
6112 * @param ParserOptions $options
6113 * @param int $outputType
6117 function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
6118 $magicScopeVariable = $this->lock();
6119 $this->startParse( $title, $options, $outputType, true );
6121 $text = $this->replaceVariables( $text );
6122 $text = $this->mStripState
->unstripBoth( $text );
6123 $text = Sanitizer
::removeHTMLtags( $text );
6128 * @param string $text
6129 * @param Title $title
6130 * @param ParserOptions $options
6133 function testPst( $text, Title
$title, ParserOptions
$options ) {
6134 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6138 * @param string $text
6139 * @param Title $title
6140 * @param ParserOptions $options
6143 function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
6144 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
6148 * Call a callback function on all regions of the given text that are not
6149 * inside strip markers, and replace those regions with the return value
6150 * of the callback. For example, with input:
6154 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6155 * two strings will be replaced with the value returned by the callback in
6159 * @param callable $callback
6163 function markerSkipCallback( $s, $callback ) {
6166 while ( $i < strlen( $s ) ) {
6167 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
6168 if ( $markerStart === false ) {
6169 $out .= call_user_func( $callback, substr( $s, $i ) );
6172 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6173 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6174 if ( $markerEnd === false ) {
6175 $out .= substr( $s, $markerStart );
6178 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6179 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6188 * Remove any strip markers found in the given text.
6190 * @param string $text Input string
6193 function killMarkers( $text ) {
6194 return $this->mStripState
->killMarkers( $text );
6198 * Save the parser state required to convert the given half-parsed text to
6199 * HTML. "Half-parsed" in this context means the output of
6200 * recursiveTagParse() or internalParse(). This output has strip markers
6201 * from replaceVariables (extensionSubstitution() etc.), and link
6202 * placeholders from replaceLinkHolders().
6204 * Returns an array which can be serialized and stored persistently. This
6205 * array can later be loaded into another parser instance with
6206 * unserializeHalfParsedText(). The text can then be safely incorporated into
6207 * the return value of a parser hook.
6209 * @param string $text
6213 function serializeHalfParsedText( $text ) {
6214 wfProfileIn( __METHOD__
);
6217 'version' => self
::HALF_PARSED_VERSION
,
6218 'stripState' => $this->mStripState
->getSubState( $text ),
6219 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6221 wfProfileOut( __METHOD__
);
6226 * Load the parser state given in the $data array, which is assumed to
6227 * have been generated by serializeHalfParsedText(). The text contents is
6228 * extracted from the array, and its markers are transformed into markers
6229 * appropriate for the current Parser instance. This transformed text is
6230 * returned, and can be safely included in the return value of a parser
6233 * If the $data array has been stored persistently, the caller should first
6234 * check whether it is still valid, by calling isValidHalfParsedText().
6236 * @param array $data Serialized data
6237 * @throws MWException
6240 function unserializeHalfParsedText( $data ) {
6241 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6242 throw new MWException( __METHOD__
. ': invalid version' );
6245 # First, extract the strip state.
6246 $texts = array( $data['text'] );
6247 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6249 # Now renumber links
6250 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6252 # Should be good to go.
6257 * Returns true if the given array, presumed to be generated by
6258 * serializeHalfParsedText(), is compatible with the current version of the
6261 * @param array $data
6265 function isValidHalfParsedText( $data ) {
6266 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6270 * Parsed a width param of imagelink like 300px or 200x300px
6272 * @param string $value
6277 public function parseWidthParam( $value ) {
6278 $parsedWidthParam = array();
6279 if ( $value === '' ) {
6280 return $parsedWidthParam;
6283 # (bug 13500) In both cases (width/height and width only),
6284 # permit trailing "px" for backward compatibility.
6285 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6286 $width = intval( $m[1] );
6287 $height = intval( $m[2] );
6288 $parsedWidthParam['width'] = $width;
6289 $parsedWidthParam['height'] = $height;
6290 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6291 $width = intval( $value );
6292 $parsedWidthParam['width'] = $width;
6294 return $parsedWidthParam;
6298 * Lock the current instance of the parser.
6300 * This is meant to stop someone from calling the parser
6301 * recursively and messing up all the strip state.
6303 * @throws MWException If parser is in a parse
6304 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6306 protected function lock() {
6307 if ( $this->mInParse
) {
6308 throw new MWException( "Parser state cleared while parsing. "
6309 . "Did you call Parser::parse recursively?" );
6311 $this->mInParse
= true;
6314 $recursiveCheck = new ScopedCallback( function() use ( $that ) {
6315 $that->mInParse
= false;
6318 return $recursiveCheck;
6322 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6324 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6325 * or if there is more than one <p/> tag in the input HTML.
6327 * @param string $html
6331 public static function stripOuterParagraph( $html ) {
6333 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6334 if ( strpos( $m[1], '</p>' ) === false ) {
6343 * Return this parser if it is not doing anything, otherwise
6344 * get a fresh parser. You can use this method by doing
6345 * $myParser = $wgParser->getFreshParser(), or more simply
6346 * $wgParser->getFreshParser()->parse( ... );
6347 * if you're unsure if $wgParser is safe to use.
6350 * @return Parser A parser object that is not parsing anything
6352 public function getFreshParser() {
6353 global $wgParserConf;
6354 if ( $this->mInParse
) {
6355 return new $wgParserConf['class']( $wgParserConf );