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 $mTplExpandCache; # empty-frame expansion cache
171 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
172 var $mExpensiveFunctionCount; # number of expensive parser function calls
173 var $mShowToc, $mForceTocPosition;
178 var $mUser; # User object; only used when doing pre-save transform
181 # These are variables reset at least once per parse regardless of $clearState
191 var $mTitle; # Title context, used for self-link rendering and similar things
192 var $mOutputType; # Output type, one of the OT_xxx constants
193 var $ot; # Shortcut alias, see setOutputType()
194 var $mRevisionObject; # The revision object of the specified revision ID
195 var $mRevisionId; # ID to display in {{REVISIONID}} tags
196 var $mRevisionTimestamp; # The timestamp of the specified revision ID
197 var $mRevisionUser; # User to display in {{REVISIONUSER}} tag
198 var $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
199 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp
200 var $mInputSize = false; # For {{PAGESIZE}} on current page.
208 * @var array Array with the language name of each language link (i.e. the
209 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
210 * duplicate language links to the ParserOutput.
212 var $mLangLinkLanguages;
215 * @var boolean Recursive call protection.
216 * This variable should be treated as if it were private.
218 public $mInParse = false;
225 public function __construct( $conf = array() ) {
226 $this->mConf
= $conf;
227 $this->mUrlProtocols
= wfUrlProtocols();
228 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
229 self
::EXT_LINK_URL_CLASS
. '+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
230 if ( isset( $conf['preprocessorClass'] ) ) {
231 $this->mPreprocessorClass
= $conf['preprocessorClass'];
232 } elseif ( defined( 'HPHP_VERSION' ) ) {
233 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
234 $this->mPreprocessorClass
= 'Preprocessor_Hash';
235 } elseif ( extension_loaded( 'domxml' ) ) {
236 # PECL extension that conflicts with the core DOM extension (bug 13770)
237 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
238 $this->mPreprocessorClass
= 'Preprocessor_Hash';
239 } elseif ( extension_loaded( 'dom' ) ) {
240 $this->mPreprocessorClass
= 'Preprocessor_DOM';
242 $this->mPreprocessorClass
= 'Preprocessor_Hash';
244 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
248 * Reduce memory usage to reduce the impact of circular references
250 function __destruct() {
251 if ( isset( $this->mLinkHolders
) ) {
252 unset( $this->mLinkHolders
);
254 foreach ( $this as $name => $value ) {
255 unset( $this->$name );
260 * Allow extensions to clean up when the parser is cloned
263 $this->mInParse
= false;
264 wfRunHooks( 'ParserCloned', array( $this ) );
268 * Do various kinds of initialisation on the first call of the parser
270 function firstCallInit() {
271 if ( !$this->mFirstCall
) {
274 $this->mFirstCall
= false;
276 wfProfileIn( __METHOD__
);
278 CoreParserFunctions
::register( $this );
279 CoreTagHooks
::register( $this );
280 $this->initialiseVariables();
282 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
283 wfProfileOut( __METHOD__
);
291 function clearState() {
292 wfProfileIn( __METHOD__
);
293 if ( $this->mFirstCall
) {
294 $this->firstCallInit();
296 $this->mOutput
= new ParserOutput
;
297 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
298 $this->mAutonumber
= 0;
299 $this->mLastSection
= '';
300 $this->mDTopen
= false;
301 $this->mIncludeCount
= array();
302 $this->mArgStack
= false;
303 $this->mInPre
= false;
304 $this->mLinkHolders
= new LinkHolderArray( $this );
306 $this->mRevisionObject
= $this->mRevisionTimestamp
=
307 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
308 $this->mVarCache
= array();
310 $this->mLangLinkLanguages
= array();
313 * Prefix for temporary replacement strings for the multipass parser.
314 * \x07 should never appear in input as it's disallowed in XML.
315 * Using it at the front also gives us a little extra robustness
316 * since it shouldn't match when butted up against identifier-like
319 * Must not consist of all title characters, or else it will change
320 * the behavior of <nowiki> in a link.
322 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
323 $this->mStripState
= new StripState( $this->mUniqPrefix
);
325 # Clear these on every parse, bug 4549
326 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
328 $this->mShowToc
= true;
329 $this->mForceTocPosition
= false;
330 $this->mIncludeSizes
= array(
334 $this->mPPNodeCount
= 0;
335 $this->mGeneratedPPNodeCount
= 0;
336 $this->mHighestExpansionDepth
= 0;
337 $this->mDefaultSort
= false;
338 $this->mHeadings
= array();
339 $this->mDoubleUnderscores
= array();
340 $this->mExpensiveFunctionCount
= 0;
343 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
344 $this->mPreprocessor
= null;
347 wfRunHooks( 'ParserClearState', array( &$this ) );
348 wfProfileOut( __METHOD__
);
352 * Convert wikitext to HTML
353 * Do not call this function recursively.
355 * @param string $text text we want to parse
356 * @param Title $title
357 * @param ParserOptions $options
358 * @param bool $linestart
359 * @param bool $clearState
360 * @param int $revid Number to pass in {{REVISIONID}}
361 * @return ParserOutput A ParserOutput
363 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
365 * First pass--just handle <nowiki> sections, pass the rest off
366 * to internalParse() which does all the real work.
369 global $wgUseTidy, $wgAlwaysUseTidy, $wgShowHostnames;
370 $fname = __METHOD__
. '-' . wfGetCaller();
371 wfProfileIn( __METHOD__
);
372 wfProfileIn( $fname );
375 $magicScopeVariable = $this->lock();
378 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
380 $this->mInputSize
= strlen( $text );
381 if ( $this->mOptions
->getEnableLimitReport() ) {
382 $this->mOutput
->resetParseStartTime();
385 # Remove the strip marker tag prefix from the input, if present.
387 $text = str_replace( $this->mUniqPrefix
, '', $text );
390 $oldRevisionId = $this->mRevisionId
;
391 $oldRevisionObject = $this->mRevisionObject
;
392 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
393 $oldRevisionUser = $this->mRevisionUser
;
394 $oldRevisionSize = $this->mRevisionSize
;
395 if ( $revid !== null ) {
396 $this->mRevisionId
= $revid;
397 $this->mRevisionObject
= null;
398 $this->mRevisionTimestamp
= null;
399 $this->mRevisionUser
= null;
400 $this->mRevisionSize
= null;
403 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
405 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
406 $text = $this->internalParse( $text );
407 wfRunHooks( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
409 $text = $this->mStripState
->unstripGeneral( $text );
411 # Clean up special characters, only run once, next-to-last before doBlockLevels
413 # french spaces, last one Guillemet-left
414 # only if there is something before the space
415 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
416 # french spaces, Guillemet-right
417 '/(\\302\\253) /' => '\\1 ',
418 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
420 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
422 $text = $this->doBlockLevels( $text, $linestart );
424 $this->replaceLinkHolders( $text );
427 * The input doesn't get language converted if
429 * b) Content isn't converted
430 * c) It's a conversion table
431 * d) it is an interface message (which is in the user language)
433 if ( !( $options->getDisableContentConversion()
434 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
436 if ( !$this->mOptions
->getInterfaceMessage() ) {
437 # The position of the convert() call should not be changed. it
438 # assumes that the links are all replaced and the only thing left
439 # is the <nowiki> mark.
440 $text = $this->getConverterLanguage()->convert( $text );
445 * A converted title will be provided in the output object if title and
446 * content conversion are enabled, the article text does not contain
447 * a conversion-suppressing double-underscore tag, and no
448 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
449 * automatic link conversion.
451 if ( !( $options->getDisableTitleConversion()
452 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
453 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
454 ||
$this->mOutput
->getDisplayTitle() !== false )
456 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
457 if ( $convruletitle ) {
458 $this->mOutput
->setTitleText( $convruletitle );
460 $titleText = $this->getConverterLanguage()->convertTitle( $title );
461 $this->mOutput
->setTitleText( $titleText );
465 $text = $this->mStripState
->unstripNoWiki( $text );
467 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
469 $text = $this->replaceTransparentTags( $text );
470 $text = $this->mStripState
->unstripGeneral( $text );
472 $text = Sanitizer
::normalizeCharReferences( $text );
474 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
475 $text = MWTidy
::tidy( $text );
477 # attempt to sanitize at least some nesting problems
478 # (bug #2702 and quite a few others)
480 # ''Something [http://www.cool.com cool''] -->
481 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
482 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
483 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
484 # fix up an anchor inside another anchor, only
485 # at least for a single single nested link (bug 3695)
486 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
487 '\\1\\2</a>\\3</a>\\1\\4</a>',
488 # fix div inside inline elements- doBlockLevels won't wrap a line which
489 # contains a div, so fix it up here; replace
490 # div with escaped text
491 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
492 '\\1\\3<div\\5>\\6</div>\\8\\9',
493 # remove empty italic or bold tag pairs, some
494 # introduced by rules above
495 '/<([bi])><\/\\1>/' => '',
498 $text = preg_replace(
499 array_keys( $tidyregs ),
500 array_values( $tidyregs ),
504 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
505 $this->limitationWarn( 'expensive-parserfunction',
506 $this->mExpensiveFunctionCount
,
507 $this->mOptions
->getExpensiveParserFunctionLimit()
511 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
513 # Information on include size limits, for the benefit of users who try to skirt them
514 if ( $this->mOptions
->getEnableLimitReport() ) {
515 $max = $this->mOptions
->getMaxIncludeSize();
517 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
518 if ( $cpuTime !== null ) {
519 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
520 sprintf( "%.3f", $cpuTime )
524 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
525 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
526 sprintf( "%.3f", $wallTime )
529 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
530 array( $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() )
532 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
533 array( $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() )
535 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
536 array( $this->mIncludeSizes
['post-expand'], $max )
538 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
539 array( $this->mIncludeSizes
['arg'], $max )
541 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
542 array( $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() )
544 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
545 array( $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() )
547 wfRunHooks( 'ParserLimitReportPrepare', array( $this, $this->mOutput
) );
549 $limitReport = "NewPP limit report\n";
550 if ( $wgShowHostnames ) {
551 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
553 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
554 if ( wfRunHooks( 'ParserLimitReportFormat',
555 array( $key, &$value, &$limitReport, false, false )
557 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
558 $valueMsg = wfMessage( array( "$key-value-text", "$key-value" ) )
559 ->inLanguage( 'en' )->useDatabase( false );
560 if ( !$valueMsg->exists() ) {
561 $valueMsg = new RawMessage( '$1' );
563 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
564 $valueMsg->params( $value );
565 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
569 // Since we're not really outputting HTML, decode the entities and
570 // then re-encode the things that need hiding inside HTML comments.
571 $limitReport = htmlspecialchars_decode( $limitReport );
572 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
574 // Sanitize for comment. Note '‐' in the replacement is U+2010,
575 // which looks much like the problematic '-'.
576 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&' ), $limitReport );
577 $text .= "\n<!-- \n$limitReport-->\n";
579 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
580 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
581 $this->mTitle
->getPrefixedDBkey() );
584 $this->mOutput
->setText( $text );
586 $this->mRevisionId
= $oldRevisionId;
587 $this->mRevisionObject
= $oldRevisionObject;
588 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
589 $this->mRevisionUser
= $oldRevisionUser;
590 $this->mRevisionSize
= $oldRevisionSize;
591 $this->mInputSize
= false;
592 wfProfileOut( $fname );
593 wfProfileOut( __METHOD__
);
595 return $this->mOutput
;
599 * Recursive parser entry point that can be called from an extension tag
602 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
604 * @param string $text Text extension wants to have parsed
605 * @param PPFrame $frame The frame to use for expanding any template variables
609 function recursiveTagParse( $text, $frame = false ) {
610 wfProfileIn( __METHOD__
);
611 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
612 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
613 $text = $this->internalParse( $text, false, $frame );
614 wfProfileOut( __METHOD__
);
619 * Expand templates and variables in the text, producing valid, static wikitext.
620 * Also removes comments.
621 * @param string $text
622 * @param Title $title
623 * @param ParserOptions $options
624 * @param int|null $revid
625 * @return mixed|string
627 function preprocess( $text, Title
$title = null, ParserOptions
$options, $revid = null ) {
628 wfProfileIn( __METHOD__
);
629 $magicScopeVariable = $this->lock();
630 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
631 if ( $revid !== null ) {
632 $this->mRevisionId
= $revid;
634 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
635 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
636 $text = $this->replaceVariables( $text );
637 $text = $this->mStripState
->unstripBoth( $text );
638 wfProfileOut( __METHOD__
);
643 * Recursive parser entry point that can be called from an extension tag
646 * @param string $text Text to be expanded
647 * @param PPFrame $frame The frame to use for expanding any template variables
651 public function recursivePreprocess( $text, $frame = false ) {
652 wfProfileIn( __METHOD__
);
653 $text = $this->replaceVariables( $text, $frame );
654 $text = $this->mStripState
->unstripBoth( $text );
655 wfProfileOut( __METHOD__
);
660 * Process the wikitext for the "?preload=" feature. (bug 5210)
662 * "<noinclude>", "<includeonly>" etc. are parsed as for template
663 * transclusion, comments, templates, arguments, tags hooks and parser
664 * functions are untouched.
666 * @param string $text
667 * @param Title $title
668 * @param ParserOptions $options
669 * @param array $params
672 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = array() ) {
673 $msg = new RawMessage( $text );
674 $text = $msg->params( $params )->plain();
676 # Parser (re)initialisation
677 $magicScopeVariable = $this->lock();
678 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
680 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
681 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
682 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
683 $text = $this->mStripState
->unstripBoth( $text );
688 * Get a random string
692 public static function getRandomString() {
693 return wfRandomString( 16 );
697 * Set the current user.
698 * Should only be used when doing pre-save transform.
700 * @param User|null $user User object or null (to reset)
702 function setUser( $user ) {
703 $this->mUser
= $user;
707 * Accessor for mUniqPrefix.
711 public function uniqPrefix() {
712 if ( !isset( $this->mUniqPrefix
) ) {
713 # @todo FIXME: This is probably *horribly wrong*
714 # LanguageConverter seems to want $wgParser's uniqPrefix, however
715 # if this is called for a parser cache hit, the parser may not
716 # have ever been initialized in the first place.
717 # Not really sure what the heck is supposed to be going on here.
719 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
721 return $this->mUniqPrefix
;
725 * Set the context title
729 function setTitle( $t ) {
731 $t = Title
::newFromText( 'NO TITLE' );
734 if ( $t->hasFragment() ) {
735 # Strip the fragment to avoid various odd effects
736 $this->mTitle
= clone $t;
737 $this->mTitle
->setFragment( '' );
744 * Accessor for the Title object
748 function getTitle() {
749 return $this->mTitle
;
753 * Accessor/mutator for the Title object
755 * @param Title $x Title object or null to just get the current one
758 function Title( $x = null ) {
759 return wfSetVar( $this->mTitle
, $x );
763 * Set the output type
765 * @param int $ot New value
767 function setOutputType( $ot ) {
768 $this->mOutputType
= $ot;
771 'html' => $ot == self
::OT_HTML
,
772 'wiki' => $ot == self
::OT_WIKI
,
773 'pre' => $ot == self
::OT_PREPROCESS
,
774 'plain' => $ot == self
::OT_PLAIN
,
779 * Accessor/mutator for the output type
781 * @param int|null $x New value or null to just get the current one
784 function OutputType( $x = null ) {
785 return wfSetVar( $this->mOutputType
, $x );
789 * Get the ParserOutput object
791 * @return ParserOutput
793 function getOutput() {
794 return $this->mOutput
;
798 * Get the ParserOptions object
800 * @return ParserOptions object
802 function getOptions() {
803 return $this->mOptions
;
807 * Accessor/mutator for the ParserOptions object
809 * @param ParserOptions $x New value or null to just get the current one
810 * @return ParserOptions Current ParserOptions object
812 function Options( $x = null ) {
813 return wfSetVar( $this->mOptions
, $x );
819 function nextLinkID() {
820 return $this->mLinkID++
;
826 function setLinkID( $id ) {
827 $this->mLinkID
= $id;
831 * Get a language object for use in parser functions such as {{FORMATNUM:}}
834 function getFunctionLang() {
835 return $this->getTargetLanguage();
839 * Get the target language for the content being parsed. This is usually the
840 * language that the content is in.
844 * @throws MWException
845 * @return Language|null
847 public function getTargetLanguage() {
848 $target = $this->mOptions
->getTargetLanguage();
850 if ( $target !== null ) {
852 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
853 return $this->mOptions
->getUserLangObj();
854 } elseif ( is_null( $this->mTitle
) ) {
855 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
858 return $this->mTitle
->getPageLanguage();
862 * Get the language object for language conversion
863 * @return Language|null
865 function getConverterLanguage() {
866 return $this->getTargetLanguage();
870 * Get a User object either from $this->mUser, if set, or from the
871 * ParserOptions object otherwise
876 if ( !is_null( $this->mUser
) ) {
879 return $this->mOptions
->getUser();
883 * Get a preprocessor object
885 * @return Preprocessor
887 function getPreprocessor() {
888 if ( !isset( $this->mPreprocessor
) ) {
889 $class = $this->mPreprocessorClass
;
890 $this->mPreprocessor
= new $class( $this );
892 return $this->mPreprocessor
;
896 * Replaces all occurrences of HTML-style comments and the given tags
897 * in the text with a random marker and returns the next text. The output
898 * parameter $matches will be an associative array filled with data in
902 * 'UNIQ-xxxxx' => array(
905 * array( 'param' => 'x' ),
906 * '<element param="x">tag content</element>' ) )
909 * @param array $elements List of element names. Comments are always extracted.
910 * @param string $text Source text string.
911 * @param array $matches Out parameter, Array: extracted tags
912 * @param string $uniq_prefix
913 * @return string Stripped text
915 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
920 $taglist = implode( '|', $elements );
921 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
923 while ( $text != '' ) {
924 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
926 if ( count( $p ) < 5 ) {
929 if ( count( $p ) > 5 ) {
943 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
944 $stripped .= $marker;
946 if ( $close === '/>' ) {
947 # Empty element tag, <tag />
952 if ( $element === '!--' ) {
955 $end = "/(<\\/$element\\s*>)/i";
957 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
959 if ( count( $q ) < 3 ) {
960 # No end tag -- let it run out to the end of the text.
969 $matches[$marker] = array( $element,
971 Sanitizer
::decodeTagAttributes( $attributes ),
972 "<$element$attributes$close$content$tail" );
978 * Get a list of strippable XML-like elements
982 function getStripList() {
983 return $this->mStripList
;
987 * Add an item to the strip state
988 * Returns the unique tag which must be inserted into the stripped text
989 * The tag will be replaced with the original text in unstrip()
991 * @param string $text
995 function insertStripItem( $text ) {
996 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
997 $this->mMarkerIndex++
;
998 $this->mStripState
->addGeneral( $rnd, $text );
1003 * parse the wiki syntax used to render tables
1006 * @param string $text
1009 function doTableStuff( $text ) {
1010 wfProfileIn( __METHOD__
);
1012 $lines = StringUtils
::explode( "\n", $text );
1014 $td_history = array(); # Is currently a td tag open?
1015 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
1016 $tr_history = array(); # Is currently a tr tag open?
1017 $tr_attributes = array(); # history of tr attributes
1018 $has_opened_tr = array(); # Did this table open a <tr> element?
1019 $indent_level = 0; # indent level of the table
1021 foreach ( $lines as $outLine ) {
1022 $line = trim( $outLine );
1024 if ( $line === '' ) { # empty line, go to next line
1025 $out .= $outLine . "\n";
1029 $first_character = $line[0];
1032 if ( preg_match( '/^(:*)\{\|(.*)$/', $line, $matches ) ) {
1033 # First check if we are starting a new table
1034 $indent_level = strlen( $matches[1] );
1036 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1037 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1039 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1040 array_push( $td_history, false );
1041 array_push( $last_tag_history, '' );
1042 array_push( $tr_history, false );
1043 array_push( $tr_attributes, '' );
1044 array_push( $has_opened_tr, false );
1045 } elseif ( count( $td_history ) == 0 ) {
1046 # Don't do any of the following
1047 $out .= $outLine . "\n";
1049 } elseif ( substr( $line, 0, 2 ) === '|}' ) {
1050 # We are ending a table
1051 $line = '</table>' . substr( $line, 2 );
1052 $last_tag = array_pop( $last_tag_history );
1054 if ( !array_pop( $has_opened_tr ) ) {
1055 $line = "<tr><td></td></tr>{$line}";
1058 if ( array_pop( $tr_history ) ) {
1059 $line = "</tr>{$line}";
1062 if ( array_pop( $td_history ) ) {
1063 $line = "</{$last_tag}>{$line}";
1065 array_pop( $tr_attributes );
1066 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
1067 } elseif ( substr( $line, 0, 2 ) === '|-' ) {
1068 # Now we have a table row
1069 $line = preg_replace( '#^\|-+#', '', $line );
1071 # Whats after the tag is now only attributes
1072 $attributes = $this->mStripState
->unstripBoth( $line );
1073 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1074 array_pop( $tr_attributes );
1075 array_push( $tr_attributes, $attributes );
1078 $last_tag = array_pop( $last_tag_history );
1079 array_pop( $has_opened_tr );
1080 array_push( $has_opened_tr, true );
1082 if ( array_pop( $tr_history ) ) {
1086 if ( array_pop( $td_history ) ) {
1087 $line = "</{$last_tag}>{$line}";
1091 array_push( $tr_history, false );
1092 array_push( $td_history, false );
1093 array_push( $last_tag_history, '' );
1094 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line, 0, 2 ) === '|+' ) {
1095 # This might be cell elements, td, th or captions
1096 if ( substr( $line, 0, 2 ) === '|+' ) {
1097 $first_character = '+';
1098 $line = substr( $line, 1 );
1101 $line = substr( $line, 1 );
1103 if ( $first_character === '!' ) {
1104 $line = str_replace( '!!', '||', $line );
1107 # Split up multiple cells on the same line.
1108 # FIXME : This can result in improper nesting of tags processed
1109 # by earlier parser steps, but should avoid splitting up eg
1110 # attribute values containing literal "||".
1111 $cells = StringUtils
::explodeMarkup( '||', $line );
1115 # Loop through each table cell
1116 foreach ( $cells as $cell ) {
1118 if ( $first_character !== '+' ) {
1119 $tr_after = array_pop( $tr_attributes );
1120 if ( !array_pop( $tr_history ) ) {
1121 $previous = "<tr{$tr_after}>\n";
1123 array_push( $tr_history, true );
1124 array_push( $tr_attributes, '' );
1125 array_pop( $has_opened_tr );
1126 array_push( $has_opened_tr, true );
1129 $last_tag = array_pop( $last_tag_history );
1131 if ( array_pop( $td_history ) ) {
1132 $previous = "</{$last_tag}>\n{$previous}";
1135 if ( $first_character === '|' ) {
1137 } elseif ( $first_character === '!' ) {
1139 } elseif ( $first_character === '+' ) {
1140 $last_tag = 'caption';
1145 array_push( $last_tag_history, $last_tag );
1147 # A cell could contain both parameters and data
1148 $cell_data = explode( '|', $cell, 2 );
1150 # Bug 553: Note that a '|' inside an invalid link should not
1151 # be mistaken as delimiting cell parameters
1152 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1153 $cell = "{$previous}<{$last_tag}>{$cell}";
1154 } elseif ( count( $cell_data ) == 1 ) {
1155 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1157 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1158 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1159 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1163 array_push( $td_history, true );
1166 $out .= $outLine . "\n";
1169 # Closing open td, tr && table
1170 while ( count( $td_history ) > 0 ) {
1171 if ( array_pop( $td_history ) ) {
1174 if ( array_pop( $tr_history ) ) {
1177 if ( !array_pop( $has_opened_tr ) ) {
1178 $out .= "<tr><td></td></tr>\n";
1181 $out .= "</table>\n";
1184 # Remove trailing line-ending (b/c)
1185 if ( substr( $out, -1 ) === "\n" ) {
1186 $out = substr( $out, 0, -1 );
1189 # special case: don't return empty table
1190 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1194 wfProfileOut( __METHOD__
);
1200 * Helper function for parse() that transforms wiki markup into
1201 * HTML. Only called for $mOutputType == self::OT_HTML.
1205 * @param string $text
1206 * @param bool $isMain
1207 * @param bool $frame
1211 function internalParse( $text, $isMain = true, $frame = false ) {
1212 wfProfileIn( __METHOD__
);
1216 # Hook to suspend the parser in this state
1217 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1218 wfProfileOut( __METHOD__
);
1222 # if $frame is provided, then use $frame for replacing any variables
1224 # use frame depth to infer how include/noinclude tags should be handled
1225 # depth=0 means this is the top-level document; otherwise it's an included document
1226 if ( !$frame->depth
) {
1229 $flag = Parser
::PTD_FOR_INCLUSION
;
1231 $dom = $this->preprocessToDom( $text, $flag );
1232 $text = $frame->expand( $dom );
1234 # if $frame is not provided, then use old-style replaceVariables
1235 $text = $this->replaceVariables( $text );
1238 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1239 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1240 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1242 # Tables need to come after variable replacement for things to work
1243 # properly; putting them before other transformations should keep
1244 # exciting things like link expansions from showing up in surprising
1246 $text = $this->doTableStuff( $text );
1248 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1250 $text = $this->doDoubleUnderscore( $text );
1252 $text = $this->doHeadings( $text );
1253 $text = $this->replaceInternalLinks( $text );
1254 $text = $this->doAllQuotes( $text );
1255 $text = $this->replaceExternalLinks( $text );
1257 # replaceInternalLinks may sometimes leave behind
1258 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1259 $text = str_replace( $this->mUniqPrefix
. 'NOPARSE', '', $text );
1261 $text = $this->doMagicLinks( $text );
1262 $text = $this->formatHeadings( $text, $origText, $isMain );
1264 wfProfileOut( __METHOD__
);
1269 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1270 * magic external links.
1275 * @param string $text
1279 function doMagicLinks( $text ) {
1280 wfProfileIn( __METHOD__
);
1281 $prots = wfUrlProtocolsWithoutProtRel();
1282 $urlChar = self
::EXT_LINK_URL_CLASS
;
1283 $text = preg_replace_callback(
1285 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1286 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1287 (\\b(?i:$prots)$urlChar+) | # m[3]: Free external links" . '
1288 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1289 ISBN\s+(\b # m[5]: ISBN, capture number
1290 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1291 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1292 [0-9Xx] # check digit
1294 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1295 wfProfileOut( __METHOD__
);
1300 * @throws MWException
1302 * @return HTML|string
1304 function magicLinkCallback( $m ) {
1305 if ( isset( $m[1] ) && $m[1] !== '' ) {
1308 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1311 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1312 # Free external link
1313 return $this->makeFreeExternalLink( $m[0] );
1314 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1316 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1319 $cssClass = 'mw-magiclink-rfc';
1321 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1323 $urlmsg = 'pubmedurl';
1324 $cssClass = 'mw-magiclink-pmid';
1327 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1328 substr( $m[0], 0, 20 ) . '"' );
1330 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1331 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass );
1332 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1335 $num = strtr( $isbn, array(
1340 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1341 return '<a href="' .
1342 htmlspecialchars( $titleObj->getLocalURL() ) .
1343 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1350 * Make a free external link, given a user-supplied URL
1352 * @param string $url
1354 * @return string HTML
1357 function makeFreeExternalLink( $url ) {
1358 wfProfileIn( __METHOD__
);
1362 # The characters '<' and '>' (which were escaped by
1363 # removeHTMLtags()) should not be included in
1364 # URLs, per RFC 2396.
1366 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1367 $trail = substr( $url, $m2[0][1] ) . $trail;
1368 $url = substr( $url, 0, $m2[0][1] );
1371 # Move trailing punctuation to $trail
1373 # If there is no left bracket, then consider right brackets fair game too
1374 if ( strpos( $url, '(' ) === false ) {
1378 $numSepChars = strspn( strrev( $url ), $sep );
1379 if ( $numSepChars ) {
1380 $trail = substr( $url, -$numSepChars ) . $trail;
1381 $url = substr( $url, 0, -$numSepChars );
1384 $url = Sanitizer
::cleanUrl( $url );
1386 # Is this an external image?
1387 $text = $this->maybeMakeExternalImage( $url );
1388 if ( $text === false ) {
1389 # Not an image, make a link
1390 $text = Linker
::makeExternalLink( $url,
1391 $this->getConverterLanguage()->markNoConversion( $url, true ),
1393 $this->getExternalLinkAttribs( $url ) );
1394 # Register it in the output object...
1395 # Replace unnecessary URL escape codes with their equivalent characters
1396 $pasteurized = self
::replaceUnusualEscapes( $url );
1397 $this->mOutput
->addExternalLink( $pasteurized );
1399 wfProfileOut( __METHOD__
);
1400 return $text . $trail;
1404 * Parse headers and return html
1408 * @param string $text
1412 function doHeadings( $text ) {
1413 wfProfileIn( __METHOD__
);
1414 for ( $i = 6; $i >= 1; --$i ) {
1415 $h = str_repeat( '=', $i );
1416 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1418 wfProfileOut( __METHOD__
);
1423 * Replace single quotes with HTML markup
1426 * @param string $text
1428 * @return string the altered text
1430 function doAllQuotes( $text ) {
1431 wfProfileIn( __METHOD__
);
1433 $lines = StringUtils
::explode( "\n", $text );
1434 foreach ( $lines as $line ) {
1435 $outtext .= $this->doQuotes( $line ) . "\n";
1437 $outtext = substr( $outtext, 0, -1 );
1438 wfProfileOut( __METHOD__
);
1443 * Helper function for doAllQuotes()
1445 * @param string $text
1449 public function doQuotes( $text ) {
1450 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1451 $countarr = count( $arr );
1452 if ( $countarr == 1 ) {
1456 // First, do some preliminary work. This may shift some apostrophes from
1457 // being mark-up to being text. It also counts the number of occurrences
1458 // of bold and italics mark-ups.
1461 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1462 $thislen = strlen( $arr[$i] );
1463 // If there are ever four apostrophes, assume the first is supposed to
1464 // be text, and the remaining three constitute mark-up for bold text.
1465 // (bug 13227: ''''foo'''' turns into ' ''' foo ' ''')
1466 if ( $thislen == 4 ) {
1467 $arr[$i - 1] .= "'";
1470 } elseif ( $thislen > 5 ) {
1471 // If there are more than 5 apostrophes in a row, assume they're all
1472 // text except for the last 5.
1473 // (bug 13227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1474 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1478 // Count the number of occurrences of bold and italics mark-ups.
1479 if ( $thislen == 2 ) {
1481 } elseif ( $thislen == 3 ) {
1483 } elseif ( $thislen == 5 ) {
1489 // If there is an odd number of both bold and italics, it is likely
1490 // that one of the bold ones was meant to be an apostrophe followed
1491 // by italics. Which one we cannot know for certain, but it is more
1492 // likely to be one that has a single-letter word before it.
1493 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1494 $firstsingleletterword = -1;
1495 $firstmultiletterword = -1;
1497 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1498 if ( strlen( $arr[$i] ) == 3 ) {
1499 $x1 = substr( $arr[$i - 1], -1 );
1500 $x2 = substr( $arr[$i - 1], -2, 1 );
1501 if ( $x1 === ' ' ) {
1502 if ( $firstspace == -1 ) {
1505 } elseif ( $x2 === ' ' ) {
1506 if ( $firstsingleletterword == -1 ) {
1507 $firstsingleletterword = $i;
1508 // if $firstsingleletterword is set, we don't
1509 // look at the other options, so we can bail early.
1513 if ( $firstmultiletterword == -1 ) {
1514 $firstmultiletterword = $i;
1520 // If there is a single-letter word, use it!
1521 if ( $firstsingleletterword > -1 ) {
1522 $arr[$firstsingleletterword] = "''";
1523 $arr[$firstsingleletterword - 1] .= "'";
1524 } elseif ( $firstmultiletterword > -1 ) {
1525 // If not, but there's a multi-letter word, use that one.
1526 $arr[$firstmultiletterword] = "''";
1527 $arr[$firstmultiletterword - 1] .= "'";
1528 } elseif ( $firstspace > -1 ) {
1529 // ... otherwise use the first one that has neither.
1530 // (notice that it is possible for all three to be -1 if, for example,
1531 // there is only one pentuple-apostrophe in the line)
1532 $arr[$firstspace] = "''";
1533 $arr[$firstspace - 1] .= "'";
1537 // Now let's actually convert our apostrophic mush to HTML!
1542 foreach ( $arr as $r ) {
1543 if ( ( $i %
2 ) == 0 ) {
1544 if ( $state === 'both' ) {
1550 $thislen = strlen( $r );
1551 if ( $thislen == 2 ) {
1552 if ( $state === 'i' ) {
1555 } elseif ( $state === 'bi' ) {
1558 } elseif ( $state === 'ib' ) {
1559 $output .= '</b></i><b>';
1561 } elseif ( $state === 'both' ) {
1562 $output .= '<b><i>' . $buffer . '</i>';
1564 } else { // $state can be 'b' or ''
1568 } elseif ( $thislen == 3 ) {
1569 if ( $state === 'b' ) {
1572 } elseif ( $state === 'bi' ) {
1573 $output .= '</i></b><i>';
1575 } elseif ( $state === 'ib' ) {
1578 } elseif ( $state === 'both' ) {
1579 $output .= '<i><b>' . $buffer . '</b>';
1581 } else { // $state can be 'i' or ''
1585 } elseif ( $thislen == 5 ) {
1586 if ( $state === 'b' ) {
1587 $output .= '</b><i>';
1589 } elseif ( $state === 'i' ) {
1590 $output .= '</i><b>';
1592 } elseif ( $state === 'bi' ) {
1593 $output .= '</i></b>';
1595 } elseif ( $state === 'ib' ) {
1596 $output .= '</b></i>';
1598 } elseif ( $state === 'both' ) {
1599 $output .= '<i><b>' . $buffer . '</b></i>';
1601 } else { // ($state == '')
1609 // Now close all remaining tags. Notice that the order is important.
1610 if ( $state === 'b' ||
$state === 'ib' ) {
1613 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1616 if ( $state === 'bi' ) {
1619 // There might be lonely ''''', so make sure we have a buffer
1620 if ( $state === 'both' && $buffer ) {
1621 $output .= '<b><i>' . $buffer . '</i></b>';
1627 * Replace external links (REL)
1629 * Note: this is all very hackish and the order of execution matters a lot.
1630 * Make sure to run tests/parserTests.php if you change this code.
1634 * @param string $text
1636 * @throws MWException
1639 function replaceExternalLinks( $text ) {
1640 wfProfileIn( __METHOD__
);
1642 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1643 if ( $bits === false ) {
1644 wfProfileOut( __METHOD__
);
1645 throw new MWException( "PCRE needs to be compiled with --enable-unicode-properties in order for MediaWiki to function" );
1647 $s = array_shift( $bits );
1650 while ( $i < count( $bits ) ) {
1653 $text = $bits[$i++
];
1654 $trail = $bits[$i++
];
1656 # The characters '<' and '>' (which were escaped by
1657 # removeHTMLtags()) should not be included in
1658 # URLs, per RFC 2396.
1660 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1661 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1662 $url = substr( $url, 0, $m2[0][1] );
1665 # If the link text is an image URL, replace it with an <img> tag
1666 # This happened by accident in the original parser, but some people used it extensively
1667 $img = $this->maybeMakeExternalImage( $text );
1668 if ( $img !== false ) {
1674 # Set linktype for CSS - if URL==text, link is essentially free
1675 $linktype = ( $text === $url ) ?
'free' : 'text';
1677 # No link text, e.g. [http://domain.tld/some.link]
1678 if ( $text == '' ) {
1680 $langObj = $this->getTargetLanguage();
1681 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1682 $linktype = 'autonumber';
1684 # Have link text, e.g. [http://domain.tld/some.link text]s
1686 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1689 $text = $this->getConverterLanguage()->markNoConversion( $text );
1691 $url = Sanitizer
::cleanUrl( $url );
1693 # Use the encoded URL
1694 # This means that users can paste URLs directly into the text
1695 # Funny characters like ö aren't valid in URLs anyway
1696 # This was changed in August 2004
1697 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1698 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1700 # Register link in the output object.
1701 # Replace unnecessary URL escape codes with the referenced character
1702 # This prevents spammers from hiding links from the filters
1703 $pasteurized = self
::replaceUnusualEscapes( $url );
1704 $this->mOutput
->addExternalLink( $pasteurized );
1707 wfProfileOut( __METHOD__
);
1712 * Get the rel attribute for a particular external link.
1715 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1716 * nofollow if appropriate
1717 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1718 * @return string|null Rel attribute for $url
1720 public static function getExternalLinkRel( $url = false, $title = null ) {
1721 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1722 $ns = $title ?
$title->getNamespace() : false;
1723 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1724 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1732 * Get an associative array of additional HTML attributes appropriate for a
1733 * particular external link. This currently may include rel => nofollow
1734 * (depending on configuration, namespace, and the URL's domain) and/or a
1735 * target attribute (depending on configuration).
1737 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1738 * nofollow if appropriate
1739 * @return array Associative array of HTML attributes
1741 function getExternalLinkAttribs( $url = false ) {
1743 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1745 if ( $this->mOptions
->getExternalLinkTarget() ) {
1746 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1752 * Replace unusual URL escape codes with their equivalent characters
1754 * @param string $url
1757 * @todo This can merge genuinely required bits in the path or query string,
1758 * breaking legit URLs. A proper fix would treat the various parts of
1759 * the URL differently; as a workaround, just use the output for
1760 * statistical records, not for actual linking/output.
1762 static function replaceUnusualEscapes( $url ) {
1763 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1764 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1768 * Callback function used in replaceUnusualEscapes().
1769 * Replaces unusual URL escape codes with their equivalent character
1771 * @param array $matches
1775 private static function replaceUnusualEscapesCallback( $matches ) {
1776 $char = urldecode( $matches[0] );
1777 $ord = ord( $char );
1778 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1779 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1780 # No, shouldn't be escaped
1783 # Yes, leave it escaped
1789 * make an image if it's allowed, either through the global
1790 * option, through the exception, or through the on-wiki whitelist
1793 * $param string $url
1797 function maybeMakeExternalImage( $url ) {
1798 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1799 $imagesexception = !empty( $imagesfrom );
1801 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1802 if ( $imagesexception && is_array( $imagesfrom ) ) {
1803 $imagematch = false;
1804 foreach ( $imagesfrom as $match ) {
1805 if ( strpos( $url, $match ) === 0 ) {
1810 } elseif ( $imagesexception ) {
1811 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1813 $imagematch = false;
1815 if ( $this->mOptions
->getAllowExternalImages()
1816 ||
( $imagesexception && $imagematch ) ) {
1817 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1819 $text = Linker
::makeExternalImage( $url );
1822 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1823 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1824 $whitelist = explode( "\n", wfMessage( 'external_image_whitelist' )->inContentLanguage()->text() );
1825 foreach ( $whitelist as $entry ) {
1826 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1827 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1830 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1831 # Image matches a whitelist entry
1832 $text = Linker
::makeExternalImage( $url );
1841 * Process [[ ]] wikilinks
1845 * @return string Processed text
1849 function replaceInternalLinks( $s ) {
1850 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1855 * Process [[ ]] wikilinks (RIL)
1857 * @throws MWException
1858 * @return LinkHolderArray
1862 function replaceInternalLinks2( &$s ) {
1863 wfProfileIn( __METHOD__
);
1865 wfProfileIn( __METHOD__
. '-setup' );
1866 static $tc = false, $e1, $e1_img;
1867 # the % is needed to support urlencoded titles as well
1869 $tc = Title
::legalChars() . '#%';
1870 # Match a link having the form [[namespace:link|alternate]]trail
1871 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1872 # Match cases where there is no "]]", which might still be images
1873 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1876 $holders = new LinkHolderArray( $this );
1878 # split the entire text string on occurrences of [[
1879 $a = StringUtils
::explode( '[[', ' ' . $s );
1880 # get the first element (all text up to first [[), and remove the space we added
1883 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1884 $s = substr( $s, 1 );
1886 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1888 if ( $useLinkPrefixExtension ) {
1889 # Match the end of a line for a word that's not followed by whitespace,
1890 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1892 $charset = $wgContLang->linkPrefixCharset();
1893 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
1896 if ( is_null( $this->mTitle
) ) {
1897 wfProfileOut( __METHOD__
. '-setup' );
1898 wfProfileOut( __METHOD__
);
1899 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
1901 $nottalk = !$this->mTitle
->isTalkPage();
1903 if ( $useLinkPrefixExtension ) {
1905 if ( preg_match( $e2, $s, $m ) ) {
1906 $first_prefix = $m[2];
1908 $first_prefix = false;
1914 $useSubpages = $this->areSubpagesAllowed();
1915 wfProfileOut( __METHOD__
. '-setup' );
1917 # Loop for each link
1918 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
1919 # Check for excessive memory usage
1920 if ( $holders->isBig() ) {
1922 # Do the existence check, replace the link holders and clear the array
1923 $holders->replace( $s );
1927 if ( $useLinkPrefixExtension ) {
1928 wfProfileIn( __METHOD__
. '-prefixhandling' );
1929 if ( preg_match( $e2, $s, $m ) ) {
1936 if ( $first_prefix ) {
1937 $prefix = $first_prefix;
1938 $first_prefix = false;
1940 wfProfileOut( __METHOD__
. '-prefixhandling' );
1943 $might_be_img = false;
1945 wfProfileIn( __METHOD__
. "-e1" );
1946 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1948 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1949 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1950 # the real problem is with the $e1 regex
1953 # Still some problems for cases where the ] is meant to be outside punctuation,
1954 # and no image is in sight. See bug 2095.
1957 && substr( $m[3], 0, 1 ) === ']'
1958 && strpos( $text, '[' ) !== false
1960 $text .= ']'; # so that replaceExternalLinks($text) works later
1961 $m[3] = substr( $m[3], 1 );
1963 # fix up urlencoded title texts
1964 if ( strpos( $m[1], '%' ) !== false ) {
1965 # Should anchors '#' also be rejected?
1966 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) );
1969 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1970 $might_be_img = true;
1972 if ( strpos( $m[1], '%' ) !== false ) {
1973 $m[1] = rawurldecode( $m[1] );
1976 } else { # Invalid form; output directly
1977 $s .= $prefix . '[[' . $line;
1978 wfProfileOut( __METHOD__
. "-e1" );
1981 wfProfileOut( __METHOD__
. "-e1" );
1982 wfProfileIn( __METHOD__
. "-misc" );
1984 # Don't allow internal links to pages containing
1985 # PROTO: where PROTO is a valid URL protocol; these
1986 # should be external links.
1987 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $m[1] ) ) {
1988 $s .= $prefix . '[[' . $line;
1989 wfProfileOut( __METHOD__
. "-misc" );
1993 # Make subpage if necessary
1994 if ( $useSubpages ) {
1995 $link = $this->maybeDoSubpageLink( $m[1], $text );
2000 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
2002 # Strip off leading ':'
2003 $link = substr( $link, 1 );
2006 wfProfileOut( __METHOD__
. "-misc" );
2007 wfProfileIn( __METHOD__
. "-title" );
2008 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
2009 if ( $nt === null ) {
2010 $s .= $prefix . '[[' . $line;
2011 wfProfileOut( __METHOD__
. "-title" );
2015 $ns = $nt->getNamespace();
2016 $iw = $nt->getInterwiki();
2017 wfProfileOut( __METHOD__
. "-title" );
2019 if ( $might_be_img ) { # if this is actually an invalid link
2020 wfProfileIn( __METHOD__
. "-might_be_img" );
2021 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2024 # look at the next 'line' to see if we can close it there
2026 $next_line = $a->current();
2027 if ( $next_line === false ||
$next_line === null ) {
2030 $m = explode( ']]', $next_line, 3 );
2031 if ( count( $m ) == 3 ) {
2032 # the first ]] closes the inner link, the second the image
2034 $text .= "[[{$m[0]}]]{$m[1]}";
2037 } elseif ( count( $m ) == 2 ) {
2038 # if there's exactly one ]] that's fine, we'll keep looking
2039 $text .= "[[{$m[0]}]]{$m[1]}";
2041 # if $next_line is invalid too, we need look no further
2042 $text .= '[[' . $next_line;
2047 # we couldn't find the end of this imageLink, so output it raw
2048 # but don't ignore what might be perfectly normal links in the text we've examined
2049 $holders->merge( $this->replaceInternalLinks2( $text ) );
2050 $s .= "{$prefix}[[$link|$text";
2051 # note: no $trail, because without an end, there *is* no trail
2052 wfProfileOut( __METHOD__
. "-might_be_img" );
2055 } else { # it's not an image, so output it raw
2056 $s .= "{$prefix}[[$link|$text";
2057 # note: no $trail, because without an end, there *is* no trail
2058 wfProfileOut( __METHOD__
. "-might_be_img" );
2061 wfProfileOut( __METHOD__
. "-might_be_img" );
2064 $wasblank = ( $text == '' );
2068 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
2069 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2070 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2071 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2072 $text = $this->doQuotes( $text );
2075 # Link not escaped by : , create the various objects
2078 wfProfileIn( __METHOD__
. "-interwiki" );
2079 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && Language
::fetchLanguageName( $iw, null, 'mw' ) ) {
2080 // XXX: the above check prevents links to sites with identifiers that are not language codes
2082 # Bug 24502: filter duplicates
2083 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2084 $this->mLangLinkLanguages
[$iw] = true;
2085 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2088 $s = rtrim( $s . $prefix );
2089 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2090 wfProfileOut( __METHOD__
. "-interwiki" );
2093 wfProfileOut( __METHOD__
. "-interwiki" );
2095 if ( $ns == NS_FILE
) {
2096 wfProfileIn( __METHOD__
. "-image" );
2097 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2099 # if no parameters were passed, $text
2100 # becomes something like "File:Foo.png",
2101 # which we don't want to pass on to the
2105 # recursively parse links inside the image caption
2106 # actually, this will parse them in any other parameters, too,
2107 # but it might be hard to fix that, and it doesn't matter ATM
2108 $text = $this->replaceExternalLinks( $text );
2109 $holders->merge( $this->replaceInternalLinks2( $text ) );
2111 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2112 $s .= $prefix . $this->armorLinks(
2113 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2115 $s .= $prefix . $trail;
2117 wfProfileOut( __METHOD__
. "-image" );
2121 if ( $ns == NS_CATEGORY
) {
2122 wfProfileIn( __METHOD__
. "-category" );
2123 $s = rtrim( $s . "\n" ); # bug 87
2126 $sortkey = $this->getDefaultSort();
2130 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2131 $sortkey = str_replace( "\n", '', $sortkey );
2132 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2133 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2136 * Strip the whitespace Category links produce, see bug 87
2138 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2140 wfProfileOut( __METHOD__
. "-category" );
2145 # Self-link checking. For some languages, variants of the title are checked in
2146 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2147 # for linking to a different variant.
2148 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2149 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2153 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2154 # @todo FIXME: Should do batch file existence checks, see comment below
2155 if ( $ns == NS_MEDIA
) {
2156 wfProfileIn( __METHOD__
. "-media" );
2157 # Give extensions a chance to select the file revision for us
2160 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2161 array( $this, $nt, &$options, &$descQuery ) );
2162 # Fetch and register the file (file title may be different via hooks)
2163 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2164 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2165 $s .= $prefix . $this->armorLinks(
2166 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2167 wfProfileOut( __METHOD__
. "-media" );
2171 wfProfileIn( __METHOD__
. "-always_known" );
2172 # Some titles, such as valid special pages or files in foreign repos, should
2173 # be shown as bluelinks even though they're not included in the page table
2175 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2176 # batch file existence checks for NS_FILE and NS_MEDIA
2177 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2178 $this->mOutput
->addLink( $nt );
2179 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2181 # Links will be added to the output link list after checking
2182 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2184 wfProfileOut( __METHOD__
. "-always_known" );
2186 wfProfileOut( __METHOD__
);
2191 * Render a forced-blue link inline; protect against double expansion of
2192 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2193 * Since this little disaster has to split off the trail text to avoid
2194 * breaking URLs in the following text without breaking trails on the
2195 * wiki links, it's been made into a horrible function.
2198 * @param string $text
2199 * @param array|string $query
2200 * @param string $trail
2201 * @param string $prefix
2202 * @return string HTML-wikitext mix oh yuck
2204 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2205 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2207 if ( is_string( $query ) ) {
2208 $query = wfCgiToArray( $query );
2210 if ( $text == '' ) {
2211 $text = htmlspecialchars( $nt->getPrefixedText() );
2214 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2216 return $this->armorLinks( $link ) . $trail;
2220 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2221 * going to go through further parsing steps before inline URL expansion.
2223 * Not needed quite as much as it used to be since free links are a bit
2224 * more sensible these days. But bracketed links are still an issue.
2226 * @param string $text More-or-less HTML
2227 * @return string Less-or-more HTML with NOPARSE bits
2229 function armorLinks( $text ) {
2230 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2231 "{$this->mUniqPrefix}NOPARSE$1", $text );
2235 * Return true if subpage links should be expanded on this page.
2238 function areSubpagesAllowed() {
2239 # Some namespaces don't allow subpages
2240 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2244 * Handle link to subpage if necessary
2246 * @param string $target The source of the link
2247 * @param string &$text The link text, modified as necessary
2248 * @return string The full name of the link
2251 function maybeDoSubpageLink( $target, &$text ) {
2252 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2256 * Used by doBlockLevels()
2261 function closeParagraph() {
2263 if ( $this->mLastSection
!= '' ) {
2264 $result = '</' . $this->mLastSection
. ">\n";
2266 $this->mInPre
= false;
2267 $this->mLastSection
= '';
2272 * getCommon() returns the length of the longest common substring
2273 * of both arguments, starting at the beginning of both.
2276 * @param string $st1
2277 * @param string $st2
2281 function getCommon( $st1, $st2 ) {
2282 $fl = strlen( $st1 );
2283 $shorter = strlen( $st2 );
2284 if ( $fl < $shorter ) {
2288 for ( $i = 0; $i < $shorter; ++
$i ) {
2289 if ( $st1[$i] != $st2[$i] ) {
2297 * These next three functions open, continue, and close the list
2298 * element appropriate to the prefix character passed into them.
2301 * @param string $char
2305 function openList( $char ) {
2306 $result = $this->closeParagraph();
2308 if ( '*' === $char ) {
2309 $result .= "<ul>\n<li>";
2310 } elseif ( '#' === $char ) {
2311 $result .= "<ol>\n<li>";
2312 } elseif ( ':' === $char ) {
2313 $result .= "<dl>\n<dd>";
2314 } elseif ( ';' === $char ) {
2315 $result .= "<dl>\n<dt>";
2316 $this->mDTopen
= true;
2318 $result = '<!-- ERR 1 -->';
2326 * @param string $char
2331 function nextItem( $char ) {
2332 if ( '*' === $char ||
'#' === $char ) {
2333 return "</li>\n<li>";
2334 } elseif ( ':' === $char ||
';' === $char ) {
2336 if ( $this->mDTopen
) {
2339 if ( ';' === $char ) {
2340 $this->mDTopen
= true;
2341 return $close . '<dt>';
2343 $this->mDTopen
= false;
2344 return $close . '<dd>';
2347 return '<!-- ERR 2 -->';
2352 * @param string $char
2357 function closeList( $char ) {
2358 if ( '*' === $char ) {
2359 $text = "</li>\n</ul>";
2360 } elseif ( '#' === $char ) {
2361 $text = "</li>\n</ol>";
2362 } elseif ( ':' === $char ) {
2363 if ( $this->mDTopen
) {
2364 $this->mDTopen
= false;
2365 $text = "</dt>\n</dl>";
2367 $text = "</dd>\n</dl>";
2370 return '<!-- ERR 3 -->';
2372 return $text . "\n";
2377 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2379 * @param string $text
2380 * @param bool $linestart Whether or not this is at the start of a line.
2382 * @return string The lists rendered as HTML
2384 function doBlockLevels( $text, $linestart ) {
2385 wfProfileIn( __METHOD__
);
2387 # Parsing through the text line by line. The main thing
2388 # happening here is handling of block-level elements p, pre,
2389 # and making lists from lines starting with * # : etc.
2391 $textLines = StringUtils
::explode( "\n", $text );
2393 $lastPrefix = $output = '';
2394 $this->mDTopen
= $inBlockElem = false;
2396 $paragraphStack = false;
2397 $inBlockquote = false;
2399 foreach ( $textLines as $oLine ) {
2401 if ( !$linestart ) {
2411 $lastPrefixLength = strlen( $lastPrefix );
2412 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2413 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2414 # If not in a <pre> element, scan for and figure out what prefixes are there.
2415 if ( !$this->mInPre
) {
2416 # Multiple prefixes may abut each other for nested lists.
2417 $prefixLength = strspn( $oLine, '*#:;' );
2418 $prefix = substr( $oLine, 0, $prefixLength );
2421 # ; and : are both from definition-lists, so they're equivalent
2422 # for the purposes of determining whether or not we need to open/close
2424 $prefix2 = str_replace( ';', ':', $prefix );
2425 $t = substr( $oLine, $prefixLength );
2426 $this->mInPre
= (bool)$preOpenMatch;
2428 # Don't interpret any other prefixes in preformatted text
2430 $prefix = $prefix2 = '';
2435 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2436 # Same as the last item, so no need to deal with nesting or opening stuff
2437 $output .= $this->nextItem( substr( $prefix, -1 ) );
2438 $paragraphStack = false;
2440 if ( substr( $prefix, -1 ) === ';' ) {
2441 # The one nasty exception: definition lists work like this:
2442 # ; title : definition text
2443 # So we check for : in the remainder text to split up the
2444 # title and definition, without b0rking links.
2446 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2448 $output .= $term . $this->nextItem( ':' );
2451 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2452 # We need to open or close prefixes, or both.
2454 # Either open or close a level...
2455 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2456 $paragraphStack = false;
2458 # Close all the prefixes which aren't shared.
2459 while ( $commonPrefixLength < $lastPrefixLength ) {
2460 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2461 --$lastPrefixLength;
2464 # Continue the current prefix if appropriate.
2465 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2466 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2469 # Open prefixes where appropriate.
2470 while ( $prefixLength > $commonPrefixLength ) {
2471 $char = substr( $prefix, $commonPrefixLength, 1 );
2472 $output .= $this->openList( $char );
2474 if ( ';' === $char ) {
2475 # @todo FIXME: This is dupe of code above
2476 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2478 $output .= $term . $this->nextItem( ':' );
2481 ++
$commonPrefixLength;
2483 $lastPrefix = $prefix2;
2486 # If we have no prefixes, go to paragraph mode.
2487 if ( 0 == $prefixLength ) {
2488 wfProfileIn( __METHOD__
. "-paragraph" );
2489 # No prefix (not in list)--go to paragraph mode
2490 # XXX: use a stack for nestable elements like span, table and div
2491 $openmatch = preg_match( '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2492 $closematch = preg_match(
2493 '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|' .
2494 '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|<\\/mw:|' . $this->mUniqPrefix
. '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS', $t );
2495 if ( $openmatch or $closematch ) {
2496 $paragraphStack = false;
2497 # TODO bug 5718: paragraph closed
2498 $output .= $this->closeParagraph();
2499 if ( $preOpenMatch and !$preCloseMatch ) {
2500 $this->mInPre
= true;
2503 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t, $bqMatch, PREG_OFFSET_CAPTURE
, $bqOffset ) ) {
2504 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
2505 $bqOffset = $bqMatch[0][1] +
strlen( $bqMatch[0][0] );
2507 $inBlockElem = !$closematch;
2508 } elseif ( !$inBlockElem && !$this->mInPre
) {
2509 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) and !$inBlockquote ) {
2511 if ( $this->mLastSection
!== 'pre' ) {
2512 $paragraphStack = false;
2513 $output .= $this->closeParagraph() . '<pre>';
2514 $this->mLastSection
= 'pre';
2516 $t = substr( $t, 1 );
2519 if ( trim( $t ) === '' ) {
2520 if ( $paragraphStack ) {
2521 $output .= $paragraphStack . '<br />';
2522 $paragraphStack = false;
2523 $this->mLastSection
= 'p';
2525 if ( $this->mLastSection
!== 'p' ) {
2526 $output .= $this->closeParagraph();
2527 $this->mLastSection
= '';
2528 $paragraphStack = '<p>';
2530 $paragraphStack = '</p><p>';
2534 if ( $paragraphStack ) {
2535 $output .= $paragraphStack;
2536 $paragraphStack = false;
2537 $this->mLastSection
= 'p';
2538 } elseif ( $this->mLastSection
!== 'p' ) {
2539 $output .= $this->closeParagraph() . '<p>';
2540 $this->mLastSection
= 'p';
2545 wfProfileOut( __METHOD__
. "-paragraph" );
2547 # somewhere above we forget to get out of pre block (bug 785)
2548 if ( $preCloseMatch && $this->mInPre
) {
2549 $this->mInPre
= false;
2551 if ( $paragraphStack === false ) {
2552 $output .= $t . "\n";
2555 while ( $prefixLength ) {
2556 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2559 if ( $this->mLastSection
!= '' ) {
2560 $output .= '</' . $this->mLastSection
. '>';
2561 $this->mLastSection
= '';
2564 wfProfileOut( __METHOD__
);
2569 * Split up a string on ':', ignoring any occurrences inside tags
2570 * to prevent illegal overlapping.
2572 * @param string $str The string to split
2573 * @param string &$before Set to everything before the ':'
2574 * @param string &$after Set to everything after the ':'
2575 * @throws MWException
2576 * @return string The position of the ':', or false if none found
2578 function findColonNoLinks( $str, &$before, &$after ) {
2579 wfProfileIn( __METHOD__
);
2581 $pos = strpos( $str, ':' );
2582 if ( $pos === false ) {
2584 wfProfileOut( __METHOD__
);
2588 $lt = strpos( $str, '<' );
2589 if ( $lt === false ||
$lt > $pos ) {
2590 # Easy; no tag nesting to worry about
2591 $before = substr( $str, 0, $pos );
2592 $after = substr( $str, $pos +
1 );
2593 wfProfileOut( __METHOD__
);
2597 # Ugly state machine to walk through avoiding tags.
2598 $state = self
::COLON_STATE_TEXT
;
2600 $len = strlen( $str );
2601 for ( $i = 0; $i < $len; $i++
) {
2605 # (Using the number is a performance hack for common cases)
2606 case 0: # self::COLON_STATE_TEXT:
2609 # Could be either a <start> tag or an </end> tag
2610 $state = self
::COLON_STATE_TAGSTART
;
2613 if ( $stack == 0 ) {
2615 $before = substr( $str, 0, $i );
2616 $after = substr( $str, $i +
1 );
2617 wfProfileOut( __METHOD__
);
2620 # Embedded in a tag; don't break it.
2623 # Skip ahead looking for something interesting
2624 $colon = strpos( $str, ':', $i );
2625 if ( $colon === false ) {
2626 # Nothing else interesting
2627 wfProfileOut( __METHOD__
);
2630 $lt = strpos( $str, '<', $i );
2631 if ( $stack === 0 ) {
2632 if ( $lt === false ||
$colon < $lt ) {
2634 $before = substr( $str, 0, $colon );
2635 $after = substr( $str, $colon +
1 );
2636 wfProfileOut( __METHOD__
);
2640 if ( $lt === false ) {
2641 # Nothing else interesting to find; abort!
2642 # We're nested, but there's no close tags left. Abort!
2645 # Skip ahead to next tag start
2647 $state = self
::COLON_STATE_TAGSTART
;
2650 case 1: # self::COLON_STATE_TAG:
2655 $state = self
::COLON_STATE_TEXT
;
2658 # Slash may be followed by >?
2659 $state = self
::COLON_STATE_TAGSLASH
;
2665 case 2: # self::COLON_STATE_TAGSTART:
2668 $state = self
::COLON_STATE_CLOSETAG
;
2671 $state = self
::COLON_STATE_COMMENT
;
2674 # Illegal early close? This shouldn't happen D:
2675 $state = self
::COLON_STATE_TEXT
;
2678 $state = self
::COLON_STATE_TAG
;
2681 case 3: # self::COLON_STATE_CLOSETAG:
2686 wfDebug( __METHOD__
. ": Invalid input; too many close tags\n" );
2687 wfProfileOut( __METHOD__
);
2690 $state = self
::COLON_STATE_TEXT
;
2693 case self
::COLON_STATE_TAGSLASH
:
2695 # Yes, a self-closed tag <blah/>
2696 $state = self
::COLON_STATE_TEXT
;
2698 # Probably we're jumping the gun, and this is an attribute
2699 $state = self
::COLON_STATE_TAG
;
2702 case 5: # self::COLON_STATE_COMMENT:
2704 $state = self
::COLON_STATE_COMMENTDASH
;
2707 case self
::COLON_STATE_COMMENTDASH
:
2709 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2711 $state = self
::COLON_STATE_COMMENT
;
2714 case self
::COLON_STATE_COMMENTDASHDASH
:
2716 $state = self
::COLON_STATE_TEXT
;
2718 $state = self
::COLON_STATE_COMMENT
;
2722 wfProfileOut( __METHOD__
);
2723 throw new MWException( "State machine error in " . __METHOD__
);
2727 wfDebug( __METHOD__
. ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2728 wfProfileOut( __METHOD__
);
2731 wfProfileOut( __METHOD__
);
2736 * Return value of a magic variable (like PAGENAME)
2741 * @param bool|PPFrame $frame
2743 * @throws MWException
2746 function getVariableValue( $index, $frame = false ) {
2747 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2748 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2750 if ( is_null( $this->mTitle
) ) {
2751 // If no title set, bad things are going to happen
2752 // later. Title should always be set since this
2753 // should only be called in the middle of a parse
2754 // operation (but the unit-tests do funky stuff)
2755 throw new MWException( __METHOD__
. ' Should only be '
2756 . ' called while parsing (no title set)' );
2760 * Some of these require message or data lookups and can be
2761 * expensive to check many times.
2763 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2764 if ( isset( $this->mVarCache
[$index] ) ) {
2765 return $this->mVarCache
[$index];
2769 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2770 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2772 $pageLang = $this->getFunctionLang();
2775 case 'currentmonth':
2776 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ) );
2778 case 'currentmonth1':
2779 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2781 case 'currentmonthname':
2782 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2784 case 'currentmonthnamegen':
2785 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2787 case 'currentmonthabbrev':
2788 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2791 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ) );
2794 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ) );
2797 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ) );
2800 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2802 case 'localmonthname':
2803 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2805 case 'localmonthnamegen':
2806 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2808 case 'localmonthabbrev':
2809 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2812 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ) );
2815 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ) );
2818 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2821 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2823 case 'fullpagename':
2824 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2826 case 'fullpagenamee':
2827 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2830 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2832 case 'subpagenamee':
2833 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2835 case 'rootpagename':
2836 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2838 case 'rootpagenamee':
2839 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getRootText() ) ) );
2841 case 'basepagename':
2842 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2844 case 'basepagenamee':
2845 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2847 case 'talkpagename':
2848 if ( $this->mTitle
->canTalk() ) {
2849 $talkPage = $this->mTitle
->getTalkPage();
2850 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2855 case 'talkpagenamee':
2856 if ( $this->mTitle
->canTalk() ) {
2857 $talkPage = $this->mTitle
->getTalkPage();
2858 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2863 case 'subjectpagename':
2864 $subjPage = $this->mTitle
->getSubjectPage();
2865 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2867 case 'subjectpagenamee':
2868 $subjPage = $this->mTitle
->getSubjectPage();
2869 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2871 case 'pageid': // requested in bug 23427
2872 $pageid = $this->getTitle()->getArticleID();
2873 if ( $pageid == 0 ) {
2874 # 0 means the page doesn't exist in the database,
2875 # which means the user is previewing a new page.
2876 # The vary-revision flag must be set, because the magic word
2877 # will have a different value once the page is saved.
2878 $this->mOutput
->setFlag( 'vary-revision' );
2879 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2881 $value = $pageid ?
$pageid : null;
2884 # Let the edit saving system know we should parse the page
2885 # *after* a revision ID has been assigned.
2886 $this->mOutput
->setFlag( 'vary-revision' );
2887 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2888 $value = $this->mRevisionId
;
2891 # Let the edit saving system know we should parse the page
2892 # *after* a revision ID has been assigned. This is for null edits.
2893 $this->mOutput
->setFlag( 'vary-revision' );
2894 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2895 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2897 case 'revisionday2':
2898 # Let the edit saving system know we should parse the page
2899 # *after* a revision ID has been assigned. This is for null edits.
2900 $this->mOutput
->setFlag( 'vary-revision' );
2901 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2902 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2904 case 'revisionmonth':
2905 # Let the edit saving system know we should parse the page
2906 # *after* a revision ID has been assigned. This is for null edits.
2907 $this->mOutput
->setFlag( 'vary-revision' );
2908 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2909 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2911 case 'revisionmonth1':
2912 # Let the edit saving system know we should parse the page
2913 # *after* a revision ID has been assigned. This is for null edits.
2914 $this->mOutput
->setFlag( 'vary-revision' );
2915 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2916 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2918 case 'revisionyear':
2919 # Let the edit saving system know we should parse the page
2920 # *after* a revision ID has been assigned. This is for null edits.
2921 $this->mOutput
->setFlag( 'vary-revision' );
2922 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2923 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2925 case 'revisiontimestamp':
2926 # Let the edit saving system know we should parse the page
2927 # *after* a revision ID has been assigned. This is for null edits.
2928 $this->mOutput
->setFlag( 'vary-revision' );
2929 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2930 $value = $this->getRevisionTimestamp();
2932 case 'revisionuser':
2933 # Let the edit saving system know we should parse the page
2934 # *after* a revision ID has been assigned. This is for null edits.
2935 $this->mOutput
->setFlag( 'vary-revision' );
2936 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2937 $value = $this->getRevisionUser();
2939 case 'revisionsize':
2940 # Let the edit saving system know we should parse the page
2941 # *after* a revision ID has been assigned. This is for null edits.
2942 $this->mOutput
->setFlag( 'vary-revision' );
2943 wfDebug( __METHOD__
. ": {{REVISIONSIZE}} used, setting vary-revision...\n" );
2944 $value = $this->getRevisionSize();
2947 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2950 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2952 case 'namespacenumber':
2953 $value = $this->mTitle
->getNamespace();
2956 $value = $this->mTitle
->canTalk() ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() ) : '';
2959 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2961 case 'subjectspace':
2962 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
2964 case 'subjectspacee':
2965 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2967 case 'currentdayname':
2968 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
2971 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
2974 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2977 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
2980 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2981 # int to remove the padding
2982 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
2985 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
2987 case 'localdayname':
2988 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1 );
2991 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
2994 $value = $pageLang->time( MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ), false, false );
2997 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
3000 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3001 # int to remove the padding
3002 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
3005 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
3007 case 'numberofarticles':
3008 $value = $pageLang->formatNum( SiteStats
::articles() );
3010 case 'numberoffiles':
3011 $value = $pageLang->formatNum( SiteStats
::images() );
3013 case 'numberofusers':
3014 $value = $pageLang->formatNum( SiteStats
::users() );
3016 case 'numberofactiveusers':
3017 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
3019 case 'numberofpages':
3020 $value = $pageLang->formatNum( SiteStats
::pages() );
3022 case 'numberofadmins':
3023 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
3025 case 'numberofedits':
3026 $value = $pageLang->formatNum( SiteStats
::edits() );
3028 case 'numberofviews':
3029 global $wgDisableCounters;
3030 $value = !$wgDisableCounters ?
$pageLang->formatNum( SiteStats
::views() ) : '';
3032 case 'currenttimestamp':
3033 $value = wfTimestamp( TS_MW
, $ts );
3035 case 'localtimestamp':
3036 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
3038 case 'currentversion':
3039 $value = SpecialVersion
::getVersion();
3042 return $wgArticlePath;
3048 return $wgServerName;
3050 return $wgScriptPath;
3052 return $wgStylePath;
3053 case 'directionmark':
3054 return $pageLang->getDirMark();
3055 case 'contentlanguage':
3056 global $wgLanguageCode;
3057 return $wgLanguageCode;
3058 case 'cascadingsources':
3059 $value = CoreParserFunctions
::cascadingsources( $this );
3063 wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) );
3068 $this->mVarCache
[$index] = $value;
3075 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3079 function initialiseVariables() {
3080 wfProfileIn( __METHOD__
);
3081 $variableIDs = MagicWord
::getVariableIDs();
3082 $substIDs = MagicWord
::getSubstIDs();
3084 $this->mVariables
= new MagicWordArray( $variableIDs );
3085 $this->mSubstWords
= new MagicWordArray( $substIDs );
3086 wfProfileOut( __METHOD__
);
3090 * Preprocess some wikitext and return the document tree.
3091 * This is the ghost of replace_variables().
3093 * @param string $text The text to parse
3094 * @param int $flags Bitwise combination of:
3095 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
3096 * included. Default is to assume a direct page view.
3098 * The generated DOM tree must depend only on the input text and the flags.
3099 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3101 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3102 * change in the DOM tree for a given text, must be passed through the section identifier
3103 * in the section edit link and thus back to extractSections().
3105 * The output of this function is currently only cached in process memory, but a persistent
3106 * cache may be implemented at a later date which takes further advantage of these strict
3107 * dependency requirements.
3111 function preprocessToDom( $text, $flags = 0 ) {
3112 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3117 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3123 public static function splitWhitespace( $s ) {
3124 $ltrimmed = ltrim( $s );
3125 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3126 $trimmed = rtrim( $ltrimmed );
3127 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3129 $w2 = substr( $ltrimmed, -$diff );
3133 return array( $w1, $trimmed, $w2 );
3137 * Replace magic variables, templates, and template arguments
3138 * with the appropriate text. Templates are substituted recursively,
3139 * taking care to avoid infinite loops.
3141 * Note that the substitution depends on value of $mOutputType:
3142 * self::OT_WIKI: only {{subst:}} templates
3143 * self::OT_PREPROCESS: templates but not extension tags
3144 * self::OT_HTML: all templates and extension tags
3146 * @param string $text The text to transform
3147 * @param PPFrame $frame Object describing the arguments passed to the template.
3148 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
3149 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
3150 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
3155 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3156 # Is there any text? Also, Prevent too big inclusions!
3157 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3160 wfProfileIn( __METHOD__
);
3162 if ( $frame === false ) {
3163 $frame = $this->getPreprocessor()->newFrame();
3164 } elseif ( !( $frame instanceof PPFrame
) ) {
3165 wfDebug( __METHOD__
. " called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
3166 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3169 $dom = $this->preprocessToDom( $text );
3170 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3171 $text = $frame->expand( $dom, $flags );
3173 wfProfileOut( __METHOD__
);
3178 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3180 * @param array $args
3184 static function createAssocArgs( $args ) {
3185 $assocArgs = array();
3187 foreach ( $args as $arg ) {
3188 $eqpos = strpos( $arg, '=' );
3189 if ( $eqpos === false ) {
3190 $assocArgs[$index++
] = $arg;
3192 $name = trim( substr( $arg, 0, $eqpos ) );
3193 $value = trim( substr( $arg, $eqpos +
1 ) );
3194 if ( $value === false ) {
3197 if ( $name !== false ) {
3198 $assocArgs[$name] = $value;
3207 * Warn the user when a parser limitation is reached
3208 * Will warn at most once the user per limitation type
3210 * @param string $limitationType Should be one of:
3211 * 'expensive-parserfunction' (corresponding messages:
3212 * 'expensive-parserfunction-warning',
3213 * 'expensive-parserfunction-category')
3214 * 'post-expand-template-argument' (corresponding messages:
3215 * 'post-expand-template-argument-warning',
3216 * 'post-expand-template-argument-category')
3217 * 'post-expand-template-inclusion' (corresponding messages:
3218 * 'post-expand-template-inclusion-warning',
3219 * 'post-expand-template-inclusion-category')
3220 * 'node-count-exceeded' (corresponding messages:
3221 * 'node-count-exceeded-warning',
3222 * 'node-count-exceeded-category')
3223 * 'expansion-depth-exceeded' (corresponding messages:
3224 * 'expansion-depth-exceeded-warning',
3225 * 'expansion-depth-exceeded-category')
3226 * @param int|null $current Current value
3227 * @param int|null $max Maximum allowed, when an explicit limit has been
3228 * exceeded, provide the values (optional)
3230 function limitationWarn( $limitationType, $current = '', $max = '' ) {
3231 # does no harm if $current and $max are present but are unnecessary for the message
3232 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3233 ->inLanguage( $this->mOptions
->getUserLangObj() )->text();
3234 $this->mOutput
->addWarning( $warning );
3235 $this->addTrackingCategory( "$limitationType-category" );
3239 * Return the text of a template, after recursively
3240 * replacing any variables or templates within the template.
3242 * @param array $piece The parts of the template
3243 * $piece['title']: the title, i.e. the part before the |
3244 * $piece['parts']: the parameter array
3245 * $piece['lineStart']: whether the brace was at the start of a line
3246 * @param PPFrame $frame The current frame, contains template arguments
3247 * @throws MWException
3248 * @return string The text of the template
3251 function braceSubstitution( $piece, $frame ) {
3252 wfProfileIn( __METHOD__
);
3253 wfProfileIn( __METHOD__
. '-setup' );
3256 $found = false; # $text has been filled
3257 $nowiki = false; # wiki markup in $text should be escaped
3258 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3259 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3260 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3261 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3263 # Title object, where $text came from
3266 # $part1 is the bit before the first |, and must contain only title characters.
3267 # Various prefixes will be stripped from it later.
3268 $titleWithSpaces = $frame->expand( $piece['title'] );
3269 $part1 = trim( $titleWithSpaces );
3272 # Original title text preserved for various purposes
3273 $originalTitle = $part1;
3275 # $args is a list of argument nodes, starting from index 0, not including $part1
3276 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3277 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3278 wfProfileOut( __METHOD__
. '-setup' );
3280 $titleProfileIn = null; // profile templates
3283 wfProfileIn( __METHOD__
. '-modifiers' );
3286 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3288 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3289 # Decide whether to expand template or keep wikitext as-is.
3290 if ( $this->ot
['wiki'] ) {
3291 if ( $substMatch === false ) {
3292 $literal = true; # literal when in PST with no prefix
3294 $literal = false; # expand when in PST with subst: or safesubst:
3297 if ( $substMatch == 'subst' ) {
3298 $literal = true; # literal when not in PST with plain subst:
3300 $literal = false; # expand when not in PST with safesubst: or no prefix
3304 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3311 if ( !$found && $args->getLength() == 0 ) {
3312 $id = $this->mVariables
->matchStartToEnd( $part1 );
3313 if ( $id !== false ) {
3314 $text = $this->getVariableValue( $id, $frame );
3315 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3316 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3322 # MSG, MSGNW and RAW
3325 $mwMsgnw = MagicWord
::get( 'msgnw' );
3326 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3329 # Remove obsolete MSG:
3330 $mwMsg = MagicWord
::get( 'msg' );
3331 $mwMsg->matchStartAndRemove( $part1 );
3335 $mwRaw = MagicWord
::get( 'raw' );
3336 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3337 $forceRawInterwiki = true;
3340 wfProfileOut( __METHOD__
. '-modifiers' );
3344 wfProfileIn( __METHOD__
. '-pfunc' );
3346 $colonPos = strpos( $part1, ':' );
3347 if ( $colonPos !== false ) {
3348 $func = substr( $part1, 0, $colonPos );
3349 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3350 for ( $i = 0; $i < $args->getLength(); $i++
) {
3351 $funcArgs[] = $args->item( $i );
3354 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3355 } catch ( Exception
$ex ) {
3356 wfProfileOut( __METHOD__
. '-pfunc' );
3357 wfProfileOut( __METHOD__
);
3361 # The interface for parser functions allows for extracting
3362 # flags into the local scope. Extract any forwarded flags
3366 wfProfileOut( __METHOD__
. '-pfunc' );
3369 # Finish mangling title and then check for loops.
3370 # Set $title to a Title object and $titleText to the PDBK
3373 # Split the title into page and subpage
3375 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3376 if ( $part1 !== $relative ) {
3378 $ns = $this->mTitle
->getNamespace();
3380 $title = Title
::newFromText( $part1, $ns );
3382 $titleText = $title->getPrefixedText();
3383 # Check for language variants if the template is not found
3384 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3385 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3387 # Do recursion depth check
3388 $limit = $this->mOptions
->getMaxTemplateDepth();
3389 if ( $frame->depth
>= $limit ) {
3391 $text = '<span class="error">'
3392 . wfMessage( 'parser-template-recursion-depth-warning' )
3393 ->numParams( $limit )->inContentLanguage()->text()
3399 # Load from database
3400 if ( !$found && $title ) {
3401 if ( !Profiler
::instance()->isPersistent() ) {
3402 # Too many unique items can kill profiling DBs/collectors
3403 $titleProfileIn = __METHOD__
. "-title-" . $title->getPrefixedDBkey();
3404 wfProfileIn( $titleProfileIn ); // template in
3406 wfProfileIn( __METHOD__
. '-loadtpl' );
3407 if ( !$title->isExternal() ) {
3408 if ( $title->isSpecialPage()
3409 && $this->mOptions
->getAllowSpecialInclusion()
3410 && $this->ot
['html']
3412 // Pass the template arguments as URL parameters.
3413 // "uselang" will have no effect since the Language object
3414 // is forced to the one defined in ParserOptions.
3415 $pageArgs = array();
3416 for ( $i = 0; $i < $args->getLength(); $i++
) {
3417 $bits = $args->item( $i )->splitArg();
3418 if ( strval( $bits['index'] ) === '' ) {
3419 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3420 $value = trim( $frame->expand( $bits['value'] ) );
3421 $pageArgs[$name] = $value;
3425 // Create a new context to execute the special page
3426 $context = new RequestContext
;
3427 $context->setTitle( $title );
3428 $context->setRequest( new FauxRequest( $pageArgs ) );
3429 $context->setUser( $this->getUser() );
3430 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3431 $ret = SpecialPageFactory
::capturePath( $title, $context );
3433 $text = $context->getOutput()->getHTML();
3434 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3437 $this->disableCache();
3439 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3440 $found = false; # access denied
3441 wfDebug( __METHOD__
. ": template inclusion denied for " .
3442 $title->getPrefixedDBkey() . "\n" );
3444 list( $text, $title ) = $this->getTemplateDom( $title );
3445 if ( $text !== false ) {
3451 # If the title is valid but undisplayable, make a link to it
3452 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3453 $text = "[[:$titleText]]";
3456 } elseif ( $title->isTrans() ) {
3457 # Interwiki transclusion
3458 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3459 $text = $this->interwikiTransclude( $title, 'render' );
3462 $text = $this->interwikiTransclude( $title, 'raw' );
3463 # Preprocess it like a template
3464 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3470 # Do infinite loop check
3471 # This has to be done after redirect resolution to avoid infinite loops via redirects
3472 if ( !$frame->loopCheck( $title ) ) {
3474 $text = '<span class="error">'
3475 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3477 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3479 wfProfileOut( __METHOD__
. '-loadtpl' );
3482 # If we haven't found text to substitute by now, we're done
3483 # Recover the source wikitext and return it
3485 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3486 if ( $titleProfileIn ) {
3487 wfProfileOut( $titleProfileIn ); // template out
3489 wfProfileOut( __METHOD__
);
3490 return array( 'object' => $text );
3493 # Expand DOM-style return values in a child frame
3494 if ( $isChildObj ) {
3495 # Clean up argument array
3496 $newFrame = $frame->newChild( $args, $title );
3499 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3500 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3501 # Expansion is eligible for the empty-frame cache
3502 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3503 $text = $this->mTplExpandCache
[$titleText];
3505 $text = $newFrame->expand( $text );
3506 $this->mTplExpandCache
[$titleText] = $text;
3509 # Uncached expansion
3510 $text = $newFrame->expand( $text );
3513 if ( $isLocalObj && $nowiki ) {
3514 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3515 $isLocalObj = false;
3518 if ( $titleProfileIn ) {
3519 wfProfileOut( $titleProfileIn ); // template out
3522 # Replace raw HTML by a placeholder
3524 $text = $this->insertStripItem( $text );
3525 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3526 # Escape nowiki-style return values
3527 $text = wfEscapeWikiText( $text );
3528 } elseif ( is_string( $text )
3529 && !$piece['lineStart']
3530 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3532 # Bug 529: if the template begins with a table or block-level
3533 # element, it should be treated as beginning a new line.
3534 # This behavior is somewhat controversial.
3535 $text = "\n" . $text;
3538 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3539 # Error, oversize inclusion
3540 if ( $titleText !== false ) {
3541 # Make a working, properly escaped link if possible (bug 23588)
3542 $text = "[[:$titleText]]";
3544 # This will probably not be a working link, but at least it may
3545 # provide some hint of where the problem is
3546 preg_replace( '/^:/', '', $originalTitle );
3547 $text = "[[:$originalTitle]]";
3549 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3550 $this->limitationWarn( 'post-expand-template-inclusion' );
3553 if ( $isLocalObj ) {
3554 $ret = array( 'object' => $text );
3556 $ret = array( 'text' => $text );
3559 wfProfileOut( __METHOD__
);
3564 * Call a parser function and return an array with text and flags.
3566 * The returned array will always contain a boolean 'found', indicating
3567 * whether the parser function was found or not. It may also contain the
3569 * text: string|object, resulting wikitext or PP DOM object
3570 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3571 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3572 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3573 * nowiki: bool, wiki markup in $text should be escaped
3576 * @param PPFrame $frame The current frame, contains template arguments
3577 * @param string $function Function name
3578 * @param array $args Arguments to the function
3581 public function callParserFunction( $frame, $function, array $args = array() ) {
3584 wfProfileIn( __METHOD__
);
3586 # Case sensitive functions
3587 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3588 $function = $this->mFunctionSynonyms
[1][$function];
3590 # Case insensitive functions
3591 $function = $wgContLang->lc( $function );
3592 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3593 $function = $this->mFunctionSynonyms
[0][$function];
3595 wfProfileOut( __METHOD__
);
3596 return array( 'found' => false );
3600 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3601 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3603 # Workaround for PHP bug 35229 and similar
3604 if ( !is_callable( $callback ) ) {
3605 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3606 wfProfileOut( __METHOD__
);
3607 throw new MWException( "Tag hook for $function is not callable\n" );
3610 $allArgs = array( &$this );
3611 if ( $flags & SFH_OBJECT_ARGS
) {
3612 # Convert arguments to PPNodes and collect for appending to $allArgs
3613 $funcArgs = array();
3614 foreach ( $args as $k => $v ) {
3615 if ( $v instanceof PPNode ||
$k === 0 ) {
3618 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( array( $k => $v ) )->item( 0 );
3622 # Add a frame parameter, and pass the arguments as an array
3623 $allArgs[] = $frame;
3624 $allArgs[] = $funcArgs;
3626 # Convert arguments to plain text and append to $allArgs
3627 foreach ( $args as $k => $v ) {
3628 if ( $v instanceof PPNode
) {
3629 $allArgs[] = trim( $frame->expand( $v ) );
3630 } elseif ( is_int( $k ) && $k >= 0 ) {
3631 $allArgs[] = trim( $v );
3633 $allArgs[] = trim( "$k=$v" );
3638 $result = call_user_func_array( $callback, $allArgs );
3640 # The interface for function hooks allows them to return a wikitext
3641 # string or an array containing the string and any flags. This mungs
3642 # things around to match what this method should return.
3643 if ( !is_array( $result ) ) {
3649 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3650 $result['text'] = $result[0];
3652 unset( $result[0] );
3659 $preprocessFlags = 0;
3660 if ( isset( $result['noparse'] ) ) {
3661 $noparse = $result['noparse'];
3663 if ( isset( $result['preprocessFlags'] ) ) {
3664 $preprocessFlags = $result['preprocessFlags'];
3668 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3669 $result['isChildObj'] = true;
3671 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3672 wfProfileOut( __METHOD__
);
3678 * Get the semi-parsed DOM representation of a template with a given title,
3679 * and its redirect destination title. Cached.
3681 * @param Title $title
3685 function getTemplateDom( $title ) {
3686 $cacheTitle = $title;
3687 $titleText = $title->getPrefixedDBkey();
3689 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3690 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3691 $title = Title
::makeTitle( $ns, $dbk );
3692 $titleText = $title->getPrefixedDBkey();
3694 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3695 return array( $this->mTplDomCache
[$titleText], $title );
3698 # Cache miss, go to the database
3699 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3701 if ( $text === false ) {
3702 $this->mTplDomCache
[$titleText] = false;
3703 return array( false, $title );
3706 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3707 $this->mTplDomCache
[$titleText] = $dom;
3709 if ( !$title->equals( $cacheTitle ) ) {
3710 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3711 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3714 return array( $dom, $title );
3718 * Fetch the unparsed text of a template and register a reference to it.
3719 * @param Title $title
3720 * @return array ( string or false, Title )
3722 function fetchTemplateAndTitle( $title ) {
3723 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3724 $stuff = call_user_func( $templateCb, $title, $this );
3725 $text = $stuff['text'];
3726 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3727 if ( isset( $stuff['deps'] ) ) {
3728 foreach ( $stuff['deps'] as $dep ) {
3729 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3730 if ( $dep['title']->equals( $this->getTitle() ) ) {
3731 // If we transclude ourselves, the final result
3732 // will change based on the new version of the page
3733 $this->mOutput
->setFlag( 'vary-revision' );
3737 return array( $text, $finalTitle );
3741 * Fetch the unparsed text of a template and register a reference to it.
3742 * @param Title $title
3743 * @return string|bool
3745 function fetchTemplate( $title ) {
3746 $rv = $this->fetchTemplateAndTitle( $title );
3751 * Static function to get a template
3752 * Can be overridden via ParserOptions::setTemplateCallback().
3754 * @param Title $title
3755 * @param Parser $parser
3759 static function statelessFetchTemplate( $title, $parser = false ) {
3760 $text = $skip = false;
3761 $finalTitle = $title;
3764 # Loop to fetch the article, with up to 1 redirect
3765 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3766 # Give extensions a chance to select the revision instead
3767 $id = false; # Assume current
3768 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3769 array( $parser, $title, &$skip, &$id ) );
3775 'page_id' => $title->getArticleID(),
3782 ? Revision
::newFromId( $id )
3783 : Revision
::newFromTitle( $title, false, Revision
::READ_NORMAL
);
3784 $rev_id = $rev ?
$rev->getId() : 0;
3785 # If there is no current revision, there is no page
3786 if ( $id === false && !$rev ) {
3787 $linkCache = LinkCache
::singleton();
3788 $linkCache->addBadLinkObj( $title );
3793 'page_id' => $title->getArticleID(),
3794 'rev_id' => $rev_id );
3795 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3796 # We fetched a rev from a different title; register it too...
3798 'title' => $rev->getTitle(),
3799 'page_id' => $rev->getPage(),
3800 'rev_id' => $rev_id );
3804 $content = $rev->getContent();
3805 $text = $content ?
$content->getWikitextForTransclusion() : null;
3807 if ( $text === false ||
$text === null ) {
3811 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3813 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3814 if ( !$message->exists() ) {
3818 $content = $message->content();
3819 $text = $message->plain();
3827 $finalTitle = $title;
3828 $title = $content->getRedirectTarget();
3832 'finalTitle' => $finalTitle,
3837 * Fetch a file and its title and register a reference to it.
3838 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3839 * @param Title $title
3840 * @param array $options Array of options to RepoGroup::findFile
3843 function fetchFile( $title, $options = array() ) {
3844 $res = $this->fetchFileAndTitle( $title, $options );
3849 * Fetch a file and its title and register a reference to it.
3850 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3851 * @param Title $title
3852 * @param array $options Array of options to RepoGroup::findFile
3853 * @return array ( File or false, Title of file )
3855 function fetchFileAndTitle( $title, $options = array() ) {
3856 $file = $this->fetchFileNoRegister( $title, $options );
3858 $time = $file ?
$file->getTimestamp() : false;
3859 $sha1 = $file ?
$file->getSha1() : false;
3860 # Register the file as a dependency...
3861 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3862 if ( $file && !$title->equals( $file->getTitle() ) ) {
3863 # Update fetched file title
3864 $title = $file->getTitle();
3865 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3867 return array( $file, $title );
3871 * Helper function for fetchFileAndTitle.
3873 * Also useful if you need to fetch a file but not use it yet,
3874 * for example to get the file's handler.
3876 * @param Title $title
3877 * @param array $options Array of options to RepoGroup::findFile
3880 protected function fetchFileNoRegister( $title, $options = array() ) {
3881 if ( isset( $options['broken'] ) ) {
3882 $file = false; // broken thumbnail forced by hook
3883 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3884 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3885 } else { // get by (name,timestamp)
3886 $file = wfFindFile( $title, $options );
3892 * Transclude an interwiki link.
3894 * @param Title $title
3895 * @param string $action
3899 function interwikiTransclude( $title, $action ) {
3900 global $wgEnableScaryTranscluding;
3902 if ( !$wgEnableScaryTranscluding ) {
3903 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
3906 $url = $title->getFullURL( array( 'action' => $action ) );
3908 if ( strlen( $url ) > 255 ) {
3909 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3911 return $this->fetchScaryTemplateMaybeFromCache( $url );
3915 * @param string $url
3916 * @return mixed|string
3918 function fetchScaryTemplateMaybeFromCache( $url ) {
3919 global $wgTranscludeCacheExpiry;
3920 $dbr = wfGetDB( DB_SLAVE
);
3921 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3922 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
3923 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3925 return $obj->tc_contents
;
3928 $req = MWHttpRequest
::factory( $url );
3929 $status = $req->execute(); // Status object
3930 if ( $status->isOK() ) {
3931 $text = $req->getContent();
3932 } elseif ( $req->getStatus() != 200 ) { // Though we failed to fetch the content, this status is useless.
3933 return wfMessage( 'scarytranscludefailed-httpstatus', $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
3935 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3938 $dbw = wfGetDB( DB_MASTER
);
3939 $dbw->replace( 'transcache', array( 'tc_url' ), array(
3941 'tc_time' => $dbw->timestamp( time() ),
3942 'tc_contents' => $text
3948 * Triple brace replacement -- used for template arguments
3951 * @param array $piece
3952 * @param PPFrame $frame
3956 function argSubstitution( $piece, $frame ) {
3957 wfProfileIn( __METHOD__
);
3960 $parts = $piece['parts'];
3961 $nameWithSpaces = $frame->expand( $piece['title'] );
3962 $argName = trim( $nameWithSpaces );
3964 $text = $frame->getArgument( $argName );
3965 if ( $text === false && $parts->getLength() > 0
3966 && ( $this->ot
['html']
3968 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3971 # No match in frame, use the supplied default
3972 $object = $parts->item( 0 )->getChildren();
3974 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3975 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3976 $this->limitationWarn( 'post-expand-template-argument' );
3979 if ( $text === false && $object === false ) {
3981 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3983 if ( $error !== false ) {
3986 if ( $object !== false ) {
3987 $ret = array( 'object' => $object );
3989 $ret = array( 'text' => $text );
3992 wfProfileOut( __METHOD__
);
3997 * Return the text to be used for a given extension tag.
3998 * This is the ghost of strip().
4000 * @param array $params Associative array of parameters:
4001 * name PPNode for the tag name
4002 * attr PPNode for unparsed text where tag attributes are thought to be
4003 * attributes Optional associative array of parsed attributes
4004 * inner Contents of extension element
4005 * noClose Original text did not have a close tag
4006 * @param PPFrame $frame
4008 * @throws MWException
4011 function extensionSubstitution( $params, $frame ) {
4012 $name = $frame->expand( $params['name'] );
4013 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
4014 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
4015 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
4017 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
4018 ( $this->ot
['html'] ||
$this->ot
['pre'] );
4019 if ( $isFunctionTag ) {
4020 $markerType = 'none';
4022 $markerType = 'general';
4024 if ( $this->ot
['html'] ||
$isFunctionTag ) {
4025 $name = strtolower( $name );
4026 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
4027 if ( isset( $params['attributes'] ) ) {
4028 $attributes = $attributes +
$params['attributes'];
4031 if ( isset( $this->mTagHooks
[$name] ) ) {
4032 # Workaround for PHP bug 35229 and similar
4033 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
4034 throw new MWException( "Tag hook for $name is not callable\n" );
4036 $output = call_user_func_array( $this->mTagHooks
[$name],
4037 array( $content, $attributes, $this, $frame ) );
4038 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
4039 list( $callback, ) = $this->mFunctionTagHooks
[$name];
4040 if ( !is_callable( $callback ) ) {
4041 throw new MWException( "Tag hook for $name is not callable\n" );
4044 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
4046 $output = '<span class="error">Invalid tag extension name: ' .
4047 htmlspecialchars( $name ) . '</span>';
4050 if ( is_array( $output ) ) {
4051 # Extract flags to local scope (to override $markerType)
4053 $output = $flags[0];
4058 if ( is_null( $attrText ) ) {
4061 if ( isset( $params['attributes'] ) ) {
4062 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4063 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4064 htmlspecialchars( $attrValue ) . '"';
4067 if ( $content === null ) {
4068 $output = "<$name$attrText/>";
4070 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4071 $output = "<$name$attrText>$content$close";
4075 if ( $markerType === 'none' ) {
4077 } elseif ( $markerType === 'nowiki' ) {
4078 $this->mStripState
->addNoWiki( $marker, $output );
4079 } elseif ( $markerType === 'general' ) {
4080 $this->mStripState
->addGeneral( $marker, $output );
4082 throw new MWException( __METHOD__
. ': invalid marker type' );
4088 * Increment an include size counter
4090 * @param string $type The type of expansion
4091 * @param int $size The size of the text
4092 * @return bool False if this inclusion would take it over the maximum, true otherwise
4094 function incrementIncludeSize( $type, $size ) {
4095 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4098 $this->mIncludeSizes
[$type] +
= $size;
4104 * Increment the expensive function count
4106 * @return bool False if the limit has been exceeded
4108 function incrementExpensiveFunctionCount() {
4109 $this->mExpensiveFunctionCount++
;
4110 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4114 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4115 * Fills $this->mDoubleUnderscores, returns the modified text
4117 * @param string $text
4121 function doDoubleUnderscore( $text ) {
4122 wfProfileIn( __METHOD__
);
4124 # The position of __TOC__ needs to be recorded
4125 $mw = MagicWord
::get( 'toc' );
4126 if ( $mw->match( $text ) ) {
4127 $this->mShowToc
= true;
4128 $this->mForceTocPosition
= true;
4130 # Set a placeholder. At the end we'll fill it in with the TOC.
4131 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4133 # Only keep the first one.
4134 $text = $mw->replace( '', $text );
4137 # Now match and remove the rest of them
4138 $mwa = MagicWord
::getDoubleUnderscoreArray();
4139 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4141 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4142 $this->mOutput
->mNoGallery
= true;
4144 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4145 $this->mShowToc
= false;
4147 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
4148 $this->addTrackingCategory( 'hidden-category-category' );
4150 # (bug 8068) Allow control over whether robots index a page.
4152 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4153 # is not desirable, the last one on the page should win.
4154 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4155 $this->mOutput
->setIndexPolicy( 'noindex' );
4156 $this->addTrackingCategory( 'noindex-category' );
4158 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4159 $this->mOutput
->setIndexPolicy( 'index' );
4160 $this->addTrackingCategory( 'index-category' );
4163 # Cache all double underscores in the database
4164 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4165 $this->mOutput
->setProperty( $key, '' );
4168 wfProfileOut( __METHOD__
);
4173 * Add a tracking category, getting the title from a system message,
4174 * or print a debug message if the title is invalid.
4176 * Please add any message that you use with this function to
4177 * $wgTrackingCategories. That way they will be listed on
4178 * Special:TrackingCategories.
4180 * @param string $msg Message key
4181 * @return bool Whether the addition was successful
4183 public function addTrackingCategory( $msg ) {
4184 if ( $this->mTitle
->getNamespace() === NS_SPECIAL
) {
4185 wfDebug( __METHOD__
. ": Not adding tracking category $msg to special page!\n" );
4188 // Important to parse with correct title (bug 31469)
4189 $cat = wfMessage( $msg )
4190 ->title( $this->getTitle() )
4191 ->inContentLanguage()
4194 # Allow tracking categories to be disabled by setting them to "-"
4195 if ( $cat === '-' ) {
4199 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
4200 if ( $containerCategory ) {
4201 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
4204 wfDebug( __METHOD__
. ": [[MediaWiki:$msg]] is not a valid title!\n" );
4210 * This function accomplishes several tasks:
4211 * 1) Auto-number headings if that option is enabled
4212 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4213 * 3) Add a Table of contents on the top for users who have enabled the option
4214 * 4) Auto-anchor headings
4216 * It loops through all headlines, collects the necessary data, then splits up the
4217 * string and re-inserts the newly formatted headlines.
4219 * @param string $text
4220 * @param string $origText Original, untouched wikitext
4221 * @param bool $isMain
4222 * @return mixed|string
4225 function formatHeadings( $text, $origText, $isMain = true ) {
4226 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4228 # Inhibit editsection links if requested in the page
4229 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4230 $maybeShowEditLink = $showEditLink = false;
4232 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4233 $showEditLink = $this->mOptions
->getEditSection();
4235 if ( $showEditLink ) {
4236 $this->mOutput
->setEditSectionTokens( true );
4239 # Get all headlines for numbering them and adding funky stuff like [edit]
4240 # links - this is for later, but we need the number of headlines right now
4242 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?' . '>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i', $text, $matches );
4244 # if there are fewer than 4 headlines in the article, do not show TOC
4245 # unless it's been explicitly enabled.
4246 $enoughToc = $this->mShowToc
&&
4247 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4249 # Allow user to stipulate that a page should have a "new section"
4250 # link added via __NEWSECTIONLINK__
4251 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4252 $this->mOutput
->setNewSection( true );
4255 # Allow user to remove the "new section"
4256 # link via __NONEWSECTIONLINK__
4257 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4258 $this->mOutput
->hideNewSection( true );
4261 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4262 # override above conditions and always show TOC above first header
4263 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4264 $this->mShowToc
= true;
4272 # Ugh .. the TOC should have neat indentation levels which can be
4273 # passed to the skin functions. These are determined here
4277 $sublevelCount = array();
4278 $levelCount = array();
4283 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4284 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4285 $oldType = $this->mOutputType
;
4286 $this->setOutputType( self
::OT_WIKI
);
4287 $frame = $this->getPreprocessor()->newFrame();
4288 $root = $this->preprocessToDom( $origText );
4289 $node = $root->getFirstChild();
4294 foreach ( $matches[3] as $headline ) {
4295 $isTemplate = false;
4297 $sectionIndex = false;
4299 $markerMatches = array();
4300 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4301 $serial = $markerMatches[1];
4302 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4303 $isTemplate = ( $titleText != $baseTitleText );
4304 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4308 $prevlevel = $level;
4310 $level = $matches[1][$headlineCount];
4312 if ( $level > $prevlevel ) {
4313 # Increase TOC level
4315 $sublevelCount[$toclevel] = 0;
4316 if ( $toclevel < $wgMaxTocLevel ) {
4317 $prevtoclevel = $toclevel;
4318 $toc .= Linker
::tocIndent();
4321 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4322 # Decrease TOC level, find level to jump to
4324 for ( $i = $toclevel; $i > 0; $i-- ) {
4325 if ( $levelCount[$i] == $level ) {
4326 # Found last matching level
4329 } elseif ( $levelCount[$i] < $level ) {
4330 # Found first matching level below current level
4338 if ( $toclevel < $wgMaxTocLevel ) {
4339 if ( $prevtoclevel < $wgMaxTocLevel ) {
4340 # Unindent only if the previous toc level was shown :p
4341 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4342 $prevtoclevel = $toclevel;
4344 $toc .= Linker
::tocLineEnd();
4348 # No change in level, end TOC line
4349 if ( $toclevel < $wgMaxTocLevel ) {
4350 $toc .= Linker
::tocLineEnd();
4354 $levelCount[$toclevel] = $level;
4356 # count number of headlines for each level
4357 $sublevelCount[$toclevel]++
;
4359 for ( $i = 1; $i <= $toclevel; $i++
) {
4360 if ( !empty( $sublevelCount[$i] ) ) {
4364 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4369 # The safe header is a version of the header text safe to use for links
4371 # Remove link placeholders by the link text.
4372 # <!--LINK number-->
4374 # link text with suffix
4375 # Do this before unstrip since link text can contain strip markers
4376 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4378 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4379 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4381 # Strip out HTML (first regex removes any tag not allowed)
4383 # * <sup> and <sub> (bug 8393)
4386 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4388 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4389 # to allow setting directionality in toc items.
4390 $tocline = preg_replace(
4391 array( '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?' . '>#', '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?' . '>#' ),
4392 array( '', '<$1>' ),
4395 $tocline = trim( $tocline );
4397 # For the anchor, strip out HTML-y stuff period
4398 $safeHeadline = preg_replace( '/<.*?' . '>/', '', $safeHeadline );
4399 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4401 # Save headline for section edit hint before it's escaped
4402 $headlineHint = $safeHeadline;
4404 if ( $wgExperimentalHtmlIds ) {
4405 # For reverse compatibility, provide an id that's
4406 # HTML4-compatible, like we used to.
4408 # It may be worth noting, academically, that it's possible for
4409 # the legacy anchor to conflict with a non-legacy headline
4410 # anchor on the page. In this case likely the "correct" thing
4411 # would be to either drop the legacy anchors or make sure
4412 # they're numbered first. However, this would require people
4413 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4414 # manually, so let's not bother worrying about it.
4415 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4416 array( 'noninitial', 'legacy' ) );
4417 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4419 if ( $legacyHeadline == $safeHeadline ) {
4420 # No reason to have both (in fact, we can't)
4421 $legacyHeadline = false;
4424 $legacyHeadline = false;
4425 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4429 # HTML names must be case-insensitively unique (bug 10721).
4430 # This does not apply to Unicode characters per
4431 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4432 # @todo FIXME: We may be changing them depending on the current locale.
4433 $arrayKey = strtolower( $safeHeadline );
4434 if ( $legacyHeadline === false ) {
4435 $legacyArrayKey = false;
4437 $legacyArrayKey = strtolower( $legacyHeadline );
4440 # count how many in assoc. array so we can track dupes in anchors
4441 if ( isset( $refers[$arrayKey] ) ) {
4442 $refers[$arrayKey]++
;
4444 $refers[$arrayKey] = 1;
4446 if ( isset( $refers[$legacyArrayKey] ) ) {
4447 $refers[$legacyArrayKey]++
;
4449 $refers[$legacyArrayKey] = 1;
4452 # Don't number the heading if it is the only one (looks silly)
4453 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4454 # the two are different if the line contains a link
4455 $headline = Html
::element( 'span', array( 'class' => 'mw-headline-number' ), $numbering ) . ' ' . $headline;
4458 # Create the anchor for linking from the TOC to the section
4459 $anchor = $safeHeadline;
4460 $legacyAnchor = $legacyHeadline;
4461 if ( $refers[$arrayKey] > 1 ) {
4462 $anchor .= '_' . $refers[$arrayKey];
4464 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4465 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4467 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4468 $toc .= Linker
::tocLine( $anchor, $tocline,
4469 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4472 # Add the section to the section tree
4473 # Find the DOM node for this header
4474 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4475 while ( $node && !$noOffset ) {
4476 if ( $node->getName() === 'h' ) {
4477 $bits = $node->splitHeading();
4478 if ( $bits['i'] == $sectionIndex ) {
4482 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4483 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4484 $node = $node->getNextSibling();
4487 'toclevel' => $toclevel,
4490 'number' => $numbering,
4491 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4492 'fromtitle' => $titleText,
4493 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4494 'anchor' => $anchor,
4497 # give headline the correct <h#> tag
4498 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4499 // Output edit section links as markers with styles that can be customized by skins
4500 if ( $isTemplate ) {
4501 # Put a T flag in the section identifier, to indicate to extractSections()
4502 # that sections inside <includeonly> should be counted.
4503 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4505 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
4507 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4508 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4509 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4510 // so we don't have to worry about a user trying to input one of these markers directly.
4511 // We use a page and section attribute to stop the language converter from converting these important bits
4512 // of data, but put the headline hint inside a content block because the language converter is supposed to
4513 // be able to convert that piece of data.
4514 $editlink = '<mw:editsection page="' . htmlspecialchars( $editlinkArgs[0] );
4515 $editlink .= '" section="' . htmlspecialchars( $editlinkArgs[1] ) . '"';
4516 if ( isset( $editlinkArgs[2] ) ) {
4517 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4524 $head[$headlineCount] = Linker
::makeHeadline( $level,
4525 $matches['attrib'][$headlineCount], $anchor, $headline,
4526 $editlink, $legacyAnchor );
4531 $this->setOutputType( $oldType );
4533 # Never ever show TOC if no headers
4534 if ( $numVisible < 1 ) {
4539 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4540 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4542 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4543 $this->mOutput
->setTOCHTML( $toc );
4544 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4545 $this->mOutput
->addModules( 'mediawiki.toc' );
4549 $this->mOutput
->setSections( $tocraw );
4552 # split up and insert constructed headlines
4553 $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text );
4556 // build an array of document sections
4557 $sections = array();
4558 foreach ( $blocks as $block ) {
4559 // $head is zero-based, sections aren't.
4560 if ( empty( $head[$i - 1] ) ) {
4561 $sections[$i] = $block;
4563 $sections[$i] = $head[$i - 1] . $block;
4567 * Send a hook, one per section.
4568 * The idea here is to be able to make section-level DIVs, but to do so in a
4569 * lower-impact, more correct way than r50769
4572 * $section : the section number
4573 * &$sectionContent : ref to the content of the section
4574 * $showEditLinks : boolean describing whether this section has an edit link
4576 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4581 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4582 // append the TOC at the beginning
4583 // Top anchor now in skin
4584 $sections[0] = $sections[0] . $toc . "\n";
4587 $full .= join( '', $sections );
4589 if ( $this->mForceTocPosition
) {
4590 return str_replace( '<!--MWTOC-->', $toc, $full );
4597 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4598 * conversion, substitting signatures, {{subst:}} templates, etc.
4600 * @param string $text The text to transform
4601 * @param Title $title The Title object for the current article
4602 * @param User $user The User object describing the current user
4603 * @param ParserOptions $options Parsing options
4604 * @param bool $clearState Whether to clear the parser state first
4605 * @return string The altered wiki markup
4607 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4608 if ( $clearState ) {
4609 $magicScopeVariable = $this->lock();
4611 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4612 $this->setUser( $user );
4617 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4618 if ( $options->getPreSaveTransform() ) {
4619 $text = $this->pstPass2( $text, $user );
4621 $text = $this->mStripState
->unstripBoth( $text );
4623 $this->setUser( null ); #Reset
4629 * Pre-save transform helper function
4631 * @param string $text
4636 private function pstPass2( $text, $user ) {
4639 # Note: This is the timestamp saved as hardcoded wikitext to
4640 # the database, we use $wgContLang here in order to give
4641 # everyone the same signature and use the default one rather
4642 # than the one selected in each user's preferences.
4643 # (see also bug 12815)
4644 $ts = $this->mOptions
->getTimestamp();
4645 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4646 $ts = $timestamp->format( 'YmdHis' );
4647 $tzMsg = $timestamp->format( 'T' ); # might vary on DST changeover!
4649 # Allow translation of timezones through wiki. format() can return
4650 # whatever crap the system uses, localised or not, so we cannot
4651 # ship premade translations.
4652 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4653 $msg = wfMessage( $key )->inContentLanguage();
4654 if ( $msg->exists() ) {
4655 $tzMsg = $msg->text();
4658 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4660 # Variable replacement
4661 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4662 $text = $this->replaceVariables( $text );
4664 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4665 # which may corrupt this parser instance via its wfMessage()->text() call-
4668 $sigText = $this->getUserSig( $user );
4669 $text = strtr( $text, array(
4671 '~~~~' => "$sigText $d",
4675 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4676 $tc = '[' . Title
::legalChars() . ']';
4677 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4679 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4680 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]] (double-width brackets, added in r40257)
4681 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/"; # [[ns:page (context), context|]] (using either single or double-width comma)
4682 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]] (reverse pipe trick: add context from page title)
4684 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4685 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4686 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4687 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4689 $t = $this->mTitle
->getText();
4691 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4692 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4693 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4694 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4696 # if there's no context, don't bother duplicating the title
4697 $text = preg_replace( $p2, '[[\\1]]', $text );
4700 # Trim trailing whitespace
4701 $text = rtrim( $text );
4707 * Fetch the user's signature text, if any, and normalize to
4708 * validated, ready-to-insert wikitext.
4709 * If you have pre-fetched the nickname or the fancySig option, you can
4710 * specify them here to save a database query.
4711 * Do not reuse this parser instance after calling getUserSig(),
4712 * as it may have changed if it's the $wgParser.
4715 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4716 * @param bool|null $fancySig whether the nicknname is the complete signature
4717 * or null to use default value
4720 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4721 global $wgMaxSigChars;
4723 $username = $user->getName();
4725 # If not given, retrieve from the user object.
4726 if ( $nickname === false ) {
4727 $nickname = $user->getOption( 'nickname' );
4730 if ( is_null( $fancySig ) ) {
4731 $fancySig = $user->getBoolOption( 'fancysig' );
4734 $nickname = $nickname == null ?
$username : $nickname;
4736 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4737 $nickname = $username;
4738 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4739 } elseif ( $fancySig !== false ) {
4740 # Sig. might contain markup; validate this
4741 if ( $this->validateSig( $nickname ) !== false ) {
4742 # Validated; clean up (if needed) and return it
4743 return $this->cleanSig( $nickname, true );
4745 # Failed to validate; fall back to the default
4746 $nickname = $username;
4747 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4751 # Make sure nickname doesnt get a sig in a sig
4752 $nickname = self
::cleanSigInSig( $nickname );
4754 # If we're still here, make it a link to the user page
4755 $userText = wfEscapeWikiText( $username );
4756 $nickText = wfEscapeWikiText( $nickname );
4757 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4759 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4763 * Check that the user's signature contains no bad XML
4765 * @param string $text
4766 * @return string|bool An expanded string, or false if invalid.
4768 function validateSig( $text ) {
4769 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4773 * Clean up signature text
4775 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4776 * 2) Substitute all transclusions
4778 * @param string $text
4779 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4780 * @return string Signature text
4782 public function cleanSig( $text, $parsing = false ) {
4785 $magicScopeVariable = $this->lock();
4786 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4789 # Option to disable this feature
4790 if ( !$this->mOptions
->getCleanSignatures() ) {
4794 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4795 # => Move this logic to braceSubstitution()
4796 $substWord = MagicWord
::get( 'subst' );
4797 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4798 $substText = '{{' . $substWord->getSynonym( 0 );
4800 $text = preg_replace( $substRegex, $substText, $text );
4801 $text = self
::cleanSigInSig( $text );
4802 $dom = $this->preprocessToDom( $text );
4803 $frame = $this->getPreprocessor()->newFrame();
4804 $text = $frame->expand( $dom );
4807 $text = $this->mStripState
->unstripBoth( $text );
4814 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4816 * @param string $text
4817 * @return string Signature text with /~{3,5}/ removed
4819 public static function cleanSigInSig( $text ) {
4820 $text = preg_replace( '/~{3,5}/', '', $text );
4825 * Set up some variables which are usually set up in parse()
4826 * so that an external function can call some class members with confidence
4828 * @param Title|null $title
4829 * @param ParserOptions $options
4830 * @param int $outputType
4831 * @param bool $clearState
4833 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4834 $this->startParse( $title, $options, $outputType, $clearState );
4838 * @param Title|null $title
4839 * @param ParserOptions $options
4840 * @param int $outputType
4841 * @param bool $clearState
4843 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4844 $this->setTitle( $title );
4845 $this->mOptions
= $options;
4846 $this->setOutputType( $outputType );
4847 if ( $clearState ) {
4848 $this->clearState();
4853 * Wrapper for preprocess()
4855 * @param string $text The text to preprocess
4856 * @param ParserOptions $options Options
4857 * @param Title|null $title Title object or null to use $wgTitle
4860 public function transformMsg( $text, $options, $title = null ) {
4861 static $executing = false;
4863 # Guard against infinite recursion
4869 wfProfileIn( __METHOD__
);
4875 $text = $this->preprocess( $text, $title, $options );
4878 wfProfileOut( __METHOD__
);
4883 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4884 * The callback should have the following form:
4885 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4887 * Transform and return $text. Use $parser for any required context, e.g. use
4888 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4890 * Hooks may return extended information by returning an array, of which the
4891 * first numbered element (index 0) must be the return string, and all other
4892 * entries are extracted into local variables within an internal function
4893 * in the Parser class.
4895 * This interface (introduced r61913) appears to be undocumented, but
4896 * 'markerName' is used by some core tag hooks to override which strip
4897 * array their results are placed in. **Use great caution if attempting
4898 * this interface, as it is not documented and injudicious use could smash
4899 * private variables.**
4901 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4902 * @param mixed $callback The callback function (and object) to use for the tag
4903 * @throws MWException
4904 * @return mixed|null The old value of the mTagHooks array associated with the hook
4906 public function setHook( $tag, $callback ) {
4907 $tag = strtolower( $tag );
4908 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4909 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4911 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4912 $this->mTagHooks
[$tag] = $callback;
4913 if ( !in_array( $tag, $this->mStripList
) ) {
4914 $this->mStripList
[] = $tag;
4921 * As setHook(), but letting the contents be parsed.
4923 * Transparent tag hooks are like regular XML-style tag hooks, except they
4924 * operate late in the transformation sequence, on HTML instead of wikitext.
4926 * This is probably obsoleted by things dealing with parser frames?
4927 * The only extension currently using it is geoserver.
4930 * @todo better document or deprecate this
4932 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
4933 * @param mixed $callback The callback function (and object) to use for the tag
4934 * @throws MWException
4935 * @return mixed|null The old value of the mTagHooks array associated with the hook
4937 function setTransparentTagHook( $tag, $callback ) {
4938 $tag = strtolower( $tag );
4939 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4940 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4942 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4943 $this->mTransparentTagHooks
[$tag] = $callback;
4949 * Remove all tag hooks
4951 function clearTagHooks() {
4952 $this->mTagHooks
= array();
4953 $this->mFunctionTagHooks
= array();
4954 $this->mStripList
= $this->mDefaultStripList
;
4958 * Create a function, e.g. {{sum:1|2|3}}
4959 * The callback function should have the form:
4960 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4962 * Or with SFH_OBJECT_ARGS:
4963 * function myParserFunction( $parser, $frame, $args ) { ... }
4965 * The callback may either return the text result of the function, or an array with the text
4966 * in element 0, and a number of flags in the other elements. The names of the flags are
4967 * specified in the keys. Valid flags are:
4968 * found The text returned is valid, stop processing the template. This
4970 * nowiki Wiki markup in the return value should be escaped
4971 * isHTML The returned text is HTML, armour it against wikitext transformation
4973 * @param string $id The magic word ID
4974 * @param mixed $callback The callback function (and object) to use
4975 * @param int $flags A combination of the following flags:
4976 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4978 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4979 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4980 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4981 * the arguments, and to control the way they are expanded.
4983 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4984 * arguments, for instance:
4985 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4987 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4988 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4989 * working if/when this is changed.
4991 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4994 * Please read the documentation in includes/parser/Preprocessor.php for more information
4995 * about the methods available in PPFrame and PPNode.
4997 * @throws MWException
4998 * @return string|callable The old callback function for this name, if any
5000 public function setFunctionHook( $id, $callback, $flags = 0 ) {
5003 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
5004 $this->mFunctionHooks
[$id] = array( $callback, $flags );
5006 # Add to function cache
5007 $mw = MagicWord
::get( $id );
5009 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
5012 $synonyms = $mw->getSynonyms();
5013 $sensitive = intval( $mw->isCaseSensitive() );
5015 foreach ( $synonyms as $syn ) {
5017 if ( !$sensitive ) {
5018 $syn = $wgContLang->lc( $syn );
5021 if ( !( $flags & SFH_NO_HASH
) ) {
5024 # Remove trailing colon
5025 if ( substr( $syn, -1, 1 ) === ':' ) {
5026 $syn = substr( $syn, 0, -1 );
5028 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
5034 * Get all registered function hook identifiers
5038 function getFunctionHooks() {
5039 return array_keys( $this->mFunctionHooks
);
5043 * Create a tag function, e.g. "<test>some stuff</test>".
5044 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5045 * Unlike parser functions, their content is not preprocessed.
5046 * @param string $tag
5047 * @param callable $callback
5049 * @throws MWException
5052 function setFunctionTagHook( $tag, $callback, $flags ) {
5053 $tag = strtolower( $tag );
5054 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5055 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5057 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
5058 $this->mFunctionTagHooks
[$tag] : null;
5059 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
5061 if ( !in_array( $tag, $this->mStripList
) ) {
5062 $this->mStripList
[] = $tag;
5069 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
5070 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5071 * Placeholders created in Skin::makeLinkObj()
5073 * @param string $text
5074 * @param int $options
5076 * @return array Array of link CSS classes, indexed by PDBK.
5078 function replaceLinkHolders( &$text, $options = 0 ) {
5079 return $this->mLinkHolders
->replace( $text );
5083 * Replace "<!--LINK-->" link placeholders with plain text of links
5084 * (not HTML-formatted).
5086 * @param string $text
5089 function replaceLinkHoldersText( $text ) {
5090 return $this->mLinkHolders
->replaceText( $text );
5094 * Renders an image gallery from a text with one line per image.
5095 * text labels may be given by using |-style alternative text. E.g.
5096 * Image:one.jpg|The number "1"
5097 * Image:tree.jpg|A tree
5098 * given as text will return the HTML of a gallery with two images,
5099 * labeled 'The number "1"' and
5102 * @param string $text
5103 * @param array $params
5104 * @return string HTML
5106 function renderImageGallery( $text, $params ) {
5107 wfProfileIn( __METHOD__
);
5110 if ( isset( $params['mode'] ) ) {
5111 $mode = $params['mode'];
5115 $ig = ImageGalleryBase
::factory( $mode );
5116 } catch ( MWException
$e ) {
5117 // If invalid type set, fallback to default.
5118 $ig = ImageGalleryBase
::factory( false );
5121 $ig->setContextTitle( $this->mTitle
);
5122 $ig->setShowBytes( false );
5123 $ig->setShowFilename( false );
5124 $ig->setParser( $this );
5125 $ig->setHideBadImages();
5126 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
5128 if ( isset( $params['showfilename'] ) ) {
5129 $ig->setShowFilename( true );
5131 $ig->setShowFilename( false );
5133 if ( isset( $params['caption'] ) ) {
5134 $caption = $params['caption'];
5135 $caption = htmlspecialchars( $caption );
5136 $caption = $this->replaceInternalLinks( $caption );
5137 $ig->setCaptionHtml( $caption );
5139 if ( isset( $params['perrow'] ) ) {
5140 $ig->setPerRow( $params['perrow'] );
5142 if ( isset( $params['widths'] ) ) {
5143 $ig->setWidths( $params['widths'] );
5145 if ( isset( $params['heights'] ) ) {
5146 $ig->setHeights( $params['heights'] );
5148 $ig->setAdditionalOptions( $params );
5150 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5152 $lines = StringUtils
::explode( "\n", $text );
5153 foreach ( $lines as $line ) {
5154 # match lines like these:
5155 # Image:someimage.jpg|This is some image
5157 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5159 if ( count( $matches ) == 0 ) {
5163 if ( strpos( $matches[0], '%' ) !== false ) {
5164 $matches[1] = rawurldecode( $matches[1] );
5166 $title = Title
::newFromText( $matches[1], NS_FILE
);
5167 if ( is_null( $title ) ) {
5168 # Bogus title. Ignore these so we don't bomb out later.
5172 # We need to get what handler the file uses, to figure out parameters.
5173 # Note, a hook can overide the file name, and chose an entirely different
5174 # file (which potentially could be of a different type and have different handler).
5177 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5178 array( $this, $title, &$options, &$descQuery ) );
5179 # Don't register it now, as ImageGallery does that later.
5180 $file = $this->fetchFileNoRegister( $title, $options );
5181 $handler = $file ?
$file->getHandler() : false;
5183 wfProfileIn( __METHOD__
. '-getMagicWord' );
5185 'img_alt' => 'gallery-internal-alt',
5186 'img_link' => 'gallery-internal-link',
5189 $paramMap = $paramMap +
$handler->getParamMap();
5190 // We don't want people to specify per-image widths.
5191 // Additionally the width parameter would need special casing anyhow.
5192 unset( $paramMap['img_width'] );
5195 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5196 wfProfileOut( __METHOD__
. '-getMagicWord' );
5201 $handlerOptions = array();
5202 if ( isset( $matches[3] ) ) {
5203 // look for an |alt= definition while trying not to break existing
5204 // captions with multiple pipes (|) in it, until a more sensible grammar
5205 // is defined for images in galleries
5207 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5208 // splitting on '|' is a bit odd, and different from makeImage.
5209 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5210 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
5212 foreach ( $parameterMatches as $parameterMatch ) {
5213 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5215 $paramName = $paramMap[$magicName];
5217 switch ( $paramName ) {
5218 case 'gallery-internal-alt':
5219 $alt = $this->stripAltText( $match, false );
5221 case 'gallery-internal-link':
5222 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5223 $chars = self
::EXT_LINK_URL_CLASS
;
5224 $prots = $this->mUrlProtocols
;
5225 //check to see if link matches an absolute url, if not then it must be a wiki link.
5226 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5229 $localLinkTitle = Title
::newFromText( $linkValue );
5230 if ( $localLinkTitle !== null ) {
5231 $link = $localLinkTitle->getLocalURL();
5236 // Must be a handler specific parameter.
5237 if ( $handler->validateParam( $paramName, $match ) ) {
5238 $handlerOptions[$paramName] = $match;
5240 // Guess not. Append it to the caption.
5241 wfDebug( "$parameterMatch failed parameter validation\n" );
5242 $label .= '|' . $parameterMatch;
5247 // concatenate all other pipes
5248 $label .= '|' . $parameterMatch;
5251 // remove the first pipe
5252 $label = substr( $label, 1 );
5255 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5257 $html = $ig->toHTML();
5258 wfProfileOut( __METHOD__
);
5263 * @param string $handler
5266 function getImageParams( $handler ) {
5268 $handlerClass = get_class( $handler );
5272 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5273 # Initialise static lists
5274 static $internalParamNames = array(
5275 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5276 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5277 'bottom', 'text-bottom' ),
5278 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5279 'upright', 'border', 'link', 'alt', 'class' ),
5281 static $internalParamMap;
5282 if ( !$internalParamMap ) {
5283 $internalParamMap = array();
5284 foreach ( $internalParamNames as $type => $names ) {
5285 foreach ( $names as $name ) {
5286 $magicName = str_replace( '-', '_', "img_$name" );
5287 $internalParamMap[$magicName] = array( $type, $name );
5292 # Add handler params
5293 $paramMap = $internalParamMap;
5295 $handlerParamMap = $handler->getParamMap();
5296 foreach ( $handlerParamMap as $magic => $paramName ) {
5297 $paramMap[$magic] = array( 'handler', $paramName );
5300 $this->mImageParams
[$handlerClass] = $paramMap;
5301 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5303 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5307 * Parse image options text and use it to make an image
5309 * @param Title $title
5310 * @param string $options
5311 * @param LinkHolderArray|bool $holders
5312 * @return string HTML
5314 function makeImage( $title, $options, $holders = false ) {
5315 # Check if the options text is of the form "options|alt text"
5317 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5318 # * left no resizing, just left align. label is used for alt= only
5319 # * right same, but right aligned
5320 # * none same, but not aligned
5321 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5322 # * center center the image
5323 # * frame Keep original image size, no magnify-button.
5324 # * framed Same as "frame"
5325 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5326 # * upright reduce width for upright images, rounded to full __0 px
5327 # * border draw a 1px border around the image
5328 # * alt Text for HTML alt attribute (defaults to empty)
5329 # * class Set a class for img node
5330 # * link Set the target of the image link. Can be external, interwiki, or local
5331 # vertical-align values (no % or length right now):
5341 $parts = StringUtils
::explode( "|", $options );
5343 # Give extensions a chance to select the file revision for us
5346 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5347 array( $this, $title, &$options, &$descQuery ) );
5348 # Fetch and register the file (file title may be different via hooks)
5349 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5352 $handler = $file ?
$file->getHandler() : false;
5354 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5357 $this->addTrackingCategory( 'broken-file-category' );
5360 # Process the input parameters
5362 $params = array( 'frame' => array(), 'handler' => array(),
5363 'horizAlign' => array(), 'vertAlign' => array() );
5364 $seenformat = false;
5365 foreach ( $parts as $part ) {
5366 $part = trim( $part );
5367 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5369 if ( isset( $paramMap[$magicName] ) ) {
5370 list( $type, $paramName ) = $paramMap[$magicName];
5372 # Special case; width and height come in one variable together
5373 if ( $type === 'handler' && $paramName === 'width' ) {
5374 $parsedWidthParam = $this->parseWidthParam( $value );
5375 if ( isset( $parsedWidthParam['width'] ) ) {
5376 $width = $parsedWidthParam['width'];
5377 if ( $handler->validateParam( 'width', $width ) ) {
5378 $params[$type]['width'] = $width;
5382 if ( isset( $parsedWidthParam['height'] ) ) {
5383 $height = $parsedWidthParam['height'];
5384 if ( $handler->validateParam( 'height', $height ) ) {
5385 $params[$type]['height'] = $height;
5389 # else no validation -- bug 13436
5391 if ( $type === 'handler' ) {
5392 # Validate handler parameter
5393 $validated = $handler->validateParam( $paramName, $value );
5395 # Validate internal parameters
5396 switch ( $paramName ) {
5400 # @todo FIXME: Possibly check validity here for
5401 # manualthumb? downstream behavior seems odd with
5402 # missing manual thumbs.
5404 $value = $this->stripAltText( $value, $holders );
5407 $chars = self
::EXT_LINK_URL_CLASS
;
5408 $prots = $this->mUrlProtocols
;
5409 if ( $value === '' ) {
5410 $paramName = 'no-link';
5413 } elseif ( preg_match( "/^(?i)$prots/", $value ) ) {
5414 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5415 $paramName = 'link-url';
5416 $this->mOutput
->addExternalLink( $value );
5417 if ( $this->mOptions
->getExternalLinkTarget() ) {
5418 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5423 $linkTitle = Title
::newFromText( $value );
5425 $paramName = 'link-title';
5426 $value = $linkTitle;
5427 $this->mOutput
->addLink( $linkTitle );
5435 // use first appearing option, discard others.
5436 $validated = ! $seenformat;
5440 # Most other things appear to be empty or numeric...
5441 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5446 $params[$type][$paramName] = $value;
5450 if ( !$validated ) {
5455 # Process alignment parameters
5456 if ( $params['horizAlign'] ) {
5457 $params['frame']['align'] = key( $params['horizAlign'] );
5459 if ( $params['vertAlign'] ) {
5460 $params['frame']['valign'] = key( $params['vertAlign'] );
5463 $params['frame']['caption'] = $caption;
5465 # Will the image be presented in a frame, with the caption below?
5466 $imageIsFramed = isset( $params['frame']['frame'] )
5467 ||
isset( $params['frame']['framed'] )
5468 ||
isset( $params['frame']['thumbnail'] )
5469 ||
isset( $params['frame']['manualthumb'] );
5471 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5472 # came to also set the caption, ordinary text after the image -- which
5473 # makes no sense, because that just repeats the text multiple times in
5474 # screen readers. It *also* came to set the title attribute.
5476 # Now that we have an alt attribute, we should not set the alt text to
5477 # equal the caption: that's worse than useless, it just repeats the
5478 # text. This is the framed/thumbnail case. If there's no caption, we
5479 # use the unnamed parameter for alt text as well, just for the time be-
5480 # ing, if the unnamed param is set and the alt param is not.
5482 # For the future, we need to figure out if we want to tweak this more,
5483 # e.g., introducing a title= parameter for the title; ignoring the un-
5484 # named parameter entirely for images without a caption; adding an ex-
5485 # plicit caption= parameter and preserving the old magic unnamed para-
5487 if ( $imageIsFramed ) { # Framed image
5488 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5489 # No caption or alt text, add the filename as the alt text so
5490 # that screen readers at least get some description of the image
5491 $params['frame']['alt'] = $title->getText();
5493 # Do not set $params['frame']['title'] because tooltips don't make sense
5495 } else { # Inline image
5496 if ( !isset( $params['frame']['alt'] ) ) {
5497 # No alt text, use the "caption" for the alt text
5498 if ( $caption !== '' ) {
5499 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5501 # No caption, fall back to using the filename for the
5503 $params['frame']['alt'] = $title->getText();
5506 # Use the "caption" for the tooltip text
5507 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5510 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5512 # Linker does the rest
5513 $time = isset( $options['time'] ) ?
$options['time'] : false;
5514 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5515 $time, $descQuery, $this->mOptions
->getThumbSize() );
5517 # Give the handler a chance to modify the parser object
5519 $handler->parserTransformHook( $this, $file );
5526 * @param string $caption
5527 * @param LinkHolderArray $holders
5528 * @return mixed|string
5530 protected function stripAltText( $caption, $holders ) {
5531 # Strip bad stuff out of the title (tooltip). We can't just use
5532 # replaceLinkHoldersText() here, because if this function is called
5533 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5535 $tooltip = $holders->replaceText( $caption );
5537 $tooltip = $this->replaceLinkHoldersText( $caption );
5540 # make sure there are no placeholders in thumbnail attributes
5541 # that are later expanded to html- so expand them now and
5543 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5544 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5550 * Set a flag in the output object indicating that the content is dynamic and
5551 * shouldn't be cached.
5553 function disableCache() {
5554 wfDebug( "Parser output marked as uncacheable.\n" );
5555 if ( !$this->mOutput
) {
5556 throw new MWException( __METHOD__
.
5557 " can only be called when actually parsing something" );
5559 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5560 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5564 * Callback from the Sanitizer for expanding items found in HTML attribute
5565 * values, so they can be safely tested and escaped.
5567 * @param string $text
5568 * @param PPFrame $frame
5571 function attributeStripCallback( &$text, $frame = false ) {
5572 $text = $this->replaceVariables( $text, $frame );
5573 $text = $this->mStripState
->unstripBoth( $text );
5582 function getTags() {
5583 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
), array_keys( $this->mFunctionTagHooks
) );
5587 * Replace transparent tags in $text with the values given by the callbacks.
5589 * Transparent tag hooks are like regular XML-style tag hooks, except they
5590 * operate late in the transformation sequence, on HTML instead of wikitext.
5592 * @param string $text
5596 function replaceTransparentTags( $text ) {
5598 $elements = array_keys( $this->mTransparentTagHooks
);
5599 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5600 $replacements = array();
5602 foreach ( $matches as $marker => $data ) {
5603 list( $element, $content, $params, $tag ) = $data;
5604 $tagName = strtolower( $element );
5605 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5606 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
5610 $replacements[$marker] = $output;
5612 return strtr( $text, $replacements );
5616 * Break wikitext input into sections, and either pull or replace
5617 * some particular section's text.
5619 * External callers should use the getSection and replaceSection methods.
5621 * @param string $text Page wikitext
5622 * @param string $section A section identifier string of the form:
5623 * "<flag1> - <flag2> - ... - <section number>"
5625 * Currently the only recognised flag is "T", which means the target section number
5626 * was derived during a template inclusion parse, in other words this is a template
5627 * section edit link. If no flags are given, it was an ordinary section edit link.
5628 * This flag is required to avoid a section numbering mismatch when a section is
5629 * enclosed by "<includeonly>" (bug 6563).
5631 * The section number 0 pulls the text before the first heading; other numbers will
5632 * pull the given section along with its lower-level subsections. If the section is
5633 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5635 * Section 0 is always considered to exist, even if it only contains the empty
5636 * string. If $text is the empty string and section 0 is replaced, $newText is
5639 * @param string $mode One of "get" or "replace"
5640 * @param string $newText Replacement text for section data.
5641 * @return string For "get", the extracted section text.
5642 * for "replace", the whole page with the section replaced.
5644 private function extractSections( $text, $section, $mode, $newText = '' ) {
5645 global $wgTitle; # not generally used but removes an ugly failure mode
5647 $magicScopeVariable = $this->lock();
5648 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5650 $frame = $this->getPreprocessor()->newFrame();
5652 # Process section extraction flags
5654 $sectionParts = explode( '-', $section );
5655 $sectionIndex = array_pop( $sectionParts );
5656 foreach ( $sectionParts as $part ) {
5657 if ( $part === 'T' ) {
5658 $flags |
= self
::PTD_FOR_INCLUSION
;
5662 # Check for empty input
5663 if ( strval( $text ) === '' ) {
5664 # Only sections 0 and T-0 exist in an empty document
5665 if ( $sectionIndex == 0 ) {
5666 if ( $mode === 'get' ) {
5672 if ( $mode === 'get' ) {
5680 # Preprocess the text
5681 $root = $this->preprocessToDom( $text, $flags );
5683 # <h> nodes indicate section breaks
5684 # They can only occur at the top level, so we can find them by iterating the root's children
5685 $node = $root->getFirstChild();
5687 # Find the target section
5688 if ( $sectionIndex == 0 ) {
5689 # Section zero doesn't nest, level=big
5690 $targetLevel = 1000;
5693 if ( $node->getName() === 'h' ) {
5694 $bits = $node->splitHeading();
5695 if ( $bits['i'] == $sectionIndex ) {
5696 $targetLevel = $bits['level'];
5700 if ( $mode === 'replace' ) {
5701 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5703 $node = $node->getNextSibling();
5709 if ( $mode === 'get' ) {
5716 # Find the end of the section, including nested sections
5718 if ( $node->getName() === 'h' ) {
5719 $bits = $node->splitHeading();
5720 $curLevel = $bits['level'];
5721 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5725 if ( $mode === 'get' ) {
5726 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5728 $node = $node->getNextSibling();
5731 # Write out the remainder (in replace mode only)
5732 if ( $mode === 'replace' ) {
5733 # Output the replacement text
5734 # Add two newlines on -- trailing whitespace in $newText is conventionally
5735 # stripped by the editor, so we need both newlines to restore the paragraph gap
5736 # Only add trailing whitespace if there is newText
5737 if ( $newText != "" ) {
5738 $outText .= $newText . "\n\n";
5742 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5743 $node = $node->getNextSibling();
5747 if ( is_string( $outText ) ) {
5748 # Re-insert stripped tags
5749 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5756 * This function returns the text of a section, specified by a number ($section).
5757 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5758 * the first section before any such heading (section 0).
5760 * If a section contains subsections, these are also returned.
5762 * @param string $text Text to look in
5763 * @param string $section Section identifier
5764 * @param string $deftext Default to return if section is not found
5765 * @return string Text of the requested section
5767 public function getSection( $text, $section, $deftext = '' ) {
5768 return $this->extractSections( $text, $section, "get", $deftext );
5772 * This function returns $oldtext after the content of the section
5773 * specified by $section has been replaced with $text. If the target
5774 * section does not exist, $oldtext is returned unchanged.
5776 * @param string $oldtext Former text of the article
5777 * @param int $section Section identifier
5778 * @param string $text Replacing text
5779 * @return string Modified text
5781 public function replaceSection( $oldtext, $section, $text ) {
5782 return $this->extractSections( $oldtext, $section, "replace", $text );
5786 * Get the ID of the revision we are parsing
5790 function getRevisionId() {
5791 return $this->mRevisionId
;
5795 * Get the revision object for $this->mRevisionId
5797 * @return Revision|null Either a Revision object or null
5798 * @since 1.23 (public since 1.23)
5800 public function getRevisionObject() {
5801 if ( !is_null( $this->mRevisionObject
) ) {
5802 return $this->mRevisionObject
;
5804 if ( is_null( $this->mRevisionId
) ) {
5808 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5809 return $this->mRevisionObject
;
5813 * Get the timestamp associated with the current revision, adjusted for
5814 * the default server-local timestamp
5817 function getRevisionTimestamp() {
5818 if ( is_null( $this->mRevisionTimestamp
) ) {
5819 wfProfileIn( __METHOD__
);
5823 $revObject = $this->getRevisionObject();
5824 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5826 # The cryptic '' timezone parameter tells to use the site-default
5827 # timezone offset instead of the user settings.
5829 # Since this value will be saved into the parser cache, served
5830 # to other users, and potentially even used inside links and such,
5831 # it needs to be consistent for all visitors.
5832 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5834 wfProfileOut( __METHOD__
);
5836 return $this->mRevisionTimestamp
;
5840 * Get the name of the user that edited the last revision
5842 * @return string User name
5844 function getRevisionUser() {
5845 if ( is_null( $this->mRevisionUser
) ) {
5846 $revObject = $this->getRevisionObject();
5848 # if this template is subst: the revision id will be blank,
5849 # so just use the current user's name
5851 $this->mRevisionUser
= $revObject->getUserText();
5852 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5853 $this->mRevisionUser
= $this->getUser()->getName();
5856 return $this->mRevisionUser
;
5860 * Get the size of the revision
5862 * @return int|null Revision size
5864 function getRevisionSize() {
5865 if ( is_null( $this->mRevisionSize
) ) {
5866 $revObject = $this->getRevisionObject();
5868 # if this variable is subst: the revision id will be blank,
5869 # so just use the parser input size, because the own substituation
5870 # will change the size.
5872 $this->mRevisionSize
= $revObject->getSize();
5873 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5874 $this->mRevisionSize
= $this->mInputSize
;
5877 return $this->mRevisionSize
;
5881 * Mutator for $mDefaultSort
5883 * @param string $sort New value
5885 public function setDefaultSort( $sort ) {
5886 $this->mDefaultSort
= $sort;
5887 $this->mOutput
->setProperty( 'defaultsort', $sort );
5891 * Accessor for $mDefaultSort
5892 * Will use the empty string if none is set.
5894 * This value is treated as a prefix, so the
5895 * empty string is equivalent to sorting by
5900 public function getDefaultSort() {
5901 if ( $this->mDefaultSort
!== false ) {
5902 return $this->mDefaultSort
;
5909 * Accessor for $mDefaultSort
5910 * Unlike getDefaultSort(), will return false if none is set
5912 * @return string|bool
5914 public function getCustomDefaultSort() {
5915 return $this->mDefaultSort
;
5919 * Try to guess the section anchor name based on a wikitext fragment
5920 * presumably extracted from a heading, for example "Header" from
5923 * @param string $text
5927 public function guessSectionNameFromWikiText( $text ) {
5928 # Strip out wikitext links(they break the anchor)
5929 $text = $this->stripSectionName( $text );
5930 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5931 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5935 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5936 * instead. For use in redirects, since IE6 interprets Redirect: headers
5937 * as something other than UTF-8 (apparently?), resulting in breakage.
5939 * @param string $text The section name
5940 * @return string An anchor
5942 public function guessLegacySectionNameFromWikiText( $text ) {
5943 # Strip out wikitext links(they break the anchor)
5944 $text = $this->stripSectionName( $text );
5945 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5946 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5950 * Strips a text string of wikitext for use in a section anchor
5952 * Accepts a text string and then removes all wikitext from the
5953 * string and leaves only the resultant text (i.e. the result of
5954 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5955 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5956 * to create valid section anchors by mimicing the output of the
5957 * parser when headings are parsed.
5959 * @param string $text Text string to be stripped of wikitext
5960 * for use in a Section anchor
5961 * @return string Filtered text string
5963 public function stripSectionName( $text ) {
5964 # Strip internal link markup
5965 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5966 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5968 # Strip external link markup
5969 # @todo FIXME: Not tolerant to blank link text
5970 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
5971 # on how many empty links there are on the page - need to figure that out.
5972 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5974 # Parse wikitext quotes (italics & bold)
5975 $text = $this->doQuotes( $text );
5978 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5983 * strip/replaceVariables/unstrip for preprocessor regression testing
5985 * @param string $text
5986 * @param Title $title
5987 * @param ParserOptions $options
5988 * @param int $outputType
5992 function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5993 $magicScopeVariable = $this->lock();
5994 $this->startParse( $title, $options, $outputType, true );
5996 $text = $this->replaceVariables( $text );
5997 $text = $this->mStripState
->unstripBoth( $text );
5998 $text = Sanitizer
::removeHTMLtags( $text );
6003 * @param string $text
6004 * @param Title $title
6005 * @param ParserOptions $options
6008 function testPst( $text, Title
$title, ParserOptions
$options ) {
6009 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6013 * @param string $text
6014 * @param Title $title
6015 * @param ParserOptions $options
6018 function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
6019 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
6023 * Call a callback function on all regions of the given text that are not
6024 * inside strip markers, and replace those regions with the return value
6025 * of the callback. For example, with input:
6029 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6030 * two strings will be replaced with the value returned by the callback in
6034 * @param callable $callback
6038 function markerSkipCallback( $s, $callback ) {
6041 while ( $i < strlen( $s ) ) {
6042 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
6043 if ( $markerStart === false ) {
6044 $out .= call_user_func( $callback, substr( $s, $i ) );
6047 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6048 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6049 if ( $markerEnd === false ) {
6050 $out .= substr( $s, $markerStart );
6053 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6054 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6063 * Remove any strip markers found in the given text.
6065 * @param string $text Input string
6068 function killMarkers( $text ) {
6069 return $this->mStripState
->killMarkers( $text );
6073 * Save the parser state required to convert the given half-parsed text to
6074 * HTML. "Half-parsed" in this context means the output of
6075 * recursiveTagParse() or internalParse(). This output has strip markers
6076 * from replaceVariables (extensionSubstitution() etc.), and link
6077 * placeholders from replaceLinkHolders().
6079 * Returns an array which can be serialized and stored persistently. This
6080 * array can later be loaded into another parser instance with
6081 * unserializeHalfParsedText(). The text can then be safely incorporated into
6082 * the return value of a parser hook.
6084 * @param string $text
6088 function serializeHalfParsedText( $text ) {
6089 wfProfileIn( __METHOD__
);
6092 'version' => self
::HALF_PARSED_VERSION
,
6093 'stripState' => $this->mStripState
->getSubState( $text ),
6094 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6096 wfProfileOut( __METHOD__
);
6101 * Load the parser state given in the $data array, which is assumed to
6102 * have been generated by serializeHalfParsedText(). The text contents is
6103 * extracted from the array, and its markers are transformed into markers
6104 * appropriate for the current Parser instance. This transformed text is
6105 * returned, and can be safely included in the return value of a parser
6108 * If the $data array has been stored persistently, the caller should first
6109 * check whether it is still valid, by calling isValidHalfParsedText().
6111 * @param array $data Serialized data
6112 * @throws MWException
6115 function unserializeHalfParsedText( $data ) {
6116 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6117 throw new MWException( __METHOD__
. ': invalid version' );
6120 # First, extract the strip state.
6121 $texts = array( $data['text'] );
6122 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6124 # Now renumber links
6125 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6127 # Should be good to go.
6132 * Returns true if the given array, presumed to be generated by
6133 * serializeHalfParsedText(), is compatible with the current version of the
6136 * @param array $data
6140 function isValidHalfParsedText( $data ) {
6141 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6145 * Parsed a width param of imagelink like 300px or 200x300px
6147 * @param string $value
6152 public function parseWidthParam( $value ) {
6153 $parsedWidthParam = array();
6154 if ( $value === '' ) {
6155 return $parsedWidthParam;
6158 # (bug 13500) In both cases (width/height and width only),
6159 # permit trailing "px" for backward compatibility.
6160 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6161 $width = intval( $m[1] );
6162 $height = intval( $m[2] );
6163 $parsedWidthParam['width'] = $width;
6164 $parsedWidthParam['height'] = $height;
6165 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6166 $width = intval( $value );
6167 $parsedWidthParam['width'] = $width;
6169 return $parsedWidthParam;
6173 * Lock the current instance of the parser.
6175 * This is meant to stop someone from calling the parser
6176 * recursively and messing up all the strip state.
6178 * @throws MWException If parser is in a parse
6179 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6181 protected function lock() {
6182 if ( $this->mInParse
) {
6183 throw new MWException( "Parser state cleared while parsing. Did you call Parser::parse recursively?" );
6185 $this->mInParse
= true;
6188 $recursiveCheck = new ScopedCallback( function() use ( $that ) {
6189 $that->mInParse
= false;
6192 return $recursiveCheck;