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 public $mTagHooks = array();
124 public $mTransparentTagHooks = array();
125 public $mFunctionHooks = array();
126 public $mFunctionSynonyms = array( 0 => array(), 1 => array() );
127 public $mFunctionTagHooks = array();
128 public $mStripList = array();
129 public $mDefaultStripList = array();
130 public $mVarCache = array();
131 public $mImageParams = array();
132 public $mImageParamsMagicArray = array();
133 public $mMarkerIndex = 0;
134 public $mFirstCall = true;
136 # Initialised by initialiseVariables()
139 * @var MagicWordArray
144 * @var MagicWordArray
147 public $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
149 # Cleared with clearState():
154 public $mAutonumber, $mDTopen;
161 public $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
163 * @var LinkHolderArray
165 public $mLinkHolders;
168 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
169 public $mDefaultSort;
170 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
171 public $mExpensiveFunctionCount; # number of expensive parser function calls
172 public $mShowToc, $mForceTocPosition;
177 public $mUser; # User object; only used when doing pre-save transform
180 # These are variables reset at least once per parse regardless of $clearState
190 public $mTitle; # Title context, used for self-link rendering and similar things
191 public $mOutputType; # Output type, one of the OT_xxx constants
192 public $ot; # Shortcut alias, see setOutputType()
193 public $mRevisionObject; # The revision object of the specified revision ID
194 public $mRevisionId; # ID to display in {{REVISIONID}} tags
195 public $mRevisionTimestamp; # The timestamp of the specified revision ID
196 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag
197 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
198 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp
199 public $mInputSize = false; # For {{PAGESIZE}} on current page.
207 * @var array Array with the language name of each language link (i.e. the
208 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
209 * duplicate language links to the ParserOutput.
211 public $mLangLinkLanguages;
214 * @var MapCacheLRU|null
217 * A cache of the current revisions of titles. Keys are $title->getPrefixedDbKey()
219 public $currentRevisionCache;
222 * @var bool Recursive call protection.
223 * This variable should be treated as if it were private.
225 public $mInParse = false;
230 public function __construct( $conf = array() ) {
231 $this->mConf
= $conf;
232 $this->mUrlProtocols
= wfUrlProtocols();
233 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
234 self
::EXT_LINK_URL_CLASS
. '+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
235 if ( isset( $conf['preprocessorClass'] ) ) {
236 $this->mPreprocessorClass
= $conf['preprocessorClass'];
237 } elseif ( defined( 'HPHP_VERSION' ) ) {
238 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
239 $this->mPreprocessorClass
= 'Preprocessor_Hash';
240 } elseif ( extension_loaded( 'domxml' ) ) {
241 # PECL extension that conflicts with the core DOM extension (bug 13770)
242 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
243 $this->mPreprocessorClass
= 'Preprocessor_Hash';
244 } elseif ( extension_loaded( 'dom' ) ) {
245 $this->mPreprocessorClass
= 'Preprocessor_DOM';
247 $this->mPreprocessorClass
= 'Preprocessor_Hash';
249 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
253 * Reduce memory usage to reduce the impact of circular references
255 public function __destruct() {
256 if ( isset( $this->mLinkHolders
) ) {
257 unset( $this->mLinkHolders
);
259 foreach ( $this as $name => $value ) {
260 unset( $this->$name );
265 * Allow extensions to clean up when the parser is cloned
267 public function __clone() {
268 $this->mInParse
= false;
269 wfRunHooks( 'ParserCloned', array( $this ) );
273 * Do various kinds of initialisation on the first call of the parser
275 public function firstCallInit() {
276 if ( !$this->mFirstCall
) {
279 $this->mFirstCall
= false;
281 wfProfileIn( __METHOD__
);
283 CoreParserFunctions
::register( $this );
284 CoreTagHooks
::register( $this );
285 $this->initialiseVariables();
287 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
288 wfProfileOut( __METHOD__
);
296 public function clearState() {
297 wfProfileIn( __METHOD__
);
298 if ( $this->mFirstCall
) {
299 $this->firstCallInit();
301 $this->mOutput
= new ParserOutput
;
302 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
303 $this->mAutonumber
= 0;
304 $this->mLastSection
= '';
305 $this->mDTopen
= false;
306 $this->mIncludeCount
= array();
307 $this->mArgStack
= false;
308 $this->mInPre
= false;
309 $this->mLinkHolders
= new LinkHolderArray( $this );
311 $this->mRevisionObject
= $this->mRevisionTimestamp
=
312 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
313 $this->mVarCache
= array();
315 $this->mLangLinkLanguages
= array();
316 $this->currentRevisionCache
= null;
319 * Prefix for temporary replacement strings for the multipass parser.
320 * \x07 should never appear in input as it's disallowed in XML.
321 * Using it at the front also gives us a little extra robustness
322 * since it shouldn't match when butted up against identifier-like
325 * Must not consist of all title characters, or else it will change
326 * the behavior of <nowiki> in a link.
328 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
329 $this->mStripState
= new StripState( $this->mUniqPrefix
);
331 # Clear these on every parse, bug 4549
332 $this->mTplRedirCache
= $this->mTplDomCache
= array();
334 $this->mShowToc
= true;
335 $this->mForceTocPosition
= false;
336 $this->mIncludeSizes
= array(
340 $this->mPPNodeCount
= 0;
341 $this->mGeneratedPPNodeCount
= 0;
342 $this->mHighestExpansionDepth
= 0;
343 $this->mDefaultSort
= false;
344 $this->mHeadings
= array();
345 $this->mDoubleUnderscores
= array();
346 $this->mExpensiveFunctionCount
= 0;
349 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
350 $this->mPreprocessor
= null;
353 wfRunHooks( 'ParserClearState', array( &$this ) );
354 wfProfileOut( __METHOD__
);
358 * Convert wikitext to HTML
359 * Do not call this function recursively.
361 * @param string $text Text we want to parse
362 * @param Title $title
363 * @param ParserOptions $options
364 * @param bool $linestart
365 * @param bool $clearState
366 * @param int $revid Number to pass in {{REVISIONID}}
367 * @return ParserOutput A ParserOutput
369 public function parse( $text, Title
$title, ParserOptions
$options,
370 $linestart = true, $clearState = true, $revid = null
373 * First pass--just handle <nowiki> sections, pass the rest off
374 * to internalParse() which does all the real work.
377 global $wgUseTidy, $wgAlwaysUseTidy, $wgShowHostnames;
378 $fname = __METHOD__
. '-' . wfGetCaller();
379 wfProfileIn( __METHOD__
);
380 wfProfileIn( $fname );
383 $magicScopeVariable = $this->lock();
386 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
388 $this->currentRevisionCache
= null;
389 $this->mInputSize
= strlen( $text );
390 if ( $this->mOptions
->getEnableLimitReport() ) {
391 $this->mOutput
->resetParseStartTime();
394 # Remove the strip marker tag prefix from the input, if present.
396 $text = str_replace( $this->mUniqPrefix
, '', $text );
399 $oldRevisionId = $this->mRevisionId
;
400 $oldRevisionObject = $this->mRevisionObject
;
401 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
402 $oldRevisionUser = $this->mRevisionUser
;
403 $oldRevisionSize = $this->mRevisionSize
;
404 if ( $revid !== null ) {
405 $this->mRevisionId
= $revid;
406 $this->mRevisionObject
= null;
407 $this->mRevisionTimestamp
= null;
408 $this->mRevisionUser
= null;
409 $this->mRevisionSize
= null;
412 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
414 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
415 $text = $this->internalParse( $text );
416 wfRunHooks( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
418 $text = $this->mStripState
->unstripGeneral( $text );
420 # Clean up special characters, only run once, next-to-last before doBlockLevels
422 # french spaces, last one Guillemet-left
423 # only if there is something before the space
424 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
425 # french spaces, Guillemet-right
426 '/(\\302\\253) /' => '\\1 ',
427 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
429 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
431 $text = $this->doBlockLevels( $text, $linestart );
433 $this->replaceLinkHolders( $text );
436 * The input doesn't get language converted if
438 * b) Content isn't converted
439 * c) It's a conversion table
440 * d) it is an interface message (which is in the user language)
442 if ( !( $options->getDisableContentConversion()
443 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
445 if ( !$this->mOptions
->getInterfaceMessage() ) {
446 # The position of the convert() call should not be changed. it
447 # assumes that the links are all replaced and the only thing left
448 # is the <nowiki> mark.
449 $text = $this->getConverterLanguage()->convert( $text );
454 * A converted title will be provided in the output object if title and
455 * content conversion are enabled, the article text does not contain
456 * a conversion-suppressing double-underscore tag, and no
457 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
458 * automatic link conversion.
460 if ( !( $options->getDisableTitleConversion()
461 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
462 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
463 ||
$this->mOutput
->getDisplayTitle() !== false )
465 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
466 if ( $convruletitle ) {
467 $this->mOutput
->setTitleText( $convruletitle );
469 $titleText = $this->getConverterLanguage()->convertTitle( $title );
470 $this->mOutput
->setTitleText( $titleText );
474 $text = $this->mStripState
->unstripNoWiki( $text );
476 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
478 $text = $this->replaceTransparentTags( $text );
479 $text = $this->mStripState
->unstripGeneral( $text );
481 $text = Sanitizer
::normalizeCharReferences( $text );
483 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
484 $text = MWTidy
::tidy( $text );
486 # attempt to sanitize at least some nesting problems
487 # (bug #2702 and quite a few others)
489 # ''Something [http://www.cool.com cool''] -->
490 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
491 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
492 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
493 # fix up an anchor inside another anchor, only
494 # at least for a single single nested link (bug 3695)
495 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
496 '\\1\\2</a>\\3</a>\\1\\4</a>',
497 # fix div inside inline elements- doBlockLevels won't wrap a line which
498 # contains a div, so fix it up here; replace
499 # div with escaped text
500 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
501 '\\1\\3<div\\5>\\6</div>\\8\\9',
502 # remove empty italic or bold tag pairs, some
503 # introduced by rules above
504 '/<([bi])><\/\\1>/' => '',
507 $text = preg_replace(
508 array_keys( $tidyregs ),
509 array_values( $tidyregs ),
513 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
514 $this->limitationWarn( 'expensive-parserfunction',
515 $this->mExpensiveFunctionCount
,
516 $this->mOptions
->getExpensiveParserFunctionLimit()
520 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
522 # Information on include size limits, for the benefit of users who try to skirt them
523 if ( $this->mOptions
->getEnableLimitReport() ) {
524 $max = $this->mOptions
->getMaxIncludeSize();
526 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
527 if ( $cpuTime !== null ) {
528 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
529 sprintf( "%.3f", $cpuTime )
533 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
534 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
535 sprintf( "%.3f", $wallTime )
538 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
539 array( $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() )
541 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
542 array( $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() )
544 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
545 array( $this->mIncludeSizes
['post-expand'], $max )
547 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
548 array( $this->mIncludeSizes
['arg'], $max )
550 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
551 array( $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() )
553 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
554 array( $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() )
556 wfRunHooks( 'ParserLimitReportPrepare', array( $this, $this->mOutput
) );
558 $limitReport = "NewPP limit report\n";
559 if ( $wgShowHostnames ) {
560 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
562 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
563 if ( wfRunHooks( 'ParserLimitReportFormat',
564 array( $key, &$value, &$limitReport, false, false )
566 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
567 $valueMsg = wfMessage( array( "$key-value-text", "$key-value" ) )
568 ->inLanguage( 'en' )->useDatabase( false );
569 if ( !$valueMsg->exists() ) {
570 $valueMsg = new RawMessage( '$1' );
572 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
573 $valueMsg->params( $value );
574 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
578 // Since we're not really outputting HTML, decode the entities and
579 // then re-encode the things that need hiding inside HTML comments.
580 $limitReport = htmlspecialchars_decode( $limitReport );
581 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
583 // Sanitize for comment. Note '‐' in the replacement is U+2010,
584 // which looks much like the problematic '-'.
585 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&' ), $limitReport );
586 $text .= "\n<!-- \n$limitReport-->\n";
588 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
589 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
590 $this->mTitle
->getPrefixedDBkey() );
593 $this->mOutput
->setText( $text );
595 $this->mRevisionId
= $oldRevisionId;
596 $this->mRevisionObject
= $oldRevisionObject;
597 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
598 $this->mRevisionUser
= $oldRevisionUser;
599 $this->mRevisionSize
= $oldRevisionSize;
600 $this->mInputSize
= false;
601 $this->currentRevisionCache
= null;
602 wfProfileOut( $fname );
603 wfProfileOut( __METHOD__
);
605 return $this->mOutput
;
609 * Recursive parser entry point that can be called from an extension tag
612 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
614 * @param string $text Text extension wants to have parsed
615 * @param bool|PPFrame $frame The frame to use for expanding any template variables
619 public function recursiveTagParse( $text, $frame = false ) {
620 wfProfileIn( __METHOD__
);
621 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
622 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
623 $text = $this->internalParse( $text, false, $frame );
624 wfProfileOut( __METHOD__
);
629 * Expand templates and variables in the text, producing valid, static wikitext.
630 * Also removes comments.
631 * Do not call this function recursively.
632 * @param string $text
633 * @param Title $title
634 * @param ParserOptions $options
635 * @param int|null $revid
636 * @param bool|PPFrame $frame
637 * @return mixed|string
639 public function preprocess( $text, Title
$title = null, ParserOptions
$options, $revid = null, $frame = false ) {
640 wfProfileIn( __METHOD__
);
641 $magicScopeVariable = $this->lock();
642 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
643 if ( $revid !== null ) {
644 $this->mRevisionId
= $revid;
646 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
647 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
648 $text = $this->replaceVariables( $text, $frame );
649 $text = $this->mStripState
->unstripBoth( $text );
650 wfProfileOut( __METHOD__
);
655 * Recursive parser entry point that can be called from an extension tag
658 * @param string $text Text to be expanded
659 * @param bool|PPFrame $frame The frame to use for expanding any template variables
663 public function recursivePreprocess( $text, $frame = false ) {
664 wfProfileIn( __METHOD__
);
665 $text = $this->replaceVariables( $text, $frame );
666 $text = $this->mStripState
->unstripBoth( $text );
667 wfProfileOut( __METHOD__
);
672 * Process the wikitext for the "?preload=" feature. (bug 5210)
674 * "<noinclude>", "<includeonly>" etc. are parsed as for template
675 * transclusion, comments, templates, arguments, tags hooks and parser
676 * functions are untouched.
678 * @param string $text
679 * @param Title $title
680 * @param ParserOptions $options
681 * @param array $params
684 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = array() ) {
685 $msg = new RawMessage( $text );
686 $text = $msg->params( $params )->plain();
688 # Parser (re)initialisation
689 $magicScopeVariable = $this->lock();
690 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
692 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
693 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
694 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
695 $text = $this->mStripState
->unstripBoth( $text );
700 * Get a random string
704 public static function getRandomString() {
705 return wfRandomString( 16 );
709 * Set the current user.
710 * Should only be used when doing pre-save transform.
712 * @param User|null $user User object or null (to reset)
714 public function setUser( $user ) {
715 $this->mUser
= $user;
719 * Accessor for mUniqPrefix.
723 public function uniqPrefix() {
724 if ( !isset( $this->mUniqPrefix
) ) {
725 # @todo FIXME: This is probably *horribly wrong*
726 # LanguageConverter seems to want $wgParser's uniqPrefix, however
727 # if this is called for a parser cache hit, the parser may not
728 # have ever been initialized in the first place.
729 # Not really sure what the heck is supposed to be going on here.
731 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
733 return $this->mUniqPrefix
;
737 * Set the context title
741 public function setTitle( $t ) {
743 $t = Title
::newFromText( 'NO TITLE' );
746 if ( $t->hasFragment() ) {
747 # Strip the fragment to avoid various odd effects
748 $this->mTitle
= clone $t;
749 $this->mTitle
->setFragment( '' );
756 * Accessor for the Title object
760 public function getTitle() {
761 return $this->mTitle
;
765 * Accessor/mutator for the Title object
767 * @param Title $x Title object or null to just get the current one
770 public function Title( $x = null ) {
771 return wfSetVar( $this->mTitle
, $x );
775 * Set the output type
777 * @param int $ot New value
779 public function setOutputType( $ot ) {
780 $this->mOutputType
= $ot;
783 'html' => $ot == self
::OT_HTML
,
784 'wiki' => $ot == self
::OT_WIKI
,
785 'pre' => $ot == self
::OT_PREPROCESS
,
786 'plain' => $ot == self
::OT_PLAIN
,
791 * Accessor/mutator for the output type
793 * @param int|null $x New value or null to just get the current one
796 public function OutputType( $x = null ) {
797 return wfSetVar( $this->mOutputType
, $x );
801 * Get the ParserOutput object
803 * @return ParserOutput
805 public function getOutput() {
806 return $this->mOutput
;
810 * Get the ParserOptions object
812 * @return ParserOptions
814 public function getOptions() {
815 return $this->mOptions
;
819 * Accessor/mutator for the ParserOptions object
821 * @param ParserOptions $x New value or null to just get the current one
822 * @return ParserOptions Current ParserOptions object
824 public function Options( $x = null ) {
825 return wfSetVar( $this->mOptions
, $x );
831 public function nextLinkID() {
832 return $this->mLinkID++
;
838 public function setLinkID( $id ) {
839 $this->mLinkID
= $id;
843 * Get a language object for use in parser functions such as {{FORMATNUM:}}
846 public function getFunctionLang() {
847 return $this->getTargetLanguage();
851 * Get the target language for the content being parsed. This is usually the
852 * language that the content is in.
856 * @throws MWException
859 public function getTargetLanguage() {
860 $target = $this->mOptions
->getTargetLanguage();
862 if ( $target !== null ) {
864 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
865 return $this->mOptions
->getUserLangObj();
866 } elseif ( is_null( $this->mTitle
) ) {
867 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
870 return $this->mTitle
->getPageLanguage();
874 * Get the language object for language conversion
875 * @return Language|null
877 public function getConverterLanguage() {
878 return $this->getTargetLanguage();
882 * Get a User object either from $this->mUser, if set, or from the
883 * ParserOptions object otherwise
887 public function getUser() {
888 if ( !is_null( $this->mUser
) ) {
891 return $this->mOptions
->getUser();
895 * Get a preprocessor object
897 * @return Preprocessor
899 public function getPreprocessor() {
900 if ( !isset( $this->mPreprocessor
) ) {
901 $class = $this->mPreprocessorClass
;
902 $this->mPreprocessor
= new $class( $this );
904 return $this->mPreprocessor
;
908 * Replaces all occurrences of HTML-style comments and the given tags
909 * in the text with a random marker and returns the next text. The output
910 * parameter $matches will be an associative array filled with data in
914 * 'UNIQ-xxxxx' => array(
917 * array( 'param' => 'x' ),
918 * '<element param="x">tag content</element>' ) )
921 * @param array $elements List of element names. Comments are always extracted.
922 * @param string $text Source text string.
923 * @param array $matches Out parameter, Array: extracted tags
924 * @param string $uniq_prefix
925 * @return string Stripped text
927 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
932 $taglist = implode( '|', $elements );
933 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
935 while ( $text != '' ) {
936 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
938 if ( count( $p ) < 5 ) {
941 if ( count( $p ) > 5 ) {
955 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
956 $stripped .= $marker;
958 if ( $close === '/>' ) {
959 # Empty element tag, <tag />
964 if ( $element === '!--' ) {
967 $end = "/(<\\/$element\\s*>)/i";
969 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
971 if ( count( $q ) < 3 ) {
972 # No end tag -- let it run out to the end of the text.
981 $matches[$marker] = array( $element,
983 Sanitizer
::decodeTagAttributes( $attributes ),
984 "<$element$attributes$close$content$tail" );
990 * Get a list of strippable XML-like elements
994 public function getStripList() {
995 return $this->mStripList
;
999 * Add an item to the strip state
1000 * Returns the unique tag which must be inserted into the stripped text
1001 * The tag will be replaced with the original text in unstrip()
1003 * @param string $text
1007 public function insertStripItem( $text ) {
1008 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
1009 $this->mMarkerIndex++
;
1010 $this->mStripState
->addGeneral( $rnd, $text );
1015 * parse the wiki syntax used to render tables
1018 * @param string $text
1021 public function doTableStuff( $text ) {
1022 wfProfileIn( __METHOD__
);
1024 $lines = StringUtils
::explode( "\n", $text );
1026 $td_history = array(); # Is currently a td tag open?
1027 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
1028 $tr_history = array(); # Is currently a tr tag open?
1029 $tr_attributes = array(); # history of tr attributes
1030 $has_opened_tr = array(); # Did this table open a <tr> element?
1031 $indent_level = 0; # indent level of the table
1033 foreach ( $lines as $outLine ) {
1034 $line = trim( $outLine );
1036 if ( $line === '' ) { # empty line, go to next line
1037 $out .= $outLine . "\n";
1041 $first_character = $line[0];
1044 if ( preg_match( '/^(:*)\{\|(.*)$/', $line, $matches ) ) {
1045 # First check if we are starting a new table
1046 $indent_level = strlen( $matches[1] );
1048 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1049 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1051 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1052 array_push( $td_history, false );
1053 array_push( $last_tag_history, '' );
1054 array_push( $tr_history, false );
1055 array_push( $tr_attributes, '' );
1056 array_push( $has_opened_tr, false );
1057 } elseif ( count( $td_history ) == 0 ) {
1058 # Don't do any of the following
1059 $out .= $outLine . "\n";
1061 } elseif ( substr( $line, 0, 2 ) === '|}' ) {
1062 # We are ending a table
1063 $line = '</table>' . substr( $line, 2 );
1064 $last_tag = array_pop( $last_tag_history );
1066 if ( !array_pop( $has_opened_tr ) ) {
1067 $line = "<tr><td></td></tr>{$line}";
1070 if ( array_pop( $tr_history ) ) {
1071 $line = "</tr>{$line}";
1074 if ( array_pop( $td_history ) ) {
1075 $line = "</{$last_tag}>{$line}";
1077 array_pop( $tr_attributes );
1078 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
1079 } elseif ( substr( $line, 0, 2 ) === '|-' ) {
1080 # Now we have a table row
1081 $line = preg_replace( '#^\|-+#', '', $line );
1083 # Whats after the tag is now only attributes
1084 $attributes = $this->mStripState
->unstripBoth( $line );
1085 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1086 array_pop( $tr_attributes );
1087 array_push( $tr_attributes, $attributes );
1090 $last_tag = array_pop( $last_tag_history );
1091 array_pop( $has_opened_tr );
1092 array_push( $has_opened_tr, true );
1094 if ( array_pop( $tr_history ) ) {
1098 if ( array_pop( $td_history ) ) {
1099 $line = "</{$last_tag}>{$line}";
1103 array_push( $tr_history, false );
1104 array_push( $td_history, false );
1105 array_push( $last_tag_history, '' );
1106 } elseif ( $first_character === '|'
1107 ||
$first_character === '!'
1108 ||
substr( $line, 0, 2 ) === '|+'
1110 # This might be cell elements, td, th or captions
1111 if ( substr( $line, 0, 2 ) === '|+' ) {
1112 $first_character = '+';
1113 $line = substr( $line, 1 );
1116 $line = substr( $line, 1 );
1118 if ( $first_character === '!' ) {
1119 $line = str_replace( '!!', '||', $line );
1122 # Split up multiple cells on the same line.
1123 # FIXME : This can result in improper nesting of tags processed
1124 # by earlier parser steps, but should avoid splitting up eg
1125 # attribute values containing literal "||".
1126 $cells = StringUtils
::explodeMarkup( '||', $line );
1130 # Loop through each table cell
1131 foreach ( $cells as $cell ) {
1133 if ( $first_character !== '+' ) {
1134 $tr_after = array_pop( $tr_attributes );
1135 if ( !array_pop( $tr_history ) ) {
1136 $previous = "<tr{$tr_after}>\n";
1138 array_push( $tr_history, true );
1139 array_push( $tr_attributes, '' );
1140 array_pop( $has_opened_tr );
1141 array_push( $has_opened_tr, true );
1144 $last_tag = array_pop( $last_tag_history );
1146 if ( array_pop( $td_history ) ) {
1147 $previous = "</{$last_tag}>\n{$previous}";
1150 if ( $first_character === '|' ) {
1152 } elseif ( $first_character === '!' ) {
1154 } elseif ( $first_character === '+' ) {
1155 $last_tag = 'caption';
1160 array_push( $last_tag_history, $last_tag );
1162 # A cell could contain both parameters and data
1163 $cell_data = explode( '|', $cell, 2 );
1165 # Bug 553: Note that a '|' inside an invalid link should not
1166 # be mistaken as delimiting cell parameters
1167 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1168 $cell = "{$previous}<{$last_tag}>{$cell}";
1169 } elseif ( count( $cell_data ) == 1 ) {
1170 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1172 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1173 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1174 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1178 array_push( $td_history, true );
1181 $out .= $outLine . "\n";
1184 # Closing open td, tr && table
1185 while ( count( $td_history ) > 0 ) {
1186 if ( array_pop( $td_history ) ) {
1189 if ( array_pop( $tr_history ) ) {
1192 if ( !array_pop( $has_opened_tr ) ) {
1193 $out .= "<tr><td></td></tr>\n";
1196 $out .= "</table>\n";
1199 # Remove trailing line-ending (b/c)
1200 if ( substr( $out, -1 ) === "\n" ) {
1201 $out = substr( $out, 0, -1 );
1204 # special case: don't return empty table
1205 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1209 wfProfileOut( __METHOD__
);
1215 * Helper function for parse() that transforms wiki markup into
1216 * HTML. Only called for $mOutputType == self::OT_HTML.
1220 * @param string $text
1221 * @param bool $isMain
1222 * @param bool $frame
1226 public function internalParse( $text, $isMain = true, $frame = false ) {
1227 wfProfileIn( __METHOD__
);
1231 # Hook to suspend the parser in this state
1232 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1233 wfProfileOut( __METHOD__
);
1237 # if $frame is provided, then use $frame for replacing any variables
1239 # use frame depth to infer how include/noinclude tags should be handled
1240 # depth=0 means this is the top-level document; otherwise it's an included document
1241 if ( !$frame->depth
) {
1244 $flag = Parser
::PTD_FOR_INCLUSION
;
1246 $dom = $this->preprocessToDom( $text, $flag );
1247 $text = $frame->expand( $dom );
1249 # if $frame is not provided, then use old-style replaceVariables
1250 $text = $this->replaceVariables( $text );
1253 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1254 $text = Sanitizer
::removeHTMLtags(
1256 array( &$this, 'attributeStripCallback' ),
1258 array_keys( $this->mTransparentTagHooks
)
1260 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1262 # Tables need to come after variable replacement for things to work
1263 # properly; putting them before other transformations should keep
1264 # exciting things like link expansions from showing up in surprising
1266 $text = $this->doTableStuff( $text );
1268 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1270 $text = $this->doDoubleUnderscore( $text );
1272 $text = $this->doHeadings( $text );
1273 $text = $this->replaceInternalLinks( $text );
1274 $text = $this->doAllQuotes( $text );
1275 $text = $this->replaceExternalLinks( $text );
1277 # replaceInternalLinks may sometimes leave behind
1278 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1279 $text = str_replace( $this->mUniqPrefix
. 'NOPARSE', '', $text );
1281 $text = $this->doMagicLinks( $text );
1282 $text = $this->formatHeadings( $text, $origText, $isMain );
1284 wfProfileOut( __METHOD__
);
1289 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1290 * magic external links.
1295 * @param string $text
1299 public function doMagicLinks( $text ) {
1300 wfProfileIn( __METHOD__
);
1301 $prots = wfUrlProtocolsWithoutProtRel();
1302 $urlChar = self
::EXT_LINK_URL_CLASS
;
1303 $text = preg_replace_callback(
1305 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1306 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1307 (\\b(?i:$prots)$urlChar+) | # m[3]: Free external links" . '
1308 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1309 ISBN\s+(\b # m[5]: ISBN, capture number
1310 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1311 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1312 [0-9Xx] # check digit
1314 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1315 wfProfileOut( __METHOD__
);
1320 * @throws MWException
1322 * @return HTML|string
1324 public function magicLinkCallback( $m ) {
1325 if ( isset( $m[1] ) && $m[1] !== '' ) {
1328 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1331 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1332 # Free external link
1333 return $this->makeFreeExternalLink( $m[0] );
1334 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1336 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1339 $cssClass = 'mw-magiclink-rfc';
1341 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1343 $urlmsg = 'pubmedurl';
1344 $cssClass = 'mw-magiclink-pmid';
1347 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1348 substr( $m[0], 0, 20 ) . '"' );
1350 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1351 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass );
1352 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1355 $num = strtr( $isbn, array(
1360 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1361 return '<a href="' .
1362 htmlspecialchars( $titleObj->getLocalURL() ) .
1363 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1370 * Make a free external link, given a user-supplied URL
1372 * @param string $url
1374 * @return string HTML
1377 public function makeFreeExternalLink( $url ) {
1378 wfProfileIn( __METHOD__
);
1382 # The characters '<' and '>' (which were escaped by
1383 # removeHTMLtags()) should not be included in
1384 # URLs, per RFC 2396.
1386 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1387 $trail = substr( $url, $m2[0][1] ) . $trail;
1388 $url = substr( $url, 0, $m2[0][1] );
1391 # Move trailing punctuation to $trail
1393 # If there is no left bracket, then consider right brackets fair game too
1394 if ( strpos( $url, '(' ) === false ) {
1398 $numSepChars = strspn( strrev( $url ), $sep );
1399 if ( $numSepChars ) {
1400 $trail = substr( $url, -$numSepChars ) . $trail;
1401 $url = substr( $url, 0, -$numSepChars );
1404 $url = Sanitizer
::cleanUrl( $url );
1406 # Is this an external image?
1407 $text = $this->maybeMakeExternalImage( $url );
1408 if ( $text === false ) {
1409 # Not an image, make a link
1410 $text = Linker
::makeExternalLink( $url,
1411 $this->getConverterLanguage()->markNoConversion( $url, true ),
1413 $this->getExternalLinkAttribs( $url ) );
1414 # Register it in the output object...
1415 # Replace unnecessary URL escape codes with their equivalent characters
1416 $pasteurized = self
::replaceUnusualEscapes( $url );
1417 $this->mOutput
->addExternalLink( $pasteurized );
1419 wfProfileOut( __METHOD__
);
1420 return $text . $trail;
1424 * Parse headers and return html
1428 * @param string $text
1432 public function doHeadings( $text ) {
1433 wfProfileIn( __METHOD__
);
1434 for ( $i = 6; $i >= 1; --$i ) {
1435 $h = str_repeat( '=', $i );
1436 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1438 wfProfileOut( __METHOD__
);
1443 * Replace single quotes with HTML markup
1446 * @param string $text
1448 * @return string The altered text
1450 public function doAllQuotes( $text ) {
1451 wfProfileIn( __METHOD__
);
1453 $lines = StringUtils
::explode( "\n", $text );
1454 foreach ( $lines as $line ) {
1455 $outtext .= $this->doQuotes( $line ) . "\n";
1457 $outtext = substr( $outtext, 0, -1 );
1458 wfProfileOut( __METHOD__
);
1463 * Helper function for doAllQuotes()
1465 * @param string $text
1469 public function doQuotes( $text ) {
1470 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1471 $countarr = count( $arr );
1472 if ( $countarr == 1 ) {
1476 // First, do some preliminary work. This may shift some apostrophes from
1477 // being mark-up to being text. It also counts the number of occurrences
1478 // of bold and italics mark-ups.
1481 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1482 $thislen = strlen( $arr[$i] );
1483 // If there are ever four apostrophes, assume the first is supposed to
1484 // be text, and the remaining three constitute mark-up for bold text.
1485 // (bug 13227: ''''foo'''' turns into ' ''' foo ' ''')
1486 if ( $thislen == 4 ) {
1487 $arr[$i - 1] .= "'";
1490 } elseif ( $thislen > 5 ) {
1491 // If there are more than 5 apostrophes in a row, assume they're all
1492 // text except for the last 5.
1493 // (bug 13227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1494 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1498 // Count the number of occurrences of bold and italics mark-ups.
1499 if ( $thislen == 2 ) {
1501 } elseif ( $thislen == 3 ) {
1503 } elseif ( $thislen == 5 ) {
1509 // If there is an odd number of both bold and italics, it is likely
1510 // that one of the bold ones was meant to be an apostrophe followed
1511 // by italics. Which one we cannot know for certain, but it is more
1512 // likely to be one that has a single-letter word before it.
1513 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1514 $firstsingleletterword = -1;
1515 $firstmultiletterword = -1;
1517 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1518 if ( strlen( $arr[$i] ) == 3 ) {
1519 $x1 = substr( $arr[$i - 1], -1 );
1520 $x2 = substr( $arr[$i - 1], -2, 1 );
1521 if ( $x1 === ' ' ) {
1522 if ( $firstspace == -1 ) {
1525 } elseif ( $x2 === ' ' ) {
1526 if ( $firstsingleletterword == -1 ) {
1527 $firstsingleletterword = $i;
1528 // if $firstsingleletterword is set, we don't
1529 // look at the other options, so we can bail early.
1533 if ( $firstmultiletterword == -1 ) {
1534 $firstmultiletterword = $i;
1540 // If there is a single-letter word, use it!
1541 if ( $firstsingleletterword > -1 ) {
1542 $arr[$firstsingleletterword] = "''";
1543 $arr[$firstsingleletterword - 1] .= "'";
1544 } elseif ( $firstmultiletterword > -1 ) {
1545 // If not, but there's a multi-letter word, use that one.
1546 $arr[$firstmultiletterword] = "''";
1547 $arr[$firstmultiletterword - 1] .= "'";
1548 } elseif ( $firstspace > -1 ) {
1549 // ... otherwise use the first one that has neither.
1550 // (notice that it is possible for all three to be -1 if, for example,
1551 // there is only one pentuple-apostrophe in the line)
1552 $arr[$firstspace] = "''";
1553 $arr[$firstspace - 1] .= "'";
1557 // Now let's actually convert our apostrophic mush to HTML!
1562 foreach ( $arr as $r ) {
1563 if ( ( $i %
2 ) == 0 ) {
1564 if ( $state === 'both' ) {
1570 $thislen = strlen( $r );
1571 if ( $thislen == 2 ) {
1572 if ( $state === 'i' ) {
1575 } elseif ( $state === 'bi' ) {
1578 } elseif ( $state === 'ib' ) {
1579 $output .= '</b></i><b>';
1581 } elseif ( $state === 'both' ) {
1582 $output .= '<b><i>' . $buffer . '</i>';
1584 } else { // $state can be 'b' or ''
1588 } elseif ( $thislen == 3 ) {
1589 if ( $state === 'b' ) {
1592 } elseif ( $state === 'bi' ) {
1593 $output .= '</i></b><i>';
1595 } elseif ( $state === 'ib' ) {
1598 } elseif ( $state === 'both' ) {
1599 $output .= '<i><b>' . $buffer . '</b>';
1601 } else { // $state can be 'i' or ''
1605 } elseif ( $thislen == 5 ) {
1606 if ( $state === 'b' ) {
1607 $output .= '</b><i>';
1609 } elseif ( $state === 'i' ) {
1610 $output .= '</i><b>';
1612 } elseif ( $state === 'bi' ) {
1613 $output .= '</i></b>';
1615 } elseif ( $state === 'ib' ) {
1616 $output .= '</b></i>';
1618 } elseif ( $state === 'both' ) {
1619 $output .= '<i><b>' . $buffer . '</b></i>';
1621 } else { // ($state == '')
1629 // Now close all remaining tags. Notice that the order is important.
1630 if ( $state === 'b' ||
$state === 'ib' ) {
1633 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1636 if ( $state === 'bi' ) {
1639 // There might be lonely ''''', so make sure we have a buffer
1640 if ( $state === 'both' && $buffer ) {
1641 $output .= '<b><i>' . $buffer . '</i></b>';
1647 * Replace external links (REL)
1649 * Note: this is all very hackish and the order of execution matters a lot.
1650 * Make sure to run tests/parserTests.php if you change this code.
1654 * @param string $text
1656 * @throws MWException
1659 public function replaceExternalLinks( $text ) {
1660 wfProfileIn( __METHOD__
);
1662 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1663 if ( $bits === false ) {
1664 wfProfileOut( __METHOD__
);
1665 throw new MWException( "PCRE needs to be compiled with "
1666 . "--enable-unicode-properties in order for MediaWiki to function" );
1668 $s = array_shift( $bits );
1671 while ( $i < count( $bits ) ) {
1674 $text = $bits[$i++
];
1675 $trail = $bits[$i++
];
1677 # The characters '<' and '>' (which were escaped by
1678 # removeHTMLtags()) should not be included in
1679 # URLs, per RFC 2396.
1681 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1682 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1683 $url = substr( $url, 0, $m2[0][1] );
1686 # If the link text is an image URL, replace it with an <img> tag
1687 # This happened by accident in the original parser, but some people used it extensively
1688 $img = $this->maybeMakeExternalImage( $text );
1689 if ( $img !== false ) {
1695 # Set linktype for CSS - if URL==text, link is essentially free
1696 $linktype = ( $text === $url ) ?
'free' : 'text';
1698 # No link text, e.g. [http://domain.tld/some.link]
1699 if ( $text == '' ) {
1701 $langObj = $this->getTargetLanguage();
1702 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1703 $linktype = 'autonumber';
1705 # Have link text, e.g. [http://domain.tld/some.link text]s
1707 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1710 $text = $this->getConverterLanguage()->markNoConversion( $text );
1712 $url = Sanitizer
::cleanUrl( $url );
1714 # Use the encoded URL
1715 # This means that users can paste URLs directly into the text
1716 # Funny characters like ö aren't valid in URLs anyway
1717 # This was changed in August 2004
1718 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1719 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1721 # Register link in the output object.
1722 # Replace unnecessary URL escape codes with the referenced character
1723 # This prevents spammers from hiding links from the filters
1724 $pasteurized = self
::replaceUnusualEscapes( $url );
1725 $this->mOutput
->addExternalLink( $pasteurized );
1728 wfProfileOut( __METHOD__
);
1733 * Get the rel attribute for a particular external link.
1736 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1737 * nofollow if appropriate
1738 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1739 * @return string|null Rel attribute for $url
1741 public static function getExternalLinkRel( $url = false, $title = null ) {
1742 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1743 $ns = $title ?
$title->getNamespace() : false;
1744 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1745 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1753 * Get an associative array of additional HTML attributes appropriate for a
1754 * particular external link. This currently may include rel => nofollow
1755 * (depending on configuration, namespace, and the URL's domain) and/or a
1756 * target attribute (depending on configuration).
1758 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1759 * nofollow if appropriate
1760 * @return array Associative array of HTML attributes
1762 public function getExternalLinkAttribs( $url = false ) {
1764 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1766 if ( $this->mOptions
->getExternalLinkTarget() ) {
1767 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1773 * Replace unusual URL escape codes with their equivalent characters
1775 * @param string $url
1778 * @todo This can merge genuinely required bits in the path or query string,
1779 * breaking legit URLs. A proper fix would treat the various parts of
1780 * the URL differently; as a workaround, just use the output for
1781 * statistical records, not for actual linking/output.
1783 public static function replaceUnusualEscapes( $url ) {
1784 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1785 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1789 * Callback function used in replaceUnusualEscapes().
1790 * Replaces unusual URL escape codes with their equivalent character
1792 * @param array $matches
1796 private static function replaceUnusualEscapesCallback( $matches ) {
1797 $char = urldecode( $matches[0] );
1798 $ord = ord( $char );
1799 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1800 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1801 # No, shouldn't be escaped
1804 # Yes, leave it escaped
1810 * make an image if it's allowed, either through the global
1811 * option, through the exception, or through the on-wiki whitelist
1813 * @param string $url
1817 private function maybeMakeExternalImage( $url ) {
1818 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1819 $imagesexception = !empty( $imagesfrom );
1821 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1822 if ( $imagesexception && is_array( $imagesfrom ) ) {
1823 $imagematch = false;
1824 foreach ( $imagesfrom as $match ) {
1825 if ( strpos( $url, $match ) === 0 ) {
1830 } elseif ( $imagesexception ) {
1831 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1833 $imagematch = false;
1836 if ( $this->mOptions
->getAllowExternalImages()
1837 ||
( $imagesexception && $imagematch )
1839 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1841 $text = Linker
::makeExternalImage( $url );
1844 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1845 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
1847 $whitelist = explode(
1849 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
1852 foreach ( $whitelist as $entry ) {
1853 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1854 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1857 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1858 # Image matches a whitelist entry
1859 $text = Linker
::makeExternalImage( $url );
1868 * Process [[ ]] wikilinks
1872 * @return string Processed text
1876 public function replaceInternalLinks( $s ) {
1877 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1882 * Process [[ ]] wikilinks (RIL)
1884 * @throws MWException
1885 * @return LinkHolderArray
1889 public function replaceInternalLinks2( &$s ) {
1890 global $wgExtraInterlanguageLinkPrefixes;
1891 wfProfileIn( __METHOD__
);
1893 wfProfileIn( __METHOD__
. '-setup' );
1894 static $tc = false, $e1, $e1_img;
1895 # the % is needed to support urlencoded titles as well
1897 $tc = Title
::legalChars() . '#%';
1898 # Match a link having the form [[namespace:link|alternate]]trail
1899 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1900 # Match cases where there is no "]]", which might still be images
1901 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1904 $holders = new LinkHolderArray( $this );
1906 # split the entire text string on occurrences of [[
1907 $a = StringUtils
::explode( '[[', ' ' . $s );
1908 # get the first element (all text up to first [[), and remove the space we added
1911 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1912 $s = substr( $s, 1 );
1914 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1916 if ( $useLinkPrefixExtension ) {
1917 # Match the end of a line for a word that's not followed by whitespace,
1918 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1920 $charset = $wgContLang->linkPrefixCharset();
1921 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
1924 if ( is_null( $this->mTitle
) ) {
1925 wfProfileOut( __METHOD__
. '-setup' );
1926 wfProfileOut( __METHOD__
);
1927 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
1929 $nottalk = !$this->mTitle
->isTalkPage();
1931 if ( $useLinkPrefixExtension ) {
1933 if ( preg_match( $e2, $s, $m ) ) {
1934 $first_prefix = $m[2];
1936 $first_prefix = false;
1942 $useSubpages = $this->areSubpagesAllowed();
1943 wfProfileOut( __METHOD__
. '-setup' );
1945 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
1946 # Loop for each link
1947 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
1948 // @codingStandardsIgnoreStart
1950 # Check for excessive memory usage
1951 if ( $holders->isBig() ) {
1953 # Do the existence check, replace the link holders and clear the array
1954 $holders->replace( $s );
1958 if ( $useLinkPrefixExtension ) {
1959 wfProfileIn( __METHOD__
. '-prefixhandling' );
1960 if ( preg_match( $e2, $s, $m ) ) {
1967 if ( $first_prefix ) {
1968 $prefix = $first_prefix;
1969 $first_prefix = false;
1971 wfProfileOut( __METHOD__
. '-prefixhandling' );
1974 $might_be_img = false;
1976 wfProfileIn( __METHOD__
. "-e1" );
1977 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1979 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1980 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1981 # the real problem is with the $e1 regex
1984 # Still some problems for cases where the ] is meant to be outside punctuation,
1985 # and no image is in sight. See bug 2095.
1988 && substr( $m[3], 0, 1 ) === ']'
1989 && strpos( $text, '[' ) !== false
1991 $text .= ']'; # so that replaceExternalLinks($text) works later
1992 $m[3] = substr( $m[3], 1 );
1994 # fix up urlencoded title texts
1995 if ( strpos( $m[1], '%' ) !== false ) {
1996 # Should anchors '#' also be rejected?
1997 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) );
2000 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2001 # Invalid, but might be an image with a link in its caption
2002 $might_be_img = true;
2004 if ( strpos( $m[1], '%' ) !== false ) {
2005 $m[1] = rawurldecode( $m[1] );
2008 } else { # Invalid form; output directly
2009 $s .= $prefix . '[[' . $line;
2010 wfProfileOut( __METHOD__
. "-e1" );
2013 wfProfileOut( __METHOD__
. "-e1" );
2014 wfProfileIn( __METHOD__
. "-misc" );
2018 # Don't allow internal links to pages containing
2019 # PROTO: where PROTO is a valid URL protocol; these
2020 # should be external links.
2021 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2022 $s .= $prefix . '[[' . $line;
2023 wfProfileOut( __METHOD__
. "-misc" );
2027 # Make subpage if necessary
2028 if ( $useSubpages ) {
2029 $link = $this->maybeDoSubpageLink( $origLink, $text );
2034 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2036 # Strip off leading ':'
2037 $link = substr( $link, 1 );
2040 wfProfileOut( __METHOD__
. "-misc" );
2041 wfProfileIn( __METHOD__
. "-title" );
2042 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
2043 if ( $nt === null ) {
2044 $s .= $prefix . '[[' . $line;
2045 wfProfileOut( __METHOD__
. "-title" );
2049 $ns = $nt->getNamespace();
2050 $iw = $nt->getInterwiki();
2051 wfProfileOut( __METHOD__
. "-title" );
2053 if ( $might_be_img ) { # if this is actually an invalid link
2054 wfProfileIn( __METHOD__
. "-might_be_img" );
2055 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2058 # look at the next 'line' to see if we can close it there
2060 $next_line = $a->current();
2061 if ( $next_line === false ||
$next_line === null ) {
2064 $m = explode( ']]', $next_line, 3 );
2065 if ( count( $m ) == 3 ) {
2066 # the first ]] closes the inner link, the second the image
2068 $text .= "[[{$m[0]}]]{$m[1]}";
2071 } elseif ( count( $m ) == 2 ) {
2072 # if there's exactly one ]] that's fine, we'll keep looking
2073 $text .= "[[{$m[0]}]]{$m[1]}";
2075 # if $next_line is invalid too, we need look no further
2076 $text .= '[[' . $next_line;
2081 # we couldn't find the end of this imageLink, so output it raw
2082 # but don't ignore what might be perfectly normal links in the text we've examined
2083 $holders->merge( $this->replaceInternalLinks2( $text ) );
2084 $s .= "{$prefix}[[$link|$text";
2085 # note: no $trail, because without an end, there *is* no trail
2086 wfProfileOut( __METHOD__
. "-might_be_img" );
2089 } else { # it's not an image, so output it raw
2090 $s .= "{$prefix}[[$link|$text";
2091 # note: no $trail, because without an end, there *is* no trail
2092 wfProfileOut( __METHOD__
. "-might_be_img" );
2095 wfProfileOut( __METHOD__
. "-might_be_img" );
2098 $wasblank = ( $text == '' );
2102 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
2103 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2104 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2105 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2106 $text = $this->doQuotes( $text );
2109 # Link not escaped by : , create the various objects
2110 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2112 wfProfileIn( __METHOD__
. "-interwiki" );
2114 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2115 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2116 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2119 # Bug 24502: filter duplicates
2120 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2121 $this->mLangLinkLanguages
[$iw] = true;
2122 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2125 $s = rtrim( $s . $prefix );
2126 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2127 wfProfileOut( __METHOD__
. "-interwiki" );
2130 wfProfileOut( __METHOD__
. "-interwiki" );
2132 if ( $ns == NS_FILE
) {
2133 wfProfileIn( __METHOD__
. "-image" );
2134 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2136 # if no parameters were passed, $text
2137 # becomes something like "File:Foo.png",
2138 # which we don't want to pass on to the
2142 # recursively parse links inside the image caption
2143 # actually, this will parse them in any other parameters, too,
2144 # but it might be hard to fix that, and it doesn't matter ATM
2145 $text = $this->replaceExternalLinks( $text );
2146 $holders->merge( $this->replaceInternalLinks2( $text ) );
2148 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2149 $s .= $prefix . $this->armorLinks(
2150 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2152 $s .= $prefix . $trail;
2154 wfProfileOut( __METHOD__
. "-image" );
2158 if ( $ns == NS_CATEGORY
) {
2159 wfProfileIn( __METHOD__
. "-category" );
2160 $s = rtrim( $s . "\n" ); # bug 87
2163 $sortkey = $this->getDefaultSort();
2167 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2168 $sortkey = str_replace( "\n", '', $sortkey );
2169 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2170 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2173 * Strip the whitespace Category links produce, see bug 87
2175 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2177 wfProfileOut( __METHOD__
. "-category" );
2182 # Self-link checking. For some languages, variants of the title are checked in
2183 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2184 # for linking to a different variant.
2185 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2186 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2190 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2191 # @todo FIXME: Should do batch file existence checks, see comment below
2192 if ( $ns == NS_MEDIA
) {
2193 wfProfileIn( __METHOD__
. "-media" );
2194 # Give extensions a chance to select the file revision for us
2197 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2198 array( $this, $nt, &$options, &$descQuery ) );
2199 # Fetch and register the file (file title may be different via hooks)
2200 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2201 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2202 $s .= $prefix . $this->armorLinks(
2203 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2204 wfProfileOut( __METHOD__
. "-media" );
2208 wfProfileIn( __METHOD__
. "-always_known" );
2209 # Some titles, such as valid special pages or files in foreign repos, should
2210 # be shown as bluelinks even though they're not included in the page table
2212 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2213 # batch file existence checks for NS_FILE and NS_MEDIA
2214 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2215 $this->mOutput
->addLink( $nt );
2216 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2218 # Links will be added to the output link list after checking
2219 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2221 wfProfileOut( __METHOD__
. "-always_known" );
2223 wfProfileOut( __METHOD__
);
2228 * Render a forced-blue link inline; protect against double expansion of
2229 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2230 * Since this little disaster has to split off the trail text to avoid
2231 * breaking URLs in the following text without breaking trails on the
2232 * wiki links, it's been made into a horrible function.
2235 * @param string $text
2236 * @param array|string $query
2237 * @param string $trail
2238 * @param string $prefix
2239 * @return string HTML-wikitext mix oh yuck
2241 public function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2242 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2244 if ( is_string( $query ) ) {
2245 $query = wfCgiToArray( $query );
2247 if ( $text == '' ) {
2248 $text = htmlspecialchars( $nt->getPrefixedText() );
2251 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2253 return $this->armorLinks( $link ) . $trail;
2257 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2258 * going to go through further parsing steps before inline URL expansion.
2260 * Not needed quite as much as it used to be since free links are a bit
2261 * more sensible these days. But bracketed links are still an issue.
2263 * @param string $text More-or-less HTML
2264 * @return string Less-or-more HTML with NOPARSE bits
2266 public function armorLinks( $text ) {
2267 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2268 "{$this->mUniqPrefix}NOPARSE$1", $text );
2272 * Return true if subpage links should be expanded on this page.
2275 public function areSubpagesAllowed() {
2276 # Some namespaces don't allow subpages
2277 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2281 * Handle link to subpage if necessary
2283 * @param string $target The source of the link
2284 * @param string &$text The link text, modified as necessary
2285 * @return string The full name of the link
2288 public function maybeDoSubpageLink( $target, &$text ) {
2289 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2293 * Used by doBlockLevels()
2298 public function closeParagraph() {
2300 if ( $this->mLastSection
!= '' ) {
2301 $result = '</' . $this->mLastSection
. ">\n";
2303 $this->mInPre
= false;
2304 $this->mLastSection
= '';
2309 * getCommon() returns the length of the longest common substring
2310 * of both arguments, starting at the beginning of both.
2313 * @param string $st1
2314 * @param string $st2
2318 public function getCommon( $st1, $st2 ) {
2319 $fl = strlen( $st1 );
2320 $shorter = strlen( $st2 );
2321 if ( $fl < $shorter ) {
2325 for ( $i = 0; $i < $shorter; ++
$i ) {
2326 if ( $st1[$i] != $st2[$i] ) {
2334 * These next three functions open, continue, and close the list
2335 * element appropriate to the prefix character passed into them.
2338 * @param string $char
2342 public function openList( $char ) {
2343 $result = $this->closeParagraph();
2345 if ( '*' === $char ) {
2346 $result .= "<ul><li>";
2347 } elseif ( '#' === $char ) {
2348 $result .= "<ol><li>";
2349 } elseif ( ':' === $char ) {
2350 $result .= "<dl><dd>";
2351 } elseif ( ';' === $char ) {
2352 $result .= "<dl><dt>";
2353 $this->mDTopen
= true;
2355 $result = '<!-- ERR 1 -->';
2363 * @param string $char
2368 public function nextItem( $char ) {
2369 if ( '*' === $char ||
'#' === $char ) {
2370 return "</li>\n<li>";
2371 } elseif ( ':' === $char ||
';' === $char ) {
2373 if ( $this->mDTopen
) {
2376 if ( ';' === $char ) {
2377 $this->mDTopen
= true;
2378 return $close . '<dt>';
2380 $this->mDTopen
= false;
2381 return $close . '<dd>';
2384 return '<!-- ERR 2 -->';
2389 * @param string $char
2394 public function closeList( $char ) {
2395 if ( '*' === $char ) {
2396 $text = "</li></ul>";
2397 } elseif ( '#' === $char ) {
2398 $text = "</li></ol>";
2399 } elseif ( ':' === $char ) {
2400 if ( $this->mDTopen
) {
2401 $this->mDTopen
= false;
2402 $text = "</dt></dl>";
2404 $text = "</dd></dl>";
2407 return '<!-- ERR 3 -->';
2414 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2416 * @param string $text
2417 * @param bool $linestart Whether or not this is at the start of a line.
2419 * @return string The lists rendered as HTML
2421 public function doBlockLevels( $text, $linestart ) {
2422 wfProfileIn( __METHOD__
);
2424 # Parsing through the text line by line. The main thing
2425 # happening here is handling of block-level elements p, pre,
2426 # and making lists from lines starting with * # : etc.
2428 $textLines = StringUtils
::explode( "\n", $text );
2430 $lastPrefix = $output = '';
2431 $this->mDTopen
= $inBlockElem = false;
2433 $paragraphStack = false;
2434 $inBlockquote = false;
2436 foreach ( $textLines as $oLine ) {
2438 if ( !$linestart ) {
2448 $lastPrefixLength = strlen( $lastPrefix );
2449 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2450 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2451 # If not in a <pre> element, scan for and figure out what prefixes are there.
2452 if ( !$this->mInPre
) {
2453 # Multiple prefixes may abut each other for nested lists.
2454 $prefixLength = strspn( $oLine, '*#:;' );
2455 $prefix = substr( $oLine, 0, $prefixLength );
2458 # ; and : are both from definition-lists, so they're equivalent
2459 # for the purposes of determining whether or not we need to open/close
2461 $prefix2 = str_replace( ';', ':', $prefix );
2462 $t = substr( $oLine, $prefixLength );
2463 $this->mInPre
= (bool)$preOpenMatch;
2465 # Don't interpret any other prefixes in preformatted text
2467 $prefix = $prefix2 = '';
2472 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2473 # Same as the last item, so no need to deal with nesting or opening stuff
2474 $output .= $this->nextItem( substr( $prefix, -1 ) );
2475 $paragraphStack = false;
2477 if ( substr( $prefix, -1 ) === ';' ) {
2478 # The one nasty exception: definition lists work like this:
2479 # ; title : definition text
2480 # So we check for : in the remainder text to split up the
2481 # title and definition, without b0rking links.
2483 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2485 $output .= $term . $this->nextItem( ':' );
2488 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2489 # We need to open or close prefixes, or both.
2491 # Either open or close a level...
2492 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2493 $paragraphStack = false;
2495 # Close all the prefixes which aren't shared.
2496 while ( $commonPrefixLength < $lastPrefixLength ) {
2497 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2498 --$lastPrefixLength;
2501 # Continue the current prefix if appropriate.
2502 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2503 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2506 # Open prefixes where appropriate.
2507 if ( $lastPrefix && $prefixLength > $commonPrefixLength ) {
2510 while ( $prefixLength > $commonPrefixLength ) {
2511 $char = substr( $prefix, $commonPrefixLength, 1 );
2512 $output .= $this->openList( $char );
2514 if ( ';' === $char ) {
2515 # @todo FIXME: This is dupe of code above
2516 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2518 $output .= $term . $this->nextItem( ':' );
2521 ++
$commonPrefixLength;
2523 if ( !$prefixLength && $lastPrefix ) {
2526 $lastPrefix = $prefix2;
2529 # If we have no prefixes, go to paragraph mode.
2530 if ( 0 == $prefixLength ) {
2531 wfProfileIn( __METHOD__
. "-paragraph" );
2532 # No prefix (not in list)--go to paragraph mode
2533 # XXX: use a stack for nestable elements like span, table and div
2534 $openmatch = preg_match(
2535 '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|'
2536 . '<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS',
2539 $closematch = preg_match(
2540 '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'
2541 . '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|<\\/mw:|'
2542 . $this->mUniqPrefix
2543 . '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS',
2547 if ( $openmatch or $closematch ) {
2548 $paragraphStack = false;
2549 # @todo bug 5718: paragraph closed
2550 $output .= $this->closeParagraph();
2551 if ( $preOpenMatch and !$preCloseMatch ) {
2552 $this->mInPre
= true;
2555 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t, $bqMatch, PREG_OFFSET_CAPTURE
, $bqOffset ) ) {
2556 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
2557 $bqOffset = $bqMatch[0][1] +
strlen( $bqMatch[0][0] );
2559 $inBlockElem = !$closematch;
2560 } elseif ( !$inBlockElem && !$this->mInPre
) {
2561 if ( ' ' == substr( $t, 0, 1 )
2562 && ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' )
2566 if ( $this->mLastSection
!== 'pre' ) {
2567 $paragraphStack = false;
2568 $output .= $this->closeParagraph() . '<pre>';
2569 $this->mLastSection
= 'pre';
2571 $t = substr( $t, 1 );
2574 if ( trim( $t ) === '' ) {
2575 if ( $paragraphStack ) {
2576 $output .= $paragraphStack . '<br />';
2577 $paragraphStack = false;
2578 $this->mLastSection
= 'p';
2580 if ( $this->mLastSection
!== 'p' ) {
2581 $output .= $this->closeParagraph();
2582 $this->mLastSection
= '';
2583 $paragraphStack = '<p>';
2585 $paragraphStack = '</p><p>';
2589 if ( $paragraphStack ) {
2590 $output .= $paragraphStack;
2591 $paragraphStack = false;
2592 $this->mLastSection
= 'p';
2593 } elseif ( $this->mLastSection
!== 'p' ) {
2594 $output .= $this->closeParagraph() . '<p>';
2595 $this->mLastSection
= 'p';
2600 wfProfileOut( __METHOD__
. "-paragraph" );
2602 # somewhere above we forget to get out of pre block (bug 785)
2603 if ( $preCloseMatch && $this->mInPre
) {
2604 $this->mInPre
= false;
2606 if ( $paragraphStack === false ) {
2608 if ( $prefixLength === 0 ) {
2613 while ( $prefixLength ) {
2614 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2616 if ( !$prefixLength ) {
2620 if ( $this->mLastSection
!= '' ) {
2621 $output .= '</' . $this->mLastSection
. '>';
2622 $this->mLastSection
= '';
2625 wfProfileOut( __METHOD__
);
2630 * Split up a string on ':', ignoring any occurrences inside tags
2631 * to prevent illegal overlapping.
2633 * @param string $str The string to split
2634 * @param string &$before Set to everything before the ':'
2635 * @param string &$after Set to everything after the ':'
2636 * @throws MWException
2637 * @return string The position of the ':', or false if none found
2639 public function findColonNoLinks( $str, &$before, &$after ) {
2640 wfProfileIn( __METHOD__
);
2642 $pos = strpos( $str, ':' );
2643 if ( $pos === false ) {
2645 wfProfileOut( __METHOD__
);
2649 $lt = strpos( $str, '<' );
2650 if ( $lt === false ||
$lt > $pos ) {
2651 # Easy; no tag nesting to worry about
2652 $before = substr( $str, 0, $pos );
2653 $after = substr( $str, $pos +
1 );
2654 wfProfileOut( __METHOD__
);
2658 # Ugly state machine to walk through avoiding tags.
2659 $state = self
::COLON_STATE_TEXT
;
2661 $len = strlen( $str );
2662 for ( $i = 0; $i < $len; $i++
) {
2666 # (Using the number is a performance hack for common cases)
2667 case 0: # self::COLON_STATE_TEXT:
2670 # Could be either a <start> tag or an </end> tag
2671 $state = self
::COLON_STATE_TAGSTART
;
2674 if ( $stack == 0 ) {
2676 $before = substr( $str, 0, $i );
2677 $after = substr( $str, $i +
1 );
2678 wfProfileOut( __METHOD__
);
2681 # Embedded in a tag; don't break it.
2684 # Skip ahead looking for something interesting
2685 $colon = strpos( $str, ':', $i );
2686 if ( $colon === false ) {
2687 # Nothing else interesting
2688 wfProfileOut( __METHOD__
);
2691 $lt = strpos( $str, '<', $i );
2692 if ( $stack === 0 ) {
2693 if ( $lt === false ||
$colon < $lt ) {
2695 $before = substr( $str, 0, $colon );
2696 $after = substr( $str, $colon +
1 );
2697 wfProfileOut( __METHOD__
);
2701 if ( $lt === false ) {
2702 # Nothing else interesting to find; abort!
2703 # We're nested, but there's no close tags left. Abort!
2706 # Skip ahead to next tag start
2708 $state = self
::COLON_STATE_TAGSTART
;
2711 case 1: # self::COLON_STATE_TAG:
2716 $state = self
::COLON_STATE_TEXT
;
2719 # Slash may be followed by >?
2720 $state = self
::COLON_STATE_TAGSLASH
;
2726 case 2: # self::COLON_STATE_TAGSTART:
2729 $state = self
::COLON_STATE_CLOSETAG
;
2732 $state = self
::COLON_STATE_COMMENT
;
2735 # Illegal early close? This shouldn't happen D:
2736 $state = self
::COLON_STATE_TEXT
;
2739 $state = self
::COLON_STATE_TAG
;
2742 case 3: # self::COLON_STATE_CLOSETAG:
2747 wfDebug( __METHOD__
. ": Invalid input; too many close tags\n" );
2748 wfProfileOut( __METHOD__
);
2751 $state = self
::COLON_STATE_TEXT
;
2754 case self
::COLON_STATE_TAGSLASH
:
2756 # Yes, a self-closed tag <blah/>
2757 $state = self
::COLON_STATE_TEXT
;
2759 # Probably we're jumping the gun, and this is an attribute
2760 $state = self
::COLON_STATE_TAG
;
2763 case 5: # self::COLON_STATE_COMMENT:
2765 $state = self
::COLON_STATE_COMMENTDASH
;
2768 case self
::COLON_STATE_COMMENTDASH
:
2770 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2772 $state = self
::COLON_STATE_COMMENT
;
2775 case self
::COLON_STATE_COMMENTDASHDASH
:
2777 $state = self
::COLON_STATE_TEXT
;
2779 $state = self
::COLON_STATE_COMMENT
;
2783 wfProfileOut( __METHOD__
);
2784 throw new MWException( "State machine error in " . __METHOD__
);
2788 wfDebug( __METHOD__
. ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2789 wfProfileOut( __METHOD__
);
2792 wfProfileOut( __METHOD__
);
2797 * Return value of a magic variable (like PAGENAME)
2802 * @param bool|PPFrame $frame
2804 * @throws MWException
2807 public function getVariableValue( $index, $frame = false ) {
2808 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2809 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2811 if ( is_null( $this->mTitle
) ) {
2812 // If no title set, bad things are going to happen
2813 // later. Title should always be set since this
2814 // should only be called in the middle of a parse
2815 // operation (but the unit-tests do funky stuff)
2816 throw new MWException( __METHOD__
. ' Should only be '
2817 . ' called while parsing (no title set)' );
2821 * Some of these require message or data lookups and can be
2822 * expensive to check many times.
2824 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2825 if ( isset( $this->mVarCache
[$index] ) ) {
2826 return $this->mVarCache
[$index];
2830 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2831 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2833 $pageLang = $this->getFunctionLang();
2839 case 'currentmonth':
2840 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ) );
2842 case 'currentmonth1':
2843 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2845 case 'currentmonthname':
2846 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2848 case 'currentmonthnamegen':
2849 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2851 case 'currentmonthabbrev':
2852 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2855 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ) );
2858 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ) );
2861 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ) );
2864 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2866 case 'localmonthname':
2867 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2869 case 'localmonthnamegen':
2870 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2872 case 'localmonthabbrev':
2873 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2876 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ) );
2879 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ) );
2882 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2885 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2887 case 'fullpagename':
2888 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2890 case 'fullpagenamee':
2891 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2894 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2896 case 'subpagenamee':
2897 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2899 case 'rootpagename':
2900 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2902 case 'rootpagenamee':
2903 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
2906 $this->mTitle
->getRootText()
2909 case 'basepagename':
2910 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2912 case 'basepagenamee':
2913 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
2916 $this->mTitle
->getBaseText()
2919 case 'talkpagename':
2920 if ( $this->mTitle
->canTalk() ) {
2921 $talkPage = $this->mTitle
->getTalkPage();
2922 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2927 case 'talkpagenamee':
2928 if ( $this->mTitle
->canTalk() ) {
2929 $talkPage = $this->mTitle
->getTalkPage();
2930 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
2935 case 'subjectpagename':
2936 $subjPage = $this->mTitle
->getSubjectPage();
2937 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2939 case 'subjectpagenamee':
2940 $subjPage = $this->mTitle
->getSubjectPage();
2941 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
2943 case 'pageid': // requested in bug 23427
2944 $pageid = $this->getTitle()->getArticleID();
2945 if ( $pageid == 0 ) {
2946 # 0 means the page doesn't exist in the database,
2947 # which means the user is previewing a new page.
2948 # The vary-revision flag must be set, because the magic word
2949 # will have a different value once the page is saved.
2950 $this->mOutput
->setFlag( 'vary-revision' );
2951 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2953 $value = $pageid ?
$pageid : null;
2956 # Let the edit saving system know we should parse the page
2957 # *after* a revision ID has been assigned.
2958 $this->mOutput
->setFlag( 'vary-revision' );
2959 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2960 $value = $this->mRevisionId
;
2963 # Let the edit saving system know we should parse the page
2964 # *after* a revision ID has been assigned. This is for null edits.
2965 $this->mOutput
->setFlag( 'vary-revision' );
2966 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2967 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2969 case 'revisionday2':
2970 # Let the edit saving system know we should parse the page
2971 # *after* a revision ID has been assigned. This is for null edits.
2972 $this->mOutput
->setFlag( 'vary-revision' );
2973 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2974 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2976 case 'revisionmonth':
2977 # Let the edit saving system know we should parse the page
2978 # *after* a revision ID has been assigned. This is for null edits.
2979 $this->mOutput
->setFlag( 'vary-revision' );
2980 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2981 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2983 case 'revisionmonth1':
2984 # Let the edit saving system know we should parse the page
2985 # *after* a revision ID has been assigned. This is for null edits.
2986 $this->mOutput
->setFlag( 'vary-revision' );
2987 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2988 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2990 case 'revisionyear':
2991 # Let the edit saving system know we should parse the page
2992 # *after* a revision ID has been assigned. This is for null edits.
2993 $this->mOutput
->setFlag( 'vary-revision' );
2994 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2995 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2997 case 'revisiontimestamp':
2998 # Let the edit saving system know we should parse the page
2999 # *after* a revision ID has been assigned. This is for null edits.
3000 $this->mOutput
->setFlag( 'vary-revision' );
3001 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
3002 $value = $this->getRevisionTimestamp();
3004 case 'revisionuser':
3005 # Let the edit saving system know we should parse the page
3006 # *after* a revision ID has been assigned. This is for null edits.
3007 $this->mOutput
->setFlag( 'vary-revision' );
3008 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
3009 $value = $this->getRevisionUser();
3011 case 'revisionsize':
3012 # Let the edit saving system know we should parse the page
3013 # *after* a revision ID has been assigned. This is for null edits.
3014 $this->mOutput
->setFlag( 'vary-revision' );
3015 wfDebug( __METHOD__
. ": {{REVISIONSIZE}} used, setting vary-revision...\n" );
3016 $value = $this->getRevisionSize();
3019 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3022 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3024 case 'namespacenumber':
3025 $value = $this->mTitle
->getNamespace();
3028 $value = $this->mTitle
->canTalk()
3029 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
3033 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
3035 case 'subjectspace':
3036 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
3038 case 'subjectspacee':
3039 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
3041 case 'currentdayname':
3042 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
3045 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
3048 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
3051 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
3054 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3055 # int to remove the padding
3056 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
3059 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
3061 case 'localdayname':
3062 $value = $pageLang->getWeekdayName(
3063 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
3067 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
3070 $value = $pageLang->time(
3071 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
3077 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
3080 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3081 # int to remove the padding
3082 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
3085 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
3087 case 'numberofarticles':
3088 $value = $pageLang->formatNum( SiteStats
::articles() );
3090 case 'numberoffiles':
3091 $value = $pageLang->formatNum( SiteStats
::images() );
3093 case 'numberofusers':
3094 $value = $pageLang->formatNum( SiteStats
::users() );
3096 case 'numberofactiveusers':
3097 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
3099 case 'numberofpages':
3100 $value = $pageLang->formatNum( SiteStats
::pages() );
3102 case 'numberofadmins':
3103 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
3105 case 'numberofedits':
3106 $value = $pageLang->formatNum( SiteStats
::edits() );
3108 case 'numberofviews':
3109 global $wgDisableCounters;
3110 $value = !$wgDisableCounters ?
$pageLang->formatNum( SiteStats
::views() ) : '';
3112 case 'currenttimestamp':
3113 $value = wfTimestamp( TS_MW
, $ts );
3115 case 'localtimestamp':
3116 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
3118 case 'currentversion':
3119 $value = SpecialVersion
::getVersion();
3122 return $wgArticlePath;
3128 return $wgServerName;
3130 return $wgScriptPath;
3132 return $wgStylePath;
3133 case 'directionmark':
3134 return $pageLang->getDirMark();
3135 case 'contentlanguage':
3136 global $wgLanguageCode;
3137 return $wgLanguageCode;
3138 case 'cascadingsources':
3139 $value = CoreParserFunctions
::cascadingsources( $this );
3144 'ParserGetVariableValueSwitch',
3145 array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame )
3152 $this->mVarCache
[$index] = $value;
3159 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3163 public function initialiseVariables() {
3164 wfProfileIn( __METHOD__
);
3165 $variableIDs = MagicWord
::getVariableIDs();
3166 $substIDs = MagicWord
::getSubstIDs();
3168 $this->mVariables
= new MagicWordArray( $variableIDs );
3169 $this->mSubstWords
= new MagicWordArray( $substIDs );
3170 wfProfileOut( __METHOD__
);
3174 * Preprocess some wikitext and return the document tree.
3175 * This is the ghost of replace_variables().
3177 * @param string $text The text to parse
3178 * @param int $flags Bitwise combination of:
3179 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
3180 * included. Default is to assume a direct page view.
3182 * The generated DOM tree must depend only on the input text and the flags.
3183 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3185 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3186 * change in the DOM tree for a given text, must be passed through the section identifier
3187 * in the section edit link and thus back to extractSections().
3189 * The output of this function is currently only cached in process memory, but a persistent
3190 * cache may be implemented at a later date which takes further advantage of these strict
3191 * dependency requirements.
3195 public function preprocessToDom( $text, $flags = 0 ) {
3196 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3201 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3207 public static function splitWhitespace( $s ) {
3208 $ltrimmed = ltrim( $s );
3209 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3210 $trimmed = rtrim( $ltrimmed );
3211 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3213 $w2 = substr( $ltrimmed, -$diff );
3217 return array( $w1, $trimmed, $w2 );
3221 * Replace magic variables, templates, and template arguments
3222 * with the appropriate text. Templates are substituted recursively,
3223 * taking care to avoid infinite loops.
3225 * Note that the substitution depends on value of $mOutputType:
3226 * self::OT_WIKI: only {{subst:}} templates
3227 * self::OT_PREPROCESS: templates but not extension tags
3228 * self::OT_HTML: all templates and extension tags
3230 * @param string $text The text to transform
3231 * @param bool|PPFrame $frame Object describing the arguments passed to the
3232 * template. Arguments may also be provided as an associative array, as
3233 * was the usual case before MW1.12. Providing arguments this way may be
3234 * useful for extensions wishing to perform variable replacement
3236 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3237 * double-brace expansion.
3240 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3241 # Is there any text? Also, Prevent too big inclusions!
3242 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3245 wfProfileIn( __METHOD__
);
3247 if ( $frame === false ) {
3248 $frame = $this->getPreprocessor()->newFrame();
3249 } elseif ( !( $frame instanceof PPFrame
) ) {
3250 wfDebug( __METHOD__
. " called using plain parameters instead of "
3251 . "a PPFrame instance. Creating custom frame.\n" );
3252 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3255 $dom = $this->preprocessToDom( $text );
3256 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3257 $text = $frame->expand( $dom, $flags );
3259 wfProfileOut( __METHOD__
);
3264 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3266 * @param array $args
3270 public static function createAssocArgs( $args ) {
3271 $assocArgs = array();
3273 foreach ( $args as $arg ) {
3274 $eqpos = strpos( $arg, '=' );
3275 if ( $eqpos === false ) {
3276 $assocArgs[$index++
] = $arg;
3278 $name = trim( substr( $arg, 0, $eqpos ) );
3279 $value = trim( substr( $arg, $eqpos +
1 ) );
3280 if ( $value === false ) {
3283 if ( $name !== false ) {
3284 $assocArgs[$name] = $value;
3293 * Warn the user when a parser limitation is reached
3294 * Will warn at most once the user per limitation type
3296 * @param string $limitationType Should be one of:
3297 * 'expensive-parserfunction' (corresponding messages:
3298 * 'expensive-parserfunction-warning',
3299 * 'expensive-parserfunction-category')
3300 * 'post-expand-template-argument' (corresponding messages:
3301 * 'post-expand-template-argument-warning',
3302 * 'post-expand-template-argument-category')
3303 * 'post-expand-template-inclusion' (corresponding messages:
3304 * 'post-expand-template-inclusion-warning',
3305 * 'post-expand-template-inclusion-category')
3306 * 'node-count-exceeded' (corresponding messages:
3307 * 'node-count-exceeded-warning',
3308 * 'node-count-exceeded-category')
3309 * 'expansion-depth-exceeded' (corresponding messages:
3310 * 'expansion-depth-exceeded-warning',
3311 * 'expansion-depth-exceeded-category')
3312 * @param string|int|null $current Current value
3313 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3314 * exceeded, provide the values (optional)
3316 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3317 # does no harm if $current and $max are present but are unnecessary for the message
3318 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3319 ->inLanguage( $this->mOptions
->getUserLangObj() )->text();
3320 $this->mOutput
->addWarning( $warning );
3321 $this->addTrackingCategory( "$limitationType-category" );
3325 * Return the text of a template, after recursively
3326 * replacing any variables or templates within the template.
3328 * @param array $piece The parts of the template
3329 * $piece['title']: the title, i.e. the part before the |
3330 * $piece['parts']: the parameter array
3331 * $piece['lineStart']: whether the brace was at the start of a line
3332 * @param PPFrame $frame The current frame, contains template arguments
3334 * @return string The text of the template
3336 public function braceSubstitution( $piece, $frame ) {
3337 wfProfileIn( __METHOD__
);
3338 wfProfileIn( __METHOD__
. '-setup' );
3342 // $text has been filled
3344 // wiki markup in $text should be escaped
3346 // $text is HTML, armour it against wikitext transformation
3348 // Force interwiki transclusion to be done in raw mode not rendered
3349 $forceRawInterwiki = false;
3350 // $text is a DOM node needing expansion in a child frame
3351 $isChildObj = false;
3352 // $text is a DOM node needing expansion in the current frame
3353 $isLocalObj = false;
3355 # Title object, where $text came from
3358 # $part1 is the bit before the first |, and must contain only title characters.
3359 # Various prefixes will be stripped from it later.
3360 $titleWithSpaces = $frame->expand( $piece['title'] );
3361 $part1 = trim( $titleWithSpaces );
3364 # Original title text preserved for various purposes
3365 $originalTitle = $part1;
3367 # $args is a list of argument nodes, starting from index 0, not including $part1
3368 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3369 # below won't work b/c this $args isn't an object
3370 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3371 wfProfileOut( __METHOD__
. '-setup' );
3373 $titleProfileIn = null; // profile templates
3376 wfProfileIn( __METHOD__
. '-modifiers' );
3379 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3381 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3382 # Decide whether to expand template or keep wikitext as-is.
3383 if ( $this->ot
['wiki'] ) {
3384 if ( $substMatch === false ) {
3385 $literal = true; # literal when in PST with no prefix
3387 $literal = false; # expand when in PST with subst: or safesubst:
3390 if ( $substMatch == 'subst' ) {
3391 $literal = true; # literal when not in PST with plain subst:
3393 $literal = false; # expand when not in PST with safesubst: or no prefix
3397 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3404 if ( !$found && $args->getLength() == 0 ) {
3405 $id = $this->mVariables
->matchStartToEnd( $part1 );
3406 if ( $id !== false ) {
3407 $text = $this->getVariableValue( $id, $frame );
3408 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3409 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3415 # MSG, MSGNW and RAW
3418 $mwMsgnw = MagicWord
::get( 'msgnw' );
3419 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3422 # Remove obsolete MSG:
3423 $mwMsg = MagicWord
::get( 'msg' );
3424 $mwMsg->matchStartAndRemove( $part1 );
3428 $mwRaw = MagicWord
::get( 'raw' );
3429 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3430 $forceRawInterwiki = true;
3433 wfProfileOut( __METHOD__
. '-modifiers' );
3437 wfProfileIn( __METHOD__
. '-pfunc' );
3439 $colonPos = strpos( $part1, ':' );
3440 if ( $colonPos !== false ) {
3441 $func = substr( $part1, 0, $colonPos );
3442 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3443 for ( $i = 0; $i < $args->getLength(); $i++
) {
3444 $funcArgs[] = $args->item( $i );
3447 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3448 } catch ( Exception
$ex ) {
3449 wfProfileOut( __METHOD__
. '-pfunc' );
3450 wfProfileOut( __METHOD__
);
3454 # The interface for parser functions allows for extracting
3455 # flags into the local scope. Extract any forwarded flags
3459 wfProfileOut( __METHOD__
. '-pfunc' );
3462 # Finish mangling title and then check for loops.
3463 # Set $title to a Title object and $titleText to the PDBK
3466 # Split the title into page and subpage
3468 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3469 if ( $part1 !== $relative ) {
3471 $ns = $this->mTitle
->getNamespace();
3473 $title = Title
::newFromText( $part1, $ns );
3475 $titleText = $title->getPrefixedText();
3476 # Check for language variants if the template is not found
3477 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3478 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3480 # Do recursion depth check
3481 $limit = $this->mOptions
->getMaxTemplateDepth();
3482 if ( $frame->depth
>= $limit ) {
3484 $text = '<span class="error">'
3485 . wfMessage( 'parser-template-recursion-depth-warning' )
3486 ->numParams( $limit )->inContentLanguage()->text()
3492 # Load from database
3493 if ( !$found && $title ) {
3494 if ( !Profiler
::instance()->isPersistent() ) {
3495 # Too many unique items can kill profiling DBs/collectors
3496 $titleProfileIn = __METHOD__
. "-title-" . $title->getPrefixedDBkey();
3497 wfProfileIn( $titleProfileIn ); // template in
3499 wfProfileIn( __METHOD__
. '-loadtpl' );
3500 if ( !$title->isExternal() ) {
3501 if ( $title->isSpecialPage()
3502 && $this->mOptions
->getAllowSpecialInclusion()
3503 && $this->ot
['html']
3505 // Pass the template arguments as URL parameters.
3506 // "uselang" will have no effect since the Language object
3507 // is forced to the one defined in ParserOptions.
3508 $pageArgs = array();
3509 $argsLength = $args->getLength();
3510 for ( $i = 0; $i < $argsLength; $i++
) {
3511 $bits = $args->item( $i )->splitArg();
3512 if ( strval( $bits['index'] ) === '' ) {
3513 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3514 $value = trim( $frame->expand( $bits['value'] ) );
3515 $pageArgs[$name] = $value;
3519 // Create a new context to execute the special page
3520 $context = new RequestContext
;
3521 $context->setTitle( $title );
3522 $context->setRequest( new FauxRequest( $pageArgs ) );
3523 $context->setUser( $this->getUser() );
3524 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3525 $ret = SpecialPageFactory
::capturePath( $title, $context );
3527 $text = $context->getOutput()->getHTML();
3528 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3531 $this->disableCache();
3533 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3534 $found = false; # access denied
3535 wfDebug( __METHOD__
. ": template inclusion denied for " .
3536 $title->getPrefixedDBkey() . "\n" );
3538 list( $text, $title ) = $this->getTemplateDom( $title );
3539 if ( $text !== false ) {
3545 # If the title is valid but undisplayable, make a link to it
3546 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3547 $text = "[[:$titleText]]";
3550 } elseif ( $title->isTrans() ) {
3551 # Interwiki transclusion
3552 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3553 $text = $this->interwikiTransclude( $title, 'render' );
3556 $text = $this->interwikiTransclude( $title, 'raw' );
3557 # Preprocess it like a template
3558 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3564 # Do infinite loop check
3565 # This has to be done after redirect resolution to avoid infinite loops via redirects
3566 if ( !$frame->loopCheck( $title ) ) {
3568 $text = '<span class="error">'
3569 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3571 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3573 wfProfileOut( __METHOD__
. '-loadtpl' );
3576 # If we haven't found text to substitute by now, we're done
3577 # Recover the source wikitext and return it
3579 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3580 if ( $titleProfileIn ) {
3581 wfProfileOut( $titleProfileIn ); // template out
3583 wfProfileOut( __METHOD__
);
3584 return array( 'object' => $text );
3587 # Expand DOM-style return values in a child frame
3588 if ( $isChildObj ) {
3589 # Clean up argument array
3590 $newFrame = $frame->newChild( $args, $title );
3593 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3594 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3595 # Expansion is eligible for the empty-frame cache
3596 $text = $newFrame->cachedExpand( $titleText, $text );
3598 # Uncached expansion
3599 $text = $newFrame->expand( $text );
3602 if ( $isLocalObj && $nowiki ) {
3603 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3604 $isLocalObj = false;
3607 if ( $titleProfileIn ) {
3608 wfProfileOut( $titleProfileIn ); // template out
3611 # Replace raw HTML by a placeholder
3613 $text = $this->insertStripItem( $text );
3614 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3615 # Escape nowiki-style return values
3616 $text = wfEscapeWikiText( $text );
3617 } elseif ( is_string( $text )
3618 && !$piece['lineStart']
3619 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3621 # Bug 529: if the template begins with a table or block-level
3622 # element, it should be treated as beginning a new line.
3623 # This behavior is somewhat controversial.
3624 $text = "\n" . $text;
3627 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3628 # Error, oversize inclusion
3629 if ( $titleText !== false ) {
3630 # Make a working, properly escaped link if possible (bug 23588)
3631 $text = "[[:$titleText]]";
3633 # This will probably not be a working link, but at least it may
3634 # provide some hint of where the problem is
3635 preg_replace( '/^:/', '', $originalTitle );
3636 $text = "[[:$originalTitle]]";
3638 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3639 . 'post-expand include size too large -->' );
3640 $this->limitationWarn( 'post-expand-template-inclusion' );
3643 if ( $isLocalObj ) {
3644 $ret = array( 'object' => $text );
3646 $ret = array( 'text' => $text );
3649 wfProfileOut( __METHOD__
);
3654 * Call a parser function and return an array with text and flags.
3656 * The returned array will always contain a boolean 'found', indicating
3657 * whether the parser function was found or not. It may also contain the
3659 * text: string|object, resulting wikitext or PP DOM object
3660 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3661 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3662 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3663 * nowiki: bool, wiki markup in $text should be escaped
3666 * @param PPFrame $frame The current frame, contains template arguments
3667 * @param string $function Function name
3668 * @param array $args Arguments to the function
3669 * @throws MWException
3672 public function callParserFunction( $frame, $function, array $args = array() ) {
3675 wfProfileIn( __METHOD__
);
3677 # Case sensitive functions
3678 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3679 $function = $this->mFunctionSynonyms
[1][$function];
3681 # Case insensitive functions
3682 $function = $wgContLang->lc( $function );
3683 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3684 $function = $this->mFunctionSynonyms
[0][$function];
3686 wfProfileOut( __METHOD__
);
3687 return array( 'found' => false );
3691 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3692 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3694 # Workaround for PHP bug 35229 and similar
3695 if ( !is_callable( $callback ) ) {
3696 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3697 wfProfileOut( __METHOD__
);
3698 throw new MWException( "Tag hook for $function is not callable\n" );
3701 $allArgs = array( &$this );
3702 if ( $flags & SFH_OBJECT_ARGS
) {
3703 # Convert arguments to PPNodes and collect for appending to $allArgs
3704 $funcArgs = array();
3705 foreach ( $args as $k => $v ) {
3706 if ( $v instanceof PPNode ||
$k === 0 ) {
3709 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( array( $k => $v ) )->item( 0 );
3713 # Add a frame parameter, and pass the arguments as an array
3714 $allArgs[] = $frame;
3715 $allArgs[] = $funcArgs;
3717 # Convert arguments to plain text and append to $allArgs
3718 foreach ( $args as $k => $v ) {
3719 if ( $v instanceof PPNode
) {
3720 $allArgs[] = trim( $frame->expand( $v ) );
3721 } elseif ( is_int( $k ) && $k >= 0 ) {
3722 $allArgs[] = trim( $v );
3724 $allArgs[] = trim( "$k=$v" );
3729 $result = call_user_func_array( $callback, $allArgs );
3731 # The interface for function hooks allows them to return a wikitext
3732 # string or an array containing the string and any flags. This mungs
3733 # things around to match what this method should return.
3734 if ( !is_array( $result ) ) {
3740 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3741 $result['text'] = $result[0];
3743 unset( $result[0] );
3750 $preprocessFlags = 0;
3751 if ( isset( $result['noparse'] ) ) {
3752 $noparse = $result['noparse'];
3754 if ( isset( $result['preprocessFlags'] ) ) {
3755 $preprocessFlags = $result['preprocessFlags'];
3759 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3760 $result['isChildObj'] = true;
3762 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3763 wfProfileOut( __METHOD__
);
3769 * Get the semi-parsed DOM representation of a template with a given title,
3770 * and its redirect destination title. Cached.
3772 * @param Title $title
3776 public function getTemplateDom( $title ) {
3777 $cacheTitle = $title;
3778 $titleText = $title->getPrefixedDBkey();
3780 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3781 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3782 $title = Title
::makeTitle( $ns, $dbk );
3783 $titleText = $title->getPrefixedDBkey();
3785 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3786 return array( $this->mTplDomCache
[$titleText], $title );
3789 # Cache miss, go to the database
3790 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3792 if ( $text === false ) {
3793 $this->mTplDomCache
[$titleText] = false;
3794 return array( false, $title );
3797 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3798 $this->mTplDomCache
[$titleText] = $dom;
3800 if ( !$title->equals( $cacheTitle ) ) {
3801 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3802 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3805 return array( $dom, $title );
3809 * Fetch the current revision of a given title. Note that the revision
3810 * (and even the title) may not exist in the database, so everything
3811 * contributing to the output of the parser should use this method
3812 * where possible, rather than getting the revisions themselves. This
3813 * method also caches its results, so using it benefits performance.
3816 * @param Title $title
3819 public function fetchCurrentRevisionOfTitle( $title ) {
3820 $cacheKey = $title->getPrefixedDBkey();
3821 if ( !$this->currentRevisionCache
) {
3822 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3824 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3825 $this->currentRevisionCache
->set( $cacheKey,
3826 // Defaults to Parser::statelessFetchRevision()
3827 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3830 return $this->currentRevisionCache
->get( $cacheKey );
3834 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3835 * without passing them on to it.
3838 * @param Title $title
3839 * @param Parser|bool $parser
3842 public static function statelessFetchRevision( $title, $parser = false ) {
3843 return Revision
::newFromTitle( $title );
3847 * Fetch the unparsed text of a template and register a reference to it.
3848 * @param Title $title
3849 * @return array ( string or false, Title )
3851 public function fetchTemplateAndTitle( $title ) {
3852 // Defaults to Parser::statelessFetchTemplate()
3853 $templateCb = $this->mOptions
->getTemplateCallback();
3854 $stuff = call_user_func( $templateCb, $title, $this );
3855 $text = $stuff['text'];
3856 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3857 if ( isset( $stuff['deps'] ) ) {
3858 foreach ( $stuff['deps'] as $dep ) {
3859 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3860 if ( $dep['title']->equals( $this->getTitle() ) ) {
3861 // If we transclude ourselves, the final result
3862 // will change based on the new version of the page
3863 $this->mOutput
->setFlag( 'vary-revision' );
3867 return array( $text, $finalTitle );
3871 * Fetch the unparsed text of a template and register a reference to it.
3872 * @param Title $title
3873 * @return string|bool
3875 public function fetchTemplate( $title ) {
3876 $rv = $this->fetchTemplateAndTitle( $title );
3881 * Static function to get a template
3882 * Can be overridden via ParserOptions::setTemplateCallback().
3884 * @param Title $title
3885 * @param bool|Parser $parser
3889 public static function statelessFetchTemplate( $title, $parser = false ) {
3890 $text = $skip = false;
3891 $finalTitle = $title;
3894 # Loop to fetch the article, with up to 1 redirect
3895 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3896 # Give extensions a chance to select the revision instead
3897 $id = false; # Assume current
3898 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3899 array( $parser, $title, &$skip, &$id ) );
3905 'page_id' => $title->getArticleID(),
3912 $rev = Revision
::newFromId( $id );
3913 } elseif ( $parser ) {
3914 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
3916 $rev = Revision
::newFromTitle( $title );
3918 $rev_id = $rev ?
$rev->getId() : 0;
3919 # If there is no current revision, there is no page
3920 if ( $id === false && !$rev ) {
3921 $linkCache = LinkCache
::singleton();
3922 $linkCache->addBadLinkObj( $title );
3927 'page_id' => $title->getArticleID(),
3928 'rev_id' => $rev_id );
3929 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3930 # We fetched a rev from a different title; register it too...
3932 'title' => $rev->getTitle(),
3933 'page_id' => $rev->getPage(),
3934 'rev_id' => $rev_id );
3938 $content = $rev->getContent();
3939 $text = $content ?
$content->getWikitextForTransclusion() : null;
3941 if ( $text === false ||
$text === null ) {
3945 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3947 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3948 if ( !$message->exists() ) {
3952 $content = $message->content();
3953 $text = $message->plain();
3961 $finalTitle = $title;
3962 $title = $content->getRedirectTarget();
3966 'finalTitle' => $finalTitle,
3971 * Fetch a file and its title and register a reference to it.
3972 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3973 * @param Title $title
3974 * @param array $options Array of options to RepoGroup::findFile
3977 public function fetchFile( $title, $options = array() ) {
3978 $res = $this->fetchFileAndTitle( $title, $options );
3983 * Fetch a file and its title and register a reference to it.
3984 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3985 * @param Title $title
3986 * @param array $options Array of options to RepoGroup::findFile
3987 * @return array ( File or false, Title of file )
3989 public function fetchFileAndTitle( $title, $options = array() ) {
3990 $file = $this->fetchFileNoRegister( $title, $options );
3992 $time = $file ?
$file->getTimestamp() : false;
3993 $sha1 = $file ?
$file->getSha1() : false;
3994 # Register the file as a dependency...
3995 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3996 if ( $file && !$title->equals( $file->getTitle() ) ) {
3997 # Update fetched file title
3998 $title = $file->getTitle();
3999 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4001 return array( $file, $title );
4005 * Helper function for fetchFileAndTitle.
4007 * Also useful if you need to fetch a file but not use it yet,
4008 * for example to get the file's handler.
4010 * @param Title $title
4011 * @param array $options Array of options to RepoGroup::findFile
4014 protected function fetchFileNoRegister( $title, $options = array() ) {
4015 if ( isset( $options['broken'] ) ) {
4016 $file = false; // broken thumbnail forced by hook
4017 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
4018 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
4019 } else { // get by (name,timestamp)
4020 $file = wfFindFile( $title, $options );
4026 * Transclude an interwiki link.
4028 * @param Title $title
4029 * @param string $action
4033 public function interwikiTransclude( $title, $action ) {
4034 global $wgEnableScaryTranscluding;
4036 if ( !$wgEnableScaryTranscluding ) {
4037 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
4040 $url = $title->getFullURL( array( 'action' => $action ) );
4042 if ( strlen( $url ) > 255 ) {
4043 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
4045 return $this->fetchScaryTemplateMaybeFromCache( $url );
4049 * @param string $url
4050 * @return mixed|string
4052 public function fetchScaryTemplateMaybeFromCache( $url ) {
4053 global $wgTranscludeCacheExpiry;
4054 $dbr = wfGetDB( DB_SLAVE
);
4055 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
4056 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
4057 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
4059 return $obj->tc_contents
;
4062 $req = MWHttpRequest
::factory( $url );
4063 $status = $req->execute(); // Status object
4064 if ( $status->isOK() ) {
4065 $text = $req->getContent();
4066 } elseif ( $req->getStatus() != 200 ) {
4067 // Though we failed to fetch the content, this status is useless.
4068 return wfMessage( 'scarytranscludefailed-httpstatus' )
4069 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
4071 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
4074 $dbw = wfGetDB( DB_MASTER
);
4075 $dbw->replace( 'transcache', array( 'tc_url' ), array(
4077 'tc_time' => $dbw->timestamp( time() ),
4078 'tc_contents' => $text
4084 * Triple brace replacement -- used for template arguments
4087 * @param array $piece
4088 * @param PPFrame $frame
4092 public function argSubstitution( $piece, $frame ) {
4093 wfProfileIn( __METHOD__
);
4096 $parts = $piece['parts'];
4097 $nameWithSpaces = $frame->expand( $piece['title'] );
4098 $argName = trim( $nameWithSpaces );
4100 $text = $frame->getArgument( $argName );
4101 if ( $text === false && $parts->getLength() > 0
4102 && ( $this->ot
['html']
4104 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
4107 # No match in frame, use the supplied default
4108 $object = $parts->item( 0 )->getChildren();
4110 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
4111 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
4112 $this->limitationWarn( 'post-expand-template-argument' );
4115 if ( $text === false && $object === false ) {
4117 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
4119 if ( $error !== false ) {
4122 if ( $object !== false ) {
4123 $ret = array( 'object' => $object );
4125 $ret = array( 'text' => $text );
4128 wfProfileOut( __METHOD__
);
4133 * Return the text to be used for a given extension tag.
4134 * This is the ghost of strip().
4136 * @param array $params Associative array of parameters:
4137 * name PPNode for the tag name
4138 * attr PPNode for unparsed text where tag attributes are thought to be
4139 * attributes Optional associative array of parsed attributes
4140 * inner Contents of extension element
4141 * noClose Original text did not have a close tag
4142 * @param PPFrame $frame
4144 * @throws MWException
4147 public function extensionSubstitution( $params, $frame ) {
4148 $name = $frame->expand( $params['name'] );
4149 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
4150 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
4151 $marker = "{$this->mUniqPrefix}-$name-"
4152 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
4154 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
4155 ( $this->ot
['html'] ||
$this->ot
['pre'] );
4156 if ( $isFunctionTag ) {
4157 $markerType = 'none';
4159 $markerType = 'general';
4161 if ( $this->ot
['html'] ||
$isFunctionTag ) {
4162 $name = strtolower( $name );
4163 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
4164 if ( isset( $params['attributes'] ) ) {
4165 $attributes = $attributes +
$params['attributes'];
4168 if ( isset( $this->mTagHooks
[$name] ) ) {
4169 # Workaround for PHP bug 35229 and similar
4170 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
4171 throw new MWException( "Tag hook for $name is not callable\n" );
4173 $output = call_user_func_array( $this->mTagHooks
[$name],
4174 array( $content, $attributes, $this, $frame ) );
4175 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
4176 list( $callback, ) = $this->mFunctionTagHooks
[$name];
4177 if ( !is_callable( $callback ) ) {
4178 throw new MWException( "Tag hook for $name is not callable\n" );
4181 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
4183 $output = '<span class="error">Invalid tag extension name: ' .
4184 htmlspecialchars( $name ) . '</span>';
4187 if ( is_array( $output ) ) {
4188 # Extract flags to local scope (to override $markerType)
4190 $output = $flags[0];
4195 if ( is_null( $attrText ) ) {
4198 if ( isset( $params['attributes'] ) ) {
4199 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4200 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4201 htmlspecialchars( $attrValue ) . '"';
4204 if ( $content === null ) {
4205 $output = "<$name$attrText/>";
4207 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4208 $output = "<$name$attrText>$content$close";
4212 if ( $markerType === 'none' ) {
4214 } elseif ( $markerType === 'nowiki' ) {
4215 $this->mStripState
->addNoWiki( $marker, $output );
4216 } elseif ( $markerType === 'general' ) {
4217 $this->mStripState
->addGeneral( $marker, $output );
4219 throw new MWException( __METHOD__
. ': invalid marker type' );
4225 * Increment an include size counter
4227 * @param string $type The type of expansion
4228 * @param int $size The size of the text
4229 * @return bool False if this inclusion would take it over the maximum, true otherwise
4231 public function incrementIncludeSize( $type, $size ) {
4232 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4235 $this->mIncludeSizes
[$type] +
= $size;
4241 * Increment the expensive function count
4243 * @return bool False if the limit has been exceeded
4245 public function incrementExpensiveFunctionCount() {
4246 $this->mExpensiveFunctionCount++
;
4247 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4251 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4252 * Fills $this->mDoubleUnderscores, returns the modified text
4254 * @param string $text
4258 public function doDoubleUnderscore( $text ) {
4259 wfProfileIn( __METHOD__
);
4261 # The position of __TOC__ needs to be recorded
4262 $mw = MagicWord
::get( 'toc' );
4263 if ( $mw->match( $text ) ) {
4264 $this->mShowToc
= true;
4265 $this->mForceTocPosition
= true;
4267 # Set a placeholder. At the end we'll fill it in with the TOC.
4268 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4270 # Only keep the first one.
4271 $text = $mw->replace( '', $text );
4274 # Now match and remove the rest of them
4275 $mwa = MagicWord
::getDoubleUnderscoreArray();
4276 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4278 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4279 $this->mOutput
->mNoGallery
= true;
4281 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4282 $this->mShowToc
= false;
4284 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4285 && $this->mTitle
->getNamespace() == NS_CATEGORY
4287 $this->addTrackingCategory( 'hidden-category-category' );
4289 # (bug 8068) Allow control over whether robots index a page.
4291 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4292 # is not desirable, the last one on the page should win.
4293 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4294 $this->mOutput
->setIndexPolicy( 'noindex' );
4295 $this->addTrackingCategory( 'noindex-category' );
4297 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4298 $this->mOutput
->setIndexPolicy( 'index' );
4299 $this->addTrackingCategory( 'index-category' );
4302 # Cache all double underscores in the database
4303 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4304 $this->mOutput
->setProperty( $key, '' );
4307 wfProfileOut( __METHOD__
);
4312 * Add a tracking category, getting the title from a system message,
4313 * or print a debug message if the title is invalid.
4315 * Please add any message that you use with this function to
4316 * $wgTrackingCategories. That way they will be listed on
4317 * Special:TrackingCategories.
4319 * @param string $msg Message key
4320 * @return bool Whether the addition was successful
4322 public function addTrackingCategory( $msg ) {
4323 if ( $this->mTitle
->getNamespace() === NS_SPECIAL
) {
4324 wfDebug( __METHOD__
. ": Not adding tracking category $msg to special page!\n" );
4327 // Important to parse with correct title (bug 31469)
4328 $cat = wfMessage( $msg )
4329 ->title( $this->getTitle() )
4330 ->inContentLanguage()
4333 # Allow tracking categories to be disabled by setting them to "-"
4334 if ( $cat === '-' ) {
4338 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
4339 if ( $containerCategory ) {
4340 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
4343 wfDebug( __METHOD__
. ": [[MediaWiki:$msg]] is not a valid title!\n" );
4349 * This function accomplishes several tasks:
4350 * 1) Auto-number headings if that option is enabled
4351 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4352 * 3) Add a Table of contents on the top for users who have enabled the option
4353 * 4) Auto-anchor headings
4355 * It loops through all headlines, collects the necessary data, then splits up the
4356 * string and re-inserts the newly formatted headlines.
4358 * @param string $text
4359 * @param string $origText Original, untouched wikitext
4360 * @param bool $isMain
4361 * @return mixed|string
4364 public function formatHeadings( $text, $origText, $isMain = true ) {
4365 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4367 # Inhibit editsection links if requested in the page
4368 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4369 $maybeShowEditLink = $showEditLink = false;
4371 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4372 $showEditLink = $this->mOptions
->getEditSection();
4374 if ( $showEditLink ) {
4375 $this->mOutput
->setEditSectionTokens( true );
4378 # Get all headlines for numbering them and adding funky stuff like [edit]
4379 # links - this is for later, but we need the number of headlines right now
4381 $numMatches = preg_match_all(
4382 '/<H(?P<level>[1-6])(?P<attrib>.*?' . '>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i',
4387 # if there are fewer than 4 headlines in the article, do not show TOC
4388 # unless it's been explicitly enabled.
4389 $enoughToc = $this->mShowToc
&&
4390 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4392 # Allow user to stipulate that a page should have a "new section"
4393 # link added via __NEWSECTIONLINK__
4394 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4395 $this->mOutput
->setNewSection( true );
4398 # Allow user to remove the "new section"
4399 # link via __NONEWSECTIONLINK__
4400 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4401 $this->mOutput
->hideNewSection( true );
4404 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4405 # override above conditions and always show TOC above first header
4406 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4407 $this->mShowToc
= true;
4415 # Ugh .. the TOC should have neat indentation levels which can be
4416 # passed to the skin functions. These are determined here
4420 $sublevelCount = array();
4421 $levelCount = array();
4426 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4427 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4428 $oldType = $this->mOutputType
;
4429 $this->setOutputType( self
::OT_WIKI
);
4430 $frame = $this->getPreprocessor()->newFrame();
4431 $root = $this->preprocessToDom( $origText );
4432 $node = $root->getFirstChild();
4437 foreach ( $matches[3] as $headline ) {
4438 $isTemplate = false;
4440 $sectionIndex = false;
4442 $markerMatches = array();
4443 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4444 $serial = $markerMatches[1];
4445 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4446 $isTemplate = ( $titleText != $baseTitleText );
4447 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4451 $prevlevel = $level;
4453 $level = $matches[1][$headlineCount];
4455 if ( $level > $prevlevel ) {
4456 # Increase TOC level
4458 $sublevelCount[$toclevel] = 0;
4459 if ( $toclevel < $wgMaxTocLevel ) {
4460 $prevtoclevel = $toclevel;
4461 $toc .= Linker
::tocIndent();
4464 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4465 # Decrease TOC level, find level to jump to
4467 for ( $i = $toclevel; $i > 0; $i-- ) {
4468 if ( $levelCount[$i] == $level ) {
4469 # Found last matching level
4472 } elseif ( $levelCount[$i] < $level ) {
4473 # Found first matching level below current level
4481 if ( $toclevel < $wgMaxTocLevel ) {
4482 if ( $prevtoclevel < $wgMaxTocLevel ) {
4483 # Unindent only if the previous toc level was shown :p
4484 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4485 $prevtoclevel = $toclevel;
4487 $toc .= Linker
::tocLineEnd();
4491 # No change in level, end TOC line
4492 if ( $toclevel < $wgMaxTocLevel ) {
4493 $toc .= Linker
::tocLineEnd();
4497 $levelCount[$toclevel] = $level;
4499 # count number of headlines for each level
4500 $sublevelCount[$toclevel]++
;
4502 for ( $i = 1; $i <= $toclevel; $i++
) {
4503 if ( !empty( $sublevelCount[$i] ) ) {
4507 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4512 # The safe header is a version of the header text safe to use for links
4514 # Remove link placeholders by the link text.
4515 # <!--LINK number-->
4517 # link text with suffix
4518 # Do this before unstrip since link text can contain strip markers
4519 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4521 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4522 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4524 # Strip out HTML (first regex removes any tag not allowed)
4526 # * <sup> and <sub> (bug 8393)
4529 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4531 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4532 # to allow setting directionality in toc items.
4533 $tocline = preg_replace(
4535 '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?' . '>#',
4536 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?' . '>#'
4538 array( '', '<$1>' ),
4541 $tocline = trim( $tocline );
4543 # For the anchor, strip out HTML-y stuff period
4544 $safeHeadline = preg_replace( '/<.*?' . '>/', '', $safeHeadline );
4545 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4547 # Save headline for section edit hint before it's escaped
4548 $headlineHint = $safeHeadline;
4550 if ( $wgExperimentalHtmlIds ) {
4551 # For reverse compatibility, provide an id that's
4552 # HTML4-compatible, like we used to.
4554 # It may be worth noting, academically, that it's possible for
4555 # the legacy anchor to conflict with a non-legacy headline
4556 # anchor on the page. In this case likely the "correct" thing
4557 # would be to either drop the legacy anchors or make sure
4558 # they're numbered first. However, this would require people
4559 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4560 # manually, so let's not bother worrying about it.
4561 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4562 array( 'noninitial', 'legacy' ) );
4563 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4565 if ( $legacyHeadline == $safeHeadline ) {
4566 # No reason to have both (in fact, we can't)
4567 $legacyHeadline = false;
4570 $legacyHeadline = false;
4571 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4575 # HTML names must be case-insensitively unique (bug 10721).
4576 # This does not apply to Unicode characters per
4577 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4578 # @todo FIXME: We may be changing them depending on the current locale.
4579 $arrayKey = strtolower( $safeHeadline );
4580 if ( $legacyHeadline === false ) {
4581 $legacyArrayKey = false;
4583 $legacyArrayKey = strtolower( $legacyHeadline );
4586 # count how many in assoc. array so we can track dupes in anchors
4587 if ( isset( $refers[$arrayKey] ) ) {
4588 $refers[$arrayKey]++
;
4590 $refers[$arrayKey] = 1;
4592 if ( isset( $refers[$legacyArrayKey] ) ) {
4593 $refers[$legacyArrayKey]++
;
4595 $refers[$legacyArrayKey] = 1;
4598 # Don't number the heading if it is the only one (looks silly)
4599 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4600 # the two are different if the line contains a link
4601 $headline = Html
::element(
4603 array( 'class' => 'mw-headline-number' ),
4605 ) . ' ' . $headline;
4608 # Create the anchor for linking from the TOC to the section
4609 $anchor = $safeHeadline;
4610 $legacyAnchor = $legacyHeadline;
4611 if ( $refers[$arrayKey] > 1 ) {
4612 $anchor .= '_' . $refers[$arrayKey];
4614 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4615 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4617 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4618 $toc .= Linker
::tocLine( $anchor, $tocline,
4619 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4622 # Add the section to the section tree
4623 # Find the DOM node for this header
4624 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4625 while ( $node && !$noOffset ) {
4626 if ( $node->getName() === 'h' ) {
4627 $bits = $node->splitHeading();
4628 if ( $bits['i'] == $sectionIndex ) {
4632 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4633 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4634 $node = $node->getNextSibling();
4637 'toclevel' => $toclevel,
4640 'number' => $numbering,
4641 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4642 'fromtitle' => $titleText,
4643 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4644 'anchor' => $anchor,
4647 # give headline the correct <h#> tag
4648 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4649 // Output edit section links as markers with styles that can be customized by skins
4650 if ( $isTemplate ) {
4651 # Put a T flag in the section identifier, to indicate to extractSections()
4652 # that sections inside <includeonly> should be counted.
4653 $editsectionPage = $titleText;
4654 $editsectionSection = "T-$sectionIndex";
4655 $editsectionContent = null;
4657 $editsectionPage = $this->mTitle
->getPrefixedText();
4658 $editsectionSection = $sectionIndex;
4659 $editsectionContent = $headlineHint;
4661 // We use a bit of pesudo-xml for editsection markers. The
4662 // language converter is run later on. Using a UNIQ style marker
4663 // leads to the converter screwing up the tokens when it
4664 // converts stuff. And trying to insert strip tags fails too. At
4665 // this point all real inputted tags have already been escaped,
4666 // so we don't have to worry about a user trying to input one of
4667 // these markers directly. We use a page and section attribute
4668 // to stop the language converter from converting these
4669 // important bits of data, but put the headline hint inside a
4670 // content block because the language converter is supposed to
4671 // be able to convert that piece of data.
4672 // Gets replaced with html in ParserOutput::getText
4673 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4674 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4675 if ( $editsectionContent !== null ) {
4676 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4683 $head[$headlineCount] = Linker
::makeHeadline( $level,
4684 $matches['attrib'][$headlineCount], $anchor, $headline,
4685 $editlink, $legacyAnchor );
4690 $this->setOutputType( $oldType );
4692 # Never ever show TOC if no headers
4693 if ( $numVisible < 1 ) {
4698 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4699 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4701 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4702 $this->mOutput
->setTOCHTML( $toc );
4703 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4704 $this->mOutput
->addModules( 'mediawiki.toc' );
4708 $this->mOutput
->setSections( $tocraw );
4711 # split up and insert constructed headlines
4712 $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text );
4715 // build an array of document sections
4716 $sections = array();
4717 foreach ( $blocks as $block ) {
4718 // $head is zero-based, sections aren't.
4719 if ( empty( $head[$i - 1] ) ) {
4720 $sections[$i] = $block;
4722 $sections[$i] = $head[$i - 1] . $block;
4726 * Send a hook, one per section.
4727 * The idea here is to be able to make section-level DIVs, but to do so in a
4728 * lower-impact, more correct way than r50769
4731 * $section : the section number
4732 * &$sectionContent : ref to the content of the section
4733 * $showEditLinks : boolean describing whether this section has an edit link
4735 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4740 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4741 // append the TOC at the beginning
4742 // Top anchor now in skin
4743 $sections[0] = $sections[0] . $toc . "\n";
4746 $full .= join( '', $sections );
4748 if ( $this->mForceTocPosition
) {
4749 return str_replace( '<!--MWTOC-->', $toc, $full );
4756 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4757 * conversion, substitting signatures, {{subst:}} templates, etc.
4759 * @param string $text The text to transform
4760 * @param Title $title The Title object for the current article
4761 * @param User $user The User object describing the current user
4762 * @param ParserOptions $options Parsing options
4763 * @param bool $clearState Whether to clear the parser state first
4764 * @return string The altered wiki markup
4766 public function preSaveTransform( $text, Title
$title, User
$user,
4767 ParserOptions
$options, $clearState = true
4769 if ( $clearState ) {
4770 $magicScopeVariable = $this->lock();
4772 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4773 $this->setUser( $user );
4778 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4779 if ( $options->getPreSaveTransform() ) {
4780 $text = $this->pstPass2( $text, $user );
4782 $text = $this->mStripState
->unstripBoth( $text );
4784 $this->setUser( null ); #Reset
4790 * Pre-save transform helper function
4792 * @param string $text
4797 private function pstPass2( $text, $user ) {
4800 # Note: This is the timestamp saved as hardcoded wikitext to
4801 # the database, we use $wgContLang here in order to give
4802 # everyone the same signature and use the default one rather
4803 # than the one selected in each user's preferences.
4804 # (see also bug 12815)
4805 $ts = $this->mOptions
->getTimestamp();
4806 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4807 $ts = $timestamp->format( 'YmdHis' );
4808 $tzMsg = $timestamp->format( 'T' ); # might vary on DST changeover!
4810 # Allow translation of timezones through wiki. format() can return
4811 # whatever crap the system uses, localised or not, so we cannot
4812 # ship premade translations.
4813 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4814 $msg = wfMessage( $key )->inContentLanguage();
4815 if ( $msg->exists() ) {
4816 $tzMsg = $msg->text();
4819 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4821 # Variable replacement
4822 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4823 $text = $this->replaceVariables( $text );
4825 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4826 # which may corrupt this parser instance via its wfMessage()->text() call-
4829 $sigText = $this->getUserSig( $user );
4830 $text = strtr( $text, array(
4832 '~~~~' => "$sigText $d",
4836 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4837 $tc = '[' . Title
::legalChars() . ']';
4838 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4840 // [[ns:page (context)|]]
4841 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4842 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4843 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4844 // [[ns:page (context), context|]] (using either single or double-width comma)
4845 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4846 // [[|page]] (reverse pipe trick: add context from page title)
4847 $p2 = "/\[\[\\|($tc+)]]/";
4849 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4850 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4851 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4852 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4854 $t = $this->mTitle
->getText();
4856 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4857 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4858 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4859 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4861 # if there's no context, don't bother duplicating the title
4862 $text = preg_replace( $p2, '[[\\1]]', $text );
4865 # Trim trailing whitespace
4866 $text = rtrim( $text );
4872 * Fetch the user's signature text, if any, and normalize to
4873 * validated, ready-to-insert wikitext.
4874 * If you have pre-fetched the nickname or the fancySig option, you can
4875 * specify them here to save a database query.
4876 * Do not reuse this parser instance after calling getUserSig(),
4877 * as it may have changed if it's the $wgParser.
4880 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4881 * @param bool|null $fancySig whether the nicknname is the complete signature
4882 * or null to use default value
4885 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4886 global $wgMaxSigChars;
4888 $username = $user->getName();
4890 # If not given, retrieve from the user object.
4891 if ( $nickname === false ) {
4892 $nickname = $user->getOption( 'nickname' );
4895 if ( is_null( $fancySig ) ) {
4896 $fancySig = $user->getBoolOption( 'fancysig' );
4899 $nickname = $nickname == null ?
$username : $nickname;
4901 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4902 $nickname = $username;
4903 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4904 } elseif ( $fancySig !== false ) {
4905 # Sig. might contain markup; validate this
4906 if ( $this->validateSig( $nickname ) !== false ) {
4907 # Validated; clean up (if needed) and return it
4908 return $this->cleanSig( $nickname, true );
4910 # Failed to validate; fall back to the default
4911 $nickname = $username;
4912 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4916 # Make sure nickname doesnt get a sig in a sig
4917 $nickname = self
::cleanSigInSig( $nickname );
4919 # If we're still here, make it a link to the user page
4920 $userText = wfEscapeWikiText( $username );
4921 $nickText = wfEscapeWikiText( $nickname );
4922 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4924 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4925 ->title( $this->getTitle() )->text();
4929 * Check that the user's signature contains no bad XML
4931 * @param string $text
4932 * @return string|bool An expanded string, or false if invalid.
4934 public function validateSig( $text ) {
4935 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4939 * Clean up signature text
4941 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4942 * 2) Substitute all transclusions
4944 * @param string $text
4945 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4946 * @return string Signature text
4948 public function cleanSig( $text, $parsing = false ) {
4951 $magicScopeVariable = $this->lock();
4952 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4955 # Option to disable this feature
4956 if ( !$this->mOptions
->getCleanSignatures() ) {
4960 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4961 # => Move this logic to braceSubstitution()
4962 $substWord = MagicWord
::get( 'subst' );
4963 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4964 $substText = '{{' . $substWord->getSynonym( 0 );
4966 $text = preg_replace( $substRegex, $substText, $text );
4967 $text = self
::cleanSigInSig( $text );
4968 $dom = $this->preprocessToDom( $text );
4969 $frame = $this->getPreprocessor()->newFrame();
4970 $text = $frame->expand( $dom );
4973 $text = $this->mStripState
->unstripBoth( $text );
4980 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4982 * @param string $text
4983 * @return string Signature text with /~{3,5}/ removed
4985 public static function cleanSigInSig( $text ) {
4986 $text = preg_replace( '/~{3,5}/', '', $text );
4991 * Set up some variables which are usually set up in parse()
4992 * so that an external function can call some class members with confidence
4994 * @param Title|null $title
4995 * @param ParserOptions $options
4996 * @param int $outputType
4997 * @param bool $clearState
4999 public function startExternalParse( Title
$title = null, ParserOptions
$options,
5000 $outputType, $clearState = true
5002 $this->startParse( $title, $options, $outputType, $clearState );
5006 * @param Title|null $title
5007 * @param ParserOptions $options
5008 * @param int $outputType
5009 * @param bool $clearState
5011 private function startParse( Title
$title = null, ParserOptions
$options,
5012 $outputType, $clearState = true
5014 $this->setTitle( $title );
5015 $this->mOptions
= $options;
5016 $this->setOutputType( $outputType );
5017 if ( $clearState ) {
5018 $this->clearState();
5023 * Wrapper for preprocess()
5025 * @param string $text The text to preprocess
5026 * @param ParserOptions $options Options
5027 * @param Title|null $title Title object or null to use $wgTitle
5030 public function transformMsg( $text, $options, $title = null ) {
5031 static $executing = false;
5033 # Guard against infinite recursion
5039 wfProfileIn( __METHOD__
);
5045 $text = $this->preprocess( $text, $title, $options );
5048 wfProfileOut( __METHOD__
);
5053 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
5054 * The callback should have the following form:
5055 * function myParserHook( $text, $params, $parser, $frame ) { ... }
5057 * Transform and return $text. Use $parser for any required context, e.g. use
5058 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
5060 * Hooks may return extended information by returning an array, of which the
5061 * first numbered element (index 0) must be the return string, and all other
5062 * entries are extracted into local variables within an internal function
5063 * in the Parser class.
5065 * This interface (introduced r61913) appears to be undocumented, but
5066 * 'markerName' is used by some core tag hooks to override which strip
5067 * array their results are placed in. **Use great caution if attempting
5068 * this interface, as it is not documented and injudicious use could smash
5069 * private variables.**
5071 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5072 * @param callable $callback The callback function (and object) to use for the tag
5073 * @throws MWException
5074 * @return callable|null The old value of the mTagHooks array associated with the hook
5076 public function setHook( $tag, $callback ) {
5077 $tag = strtolower( $tag );
5078 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5079 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
5081 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
5082 $this->mTagHooks
[$tag] = $callback;
5083 if ( !in_array( $tag, $this->mStripList
) ) {
5084 $this->mStripList
[] = $tag;
5091 * As setHook(), but letting the contents be parsed.
5093 * Transparent tag hooks are like regular XML-style tag hooks, except they
5094 * operate late in the transformation sequence, on HTML instead of wikitext.
5096 * This is probably obsoleted by things dealing with parser frames?
5097 * The only extension currently using it is geoserver.
5100 * @todo better document or deprecate this
5102 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5103 * @param callable $callback The callback function (and object) to use for the tag
5104 * @throws MWException
5105 * @return callable|null The old value of the mTagHooks array associated with the hook
5107 public function setTransparentTagHook( $tag, $callback ) {
5108 $tag = strtolower( $tag );
5109 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5110 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
5112 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
5113 $this->mTransparentTagHooks
[$tag] = $callback;
5119 * Remove all tag hooks
5121 public function clearTagHooks() {
5122 $this->mTagHooks
= array();
5123 $this->mFunctionTagHooks
= array();
5124 $this->mStripList
= $this->mDefaultStripList
;
5128 * Create a function, e.g. {{sum:1|2|3}}
5129 * The callback function should have the form:
5130 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
5132 * Or with SFH_OBJECT_ARGS:
5133 * function myParserFunction( $parser, $frame, $args ) { ... }
5135 * The callback may either return the text result of the function, or an array with the text
5136 * in element 0, and a number of flags in the other elements. The names of the flags are
5137 * specified in the keys. Valid flags are:
5138 * found The text returned is valid, stop processing the template. This
5140 * nowiki Wiki markup in the return value should be escaped
5141 * isHTML The returned text is HTML, armour it against wikitext transformation
5143 * @param string $id The magic word ID
5144 * @param callable $callback The callback function (and object) to use
5145 * @param int $flags A combination of the following flags:
5146 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
5148 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
5149 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
5150 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
5151 * the arguments, and to control the way they are expanded.
5153 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
5154 * arguments, for instance:
5155 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
5157 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
5158 * future versions. Please call $frame->expand() on it anyway so that your code keeps
5159 * working if/when this is changed.
5161 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
5164 * Please read the documentation in includes/parser/Preprocessor.php for more information
5165 * about the methods available in PPFrame and PPNode.
5167 * @throws MWException
5168 * @return string|callable The old callback function for this name, if any
5170 public function setFunctionHook( $id, $callback, $flags = 0 ) {
5173 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
5174 $this->mFunctionHooks
[$id] = array( $callback, $flags );
5176 # Add to function cache
5177 $mw = MagicWord
::get( $id );
5179 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
5182 $synonyms = $mw->getSynonyms();
5183 $sensitive = intval( $mw->isCaseSensitive() );
5185 foreach ( $synonyms as $syn ) {
5187 if ( !$sensitive ) {
5188 $syn = $wgContLang->lc( $syn );
5191 if ( !( $flags & SFH_NO_HASH
) ) {
5194 # Remove trailing colon
5195 if ( substr( $syn, -1, 1 ) === ':' ) {
5196 $syn = substr( $syn, 0, -1 );
5198 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
5204 * Get all registered function hook identifiers
5208 public function getFunctionHooks() {
5209 return array_keys( $this->mFunctionHooks
);
5213 * Create a tag function, e.g. "<test>some stuff</test>".
5214 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5215 * Unlike parser functions, their content is not preprocessed.
5216 * @param string $tag
5217 * @param callable $callback
5219 * @throws MWException
5222 public function setFunctionTagHook( $tag, $callback, $flags ) {
5223 $tag = strtolower( $tag );
5224 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5225 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5227 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
5228 $this->mFunctionTagHooks
[$tag] : null;
5229 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
5231 if ( !in_array( $tag, $this->mStripList
) ) {
5232 $this->mStripList
[] = $tag;
5239 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
5240 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5241 * Placeholders created in Skin::makeLinkObj()
5243 * @param string $text
5244 * @param int $options
5246 * @return array Array of link CSS classes, indexed by PDBK.
5248 public function replaceLinkHolders( &$text, $options = 0 ) {
5249 return $this->mLinkHolders
->replace( $text );
5253 * Replace "<!--LINK-->" link placeholders with plain text of links
5254 * (not HTML-formatted).
5256 * @param string $text
5259 public function replaceLinkHoldersText( $text ) {
5260 return $this->mLinkHolders
->replaceText( $text );
5264 * Renders an image gallery from a text with one line per image.
5265 * text labels may be given by using |-style alternative text. E.g.
5266 * Image:one.jpg|The number "1"
5267 * Image:tree.jpg|A tree
5268 * given as text will return the HTML of a gallery with two images,
5269 * labeled 'The number "1"' and
5272 * @param string $text
5273 * @param array $params
5274 * @return string HTML
5276 public function renderImageGallery( $text, $params ) {
5277 wfProfileIn( __METHOD__
);
5280 if ( isset( $params['mode'] ) ) {
5281 $mode = $params['mode'];
5285 $ig = ImageGalleryBase
::factory( $mode );
5286 } catch ( MWException
$e ) {
5287 // If invalid type set, fallback to default.
5288 $ig = ImageGalleryBase
::factory( false );
5291 $ig->setContextTitle( $this->mTitle
);
5292 $ig->setShowBytes( false );
5293 $ig->setShowFilename( false );
5294 $ig->setParser( $this );
5295 $ig->setHideBadImages();
5296 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
5298 if ( isset( $params['showfilename'] ) ) {
5299 $ig->setShowFilename( true );
5301 $ig->setShowFilename( false );
5303 if ( isset( $params['caption'] ) ) {
5304 $caption = $params['caption'];
5305 $caption = htmlspecialchars( $caption );
5306 $caption = $this->replaceInternalLinks( $caption );
5307 $ig->setCaptionHtml( $caption );
5309 if ( isset( $params['perrow'] ) ) {
5310 $ig->setPerRow( $params['perrow'] );
5312 if ( isset( $params['widths'] ) ) {
5313 $ig->setWidths( $params['widths'] );
5315 if ( isset( $params['heights'] ) ) {
5316 $ig->setHeights( $params['heights'] );
5318 $ig->setAdditionalOptions( $params );
5320 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5322 $lines = StringUtils
::explode( "\n", $text );
5323 foreach ( $lines as $line ) {
5324 # match lines like these:
5325 # Image:someimage.jpg|This is some image
5327 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5329 if ( count( $matches ) == 0 ) {
5333 if ( strpos( $matches[0], '%' ) !== false ) {
5334 $matches[1] = rawurldecode( $matches[1] );
5336 $title = Title
::newFromText( $matches[1], NS_FILE
);
5337 if ( is_null( $title ) ) {
5338 # Bogus title. Ignore these so we don't bomb out later.
5342 # We need to get what handler the file uses, to figure out parameters.
5343 # Note, a hook can overide the file name, and chose an entirely different
5344 # file (which potentially could be of a different type and have different handler).
5347 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5348 array( $this, $title, &$options, &$descQuery ) );
5349 # Don't register it now, as ImageGallery does that later.
5350 $file = $this->fetchFileNoRegister( $title, $options );
5351 $handler = $file ?
$file->getHandler() : false;
5353 wfProfileIn( __METHOD__
. '-getMagicWord' );
5355 'img_alt' => 'gallery-internal-alt',
5356 'img_link' => 'gallery-internal-link',
5359 $paramMap = $paramMap +
$handler->getParamMap();
5360 // We don't want people to specify per-image widths.
5361 // Additionally the width parameter would need special casing anyhow.
5362 unset( $paramMap['img_width'] );
5365 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5366 wfProfileOut( __METHOD__
. '-getMagicWord' );
5371 $handlerOptions = array();
5372 if ( isset( $matches[3] ) ) {
5373 // look for an |alt= definition while trying not to break existing
5374 // captions with multiple pipes (|) in it, until a more sensible grammar
5375 // is defined for images in galleries
5377 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5378 // splitting on '|' is a bit odd, and different from makeImage.
5379 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5380 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
5382 foreach ( $parameterMatches as $parameterMatch ) {
5383 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5385 $paramName = $paramMap[$magicName];
5387 switch ( $paramName ) {
5388 case 'gallery-internal-alt':
5389 $alt = $this->stripAltText( $match, false );
5391 case 'gallery-internal-link':
5392 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5393 $chars = self
::EXT_LINK_URL_CLASS
;
5394 $prots = $this->mUrlProtocols
;
5395 //check to see if link matches an absolute url, if not then it must be a wiki link.
5396 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5399 $localLinkTitle = Title
::newFromText( $linkValue );
5400 if ( $localLinkTitle !== null ) {
5401 $link = $localLinkTitle->getLinkURL();
5406 // Must be a handler specific parameter.
5407 if ( $handler->validateParam( $paramName, $match ) ) {
5408 $handlerOptions[$paramName] = $match;
5410 // Guess not. Append it to the caption.
5411 wfDebug( "$parameterMatch failed parameter validation\n" );
5412 $label .= '|' . $parameterMatch;
5417 // concatenate all other pipes
5418 $label .= '|' . $parameterMatch;
5421 // remove the first pipe
5422 $label = substr( $label, 1 );
5425 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5427 $html = $ig->toHTML();
5428 wfRunHooks( 'AfterParserFetchFileAndTitle', array( $this, $ig, &$html ) );
5429 wfProfileOut( __METHOD__
);
5434 * @param string $handler
5437 public function getImageParams( $handler ) {
5439 $handlerClass = get_class( $handler );
5443 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5444 # Initialise static lists
5445 static $internalParamNames = array(
5446 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5447 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5448 'bottom', 'text-bottom' ),
5449 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5450 'upright', 'border', 'link', 'alt', 'class' ),
5452 static $internalParamMap;
5453 if ( !$internalParamMap ) {
5454 $internalParamMap = array();
5455 foreach ( $internalParamNames as $type => $names ) {
5456 foreach ( $names as $name ) {
5457 $magicName = str_replace( '-', '_', "img_$name" );
5458 $internalParamMap[$magicName] = array( $type, $name );
5463 # Add handler params
5464 $paramMap = $internalParamMap;
5466 $handlerParamMap = $handler->getParamMap();
5467 foreach ( $handlerParamMap as $magic => $paramName ) {
5468 $paramMap[$magic] = array( 'handler', $paramName );
5471 $this->mImageParams
[$handlerClass] = $paramMap;
5472 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5474 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5478 * Parse image options text and use it to make an image
5480 * @param Title $title
5481 * @param string $options
5482 * @param LinkHolderArray|bool $holders
5483 * @return string HTML
5485 public function makeImage( $title, $options, $holders = false ) {
5486 # Check if the options text is of the form "options|alt text"
5488 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5489 # * left no resizing, just left align. label is used for alt= only
5490 # * right same, but right aligned
5491 # * none same, but not aligned
5492 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5493 # * center center the image
5494 # * frame Keep original image size, no magnify-button.
5495 # * framed Same as "frame"
5496 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5497 # * upright reduce width for upright images, rounded to full __0 px
5498 # * border draw a 1px border around the image
5499 # * alt Text for HTML alt attribute (defaults to empty)
5500 # * class Set a class for img node
5501 # * link Set the target of the image link. Can be external, interwiki, or local
5502 # vertical-align values (no % or length right now):
5512 $parts = StringUtils
::explode( "|", $options );
5514 # Give extensions a chance to select the file revision for us
5517 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5518 array( $this, $title, &$options, &$descQuery ) );
5519 # Fetch and register the file (file title may be different via hooks)
5520 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5523 $handler = $file ?
$file->getHandler() : false;
5525 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5528 $this->addTrackingCategory( 'broken-file-category' );
5531 # Process the input parameters
5533 $params = array( 'frame' => array(), 'handler' => array(),
5534 'horizAlign' => array(), 'vertAlign' => array() );
5535 $seenformat = false;
5536 foreach ( $parts as $part ) {
5537 $part = trim( $part );
5538 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5540 if ( isset( $paramMap[$magicName] ) ) {
5541 list( $type, $paramName ) = $paramMap[$magicName];
5543 # Special case; width and height come in one variable together
5544 if ( $type === 'handler' && $paramName === 'width' ) {
5545 $parsedWidthParam = $this->parseWidthParam( $value );
5546 if ( isset( $parsedWidthParam['width'] ) ) {
5547 $width = $parsedWidthParam['width'];
5548 if ( $handler->validateParam( 'width', $width ) ) {
5549 $params[$type]['width'] = $width;
5553 if ( isset( $parsedWidthParam['height'] ) ) {
5554 $height = $parsedWidthParam['height'];
5555 if ( $handler->validateParam( 'height', $height ) ) {
5556 $params[$type]['height'] = $height;
5560 # else no validation -- bug 13436
5562 if ( $type === 'handler' ) {
5563 # Validate handler parameter
5564 $validated = $handler->validateParam( $paramName, $value );
5566 # Validate internal parameters
5567 switch ( $paramName ) {
5571 # @todo FIXME: Possibly check validity here for
5572 # manualthumb? downstream behavior seems odd with
5573 # missing manual thumbs.
5575 $value = $this->stripAltText( $value, $holders );
5578 $chars = self
::EXT_LINK_URL_CLASS
;
5579 $prots = $this->mUrlProtocols
;
5580 if ( $value === '' ) {
5581 $paramName = 'no-link';
5584 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5585 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5586 $paramName = 'link-url';
5587 $this->mOutput
->addExternalLink( $value );
5588 if ( $this->mOptions
->getExternalLinkTarget() ) {
5589 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5594 $linkTitle = Title
::newFromText( $value );
5596 $paramName = 'link-title';
5597 $value = $linkTitle;
5598 $this->mOutput
->addLink( $linkTitle );
5606 // use first appearing option, discard others.
5607 $validated = ! $seenformat;
5611 # Most other things appear to be empty or numeric...
5612 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5617 $params[$type][$paramName] = $value;
5621 if ( !$validated ) {
5626 # Process alignment parameters
5627 if ( $params['horizAlign'] ) {
5628 $params['frame']['align'] = key( $params['horizAlign'] );
5630 if ( $params['vertAlign'] ) {
5631 $params['frame']['valign'] = key( $params['vertAlign'] );
5634 $params['frame']['caption'] = $caption;
5636 # Will the image be presented in a frame, with the caption below?
5637 $imageIsFramed = isset( $params['frame']['frame'] )
5638 ||
isset( $params['frame']['framed'] )
5639 ||
isset( $params['frame']['thumbnail'] )
5640 ||
isset( $params['frame']['manualthumb'] );
5642 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5643 # came to also set the caption, ordinary text after the image -- which
5644 # makes no sense, because that just repeats the text multiple times in
5645 # screen readers. It *also* came to set the title attribute.
5647 # Now that we have an alt attribute, we should not set the alt text to
5648 # equal the caption: that's worse than useless, it just repeats the
5649 # text. This is the framed/thumbnail case. If there's no caption, we
5650 # use the unnamed parameter for alt text as well, just for the time be-
5651 # ing, if the unnamed param is set and the alt param is not.
5653 # For the future, we need to figure out if we want to tweak this more,
5654 # e.g., introducing a title= parameter for the title; ignoring the un-
5655 # named parameter entirely for images without a caption; adding an ex-
5656 # plicit caption= parameter and preserving the old magic unnamed para-
5658 if ( $imageIsFramed ) { # Framed image
5659 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5660 # No caption or alt text, add the filename as the alt text so
5661 # that screen readers at least get some description of the image
5662 $params['frame']['alt'] = $title->getText();
5664 # Do not set $params['frame']['title'] because tooltips don't make sense
5666 } else { # Inline image
5667 if ( !isset( $params['frame']['alt'] ) ) {
5668 # No alt text, use the "caption" for the alt text
5669 if ( $caption !== '' ) {
5670 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5672 # No caption, fall back to using the filename for the
5674 $params['frame']['alt'] = $title->getText();
5677 # Use the "caption" for the tooltip text
5678 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5681 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5683 # Linker does the rest
5684 $time = isset( $options['time'] ) ?
$options['time'] : false;
5685 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5686 $time, $descQuery, $this->mOptions
->getThumbSize() );
5688 # Give the handler a chance to modify the parser object
5690 $handler->parserTransformHook( $this, $file );
5697 * @param string $caption
5698 * @param LinkHolderArray|bool $holders
5699 * @return mixed|string
5701 protected function stripAltText( $caption, $holders ) {
5702 # Strip bad stuff out of the title (tooltip). We can't just use
5703 # replaceLinkHoldersText() here, because if this function is called
5704 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5706 $tooltip = $holders->replaceText( $caption );
5708 $tooltip = $this->replaceLinkHoldersText( $caption );
5711 # make sure there are no placeholders in thumbnail attributes
5712 # that are later expanded to html- so expand them now and
5714 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5715 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5721 * Set a flag in the output object indicating that the content is dynamic and
5722 * shouldn't be cached.
5724 public function disableCache() {
5725 wfDebug( "Parser output marked as uncacheable.\n" );
5726 if ( !$this->mOutput
) {
5727 throw new MWException( __METHOD__
.
5728 " can only be called when actually parsing something" );
5730 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5731 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5735 * Callback from the Sanitizer for expanding items found in HTML attribute
5736 * values, so they can be safely tested and escaped.
5738 * @param string $text
5739 * @param bool|PPFrame $frame
5742 public function attributeStripCallback( &$text, $frame = false ) {
5743 $text = $this->replaceVariables( $text, $frame );
5744 $text = $this->mStripState
->unstripBoth( $text );
5753 public function getTags() {
5755 array_keys( $this->mTransparentTagHooks
),
5756 array_keys( $this->mTagHooks
),
5757 array_keys( $this->mFunctionTagHooks
)
5762 * Replace transparent tags in $text with the values given by the callbacks.
5764 * Transparent tag hooks are like regular XML-style tag hooks, except they
5765 * operate late in the transformation sequence, on HTML instead of wikitext.
5767 * @param string $text
5771 public function replaceTransparentTags( $text ) {
5773 $elements = array_keys( $this->mTransparentTagHooks
);
5774 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5775 $replacements = array();
5777 foreach ( $matches as $marker => $data ) {
5778 list( $element, $content, $params, $tag ) = $data;
5779 $tagName = strtolower( $element );
5780 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5781 $output = call_user_func_array(
5782 $this->mTransparentTagHooks
[$tagName],
5783 array( $content, $params, $this )
5788 $replacements[$marker] = $output;
5790 return strtr( $text, $replacements );
5794 * Break wikitext input into sections, and either pull or replace
5795 * some particular section's text.
5797 * External callers should use the getSection and replaceSection methods.
5799 * @param string $text Page wikitext
5800 * @param string|number $sectionId A section identifier string of the form:
5801 * "<flag1> - <flag2> - ... - <section number>"
5803 * Currently the only recognised flag is "T", which means the target section number
5804 * was derived during a template inclusion parse, in other words this is a template
5805 * section edit link. If no flags are given, it was an ordinary section edit link.
5806 * This flag is required to avoid a section numbering mismatch when a section is
5807 * enclosed by "<includeonly>" (bug 6563).
5809 * The section number 0 pulls the text before the first heading; other numbers will
5810 * pull the given section along with its lower-level subsections. If the section is
5811 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5813 * Section 0 is always considered to exist, even if it only contains the empty
5814 * string. If $text is the empty string and section 0 is replaced, $newText is
5817 * @param string $mode One of "get" or "replace"
5818 * @param string $newText Replacement text for section data.
5819 * @return string For "get", the extracted section text.
5820 * for "replace", the whole page with the section replaced.
5822 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5823 global $wgTitle; # not generally used but removes an ugly failure mode
5825 $magicScopeVariable = $this->lock();
5826 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5828 $frame = $this->getPreprocessor()->newFrame();
5830 # Process section extraction flags
5832 $sectionParts = explode( '-', $sectionId );
5833 $sectionIndex = array_pop( $sectionParts );
5834 foreach ( $sectionParts as $part ) {
5835 if ( $part === 'T' ) {
5836 $flags |
= self
::PTD_FOR_INCLUSION
;
5840 # Check for empty input
5841 if ( strval( $text ) === '' ) {
5842 # Only sections 0 and T-0 exist in an empty document
5843 if ( $sectionIndex == 0 ) {
5844 if ( $mode === 'get' ) {
5850 if ( $mode === 'get' ) {
5858 # Preprocess the text
5859 $root = $this->preprocessToDom( $text, $flags );
5861 # <h> nodes indicate section breaks
5862 # They can only occur at the top level, so we can find them by iterating the root's children
5863 $node = $root->getFirstChild();
5865 # Find the target section
5866 if ( $sectionIndex == 0 ) {
5867 # Section zero doesn't nest, level=big
5868 $targetLevel = 1000;
5871 if ( $node->getName() === 'h' ) {
5872 $bits = $node->splitHeading();
5873 if ( $bits['i'] == $sectionIndex ) {
5874 $targetLevel = $bits['level'];
5878 if ( $mode === 'replace' ) {
5879 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5881 $node = $node->getNextSibling();
5887 if ( $mode === 'get' ) {
5894 # Find the end of the section, including nested sections
5896 if ( $node->getName() === 'h' ) {
5897 $bits = $node->splitHeading();
5898 $curLevel = $bits['level'];
5899 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5903 if ( $mode === 'get' ) {
5904 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5906 $node = $node->getNextSibling();
5909 # Write out the remainder (in replace mode only)
5910 if ( $mode === 'replace' ) {
5911 # Output the replacement text
5912 # Add two newlines on -- trailing whitespace in $newText is conventionally
5913 # stripped by the editor, so we need both newlines to restore the paragraph gap
5914 # Only add trailing whitespace if there is newText
5915 if ( $newText != "" ) {
5916 $outText .= $newText . "\n\n";
5920 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5921 $node = $node->getNextSibling();
5925 if ( is_string( $outText ) ) {
5926 # Re-insert stripped tags
5927 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5934 * This function returns the text of a section, specified by a number ($section).
5935 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5936 * the first section before any such heading (section 0).
5938 * If a section contains subsections, these are also returned.
5940 * @param string $text Text to look in
5941 * @param string|number $sectionId Section identifier as a number or string
5942 * (e.g. 0, 1 or 'T-1').
5943 * @param string $defaultText Default to return if section is not found
5945 * @return string Text of the requested section
5947 public function getSection( $text, $sectionId, $defaultText = '' ) {
5948 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
5952 * This function returns $oldtext after the content of the section
5953 * specified by $section has been replaced with $text. If the target
5954 * section does not exist, $oldtext is returned unchanged.
5956 * @param string $oldText Former text of the article
5957 * @param string|number $sectionId Section identifier as a number or string
5958 * (e.g. 0, 1 or 'T-1').
5959 * @param string $newText Replacing text
5961 * @return string Modified text
5963 public function replaceSection( $oldText, $sectionId, $newText ) {
5964 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
5968 * Get the ID of the revision we are parsing
5972 public function getRevisionId() {
5973 return $this->mRevisionId
;
5977 * Get the revision object for $this->mRevisionId
5979 * @return Revision|null Either a Revision object or null
5980 * @since 1.23 (public since 1.23)
5982 public function getRevisionObject() {
5983 if ( !is_null( $this->mRevisionObject
) ) {
5984 return $this->mRevisionObject
;
5986 if ( is_null( $this->mRevisionId
) ) {
5990 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5991 return $this->mRevisionObject
;
5995 * Get the timestamp associated with the current revision, adjusted for
5996 * the default server-local timestamp
5999 public function getRevisionTimestamp() {
6000 if ( is_null( $this->mRevisionTimestamp
) ) {
6001 wfProfileIn( __METHOD__
);
6005 $revObject = $this->getRevisionObject();
6006 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
6008 # The cryptic '' timezone parameter tells to use the site-default
6009 # timezone offset instead of the user settings.
6011 # Since this value will be saved into the parser cache, served
6012 # to other users, and potentially even used inside links and such,
6013 # it needs to be consistent for all visitors.
6014 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
6016 wfProfileOut( __METHOD__
);
6018 return $this->mRevisionTimestamp
;
6022 * Get the name of the user that edited the last revision
6024 * @return string User name
6026 public function getRevisionUser() {
6027 if ( is_null( $this->mRevisionUser
) ) {
6028 $revObject = $this->getRevisionObject();
6030 # if this template is subst: the revision id will be blank,
6031 # so just use the current user's name
6033 $this->mRevisionUser
= $revObject->getUserText();
6034 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6035 $this->mRevisionUser
= $this->getUser()->getName();
6038 return $this->mRevisionUser
;
6042 * Get the size of the revision
6044 * @return int|null Revision size
6046 public function getRevisionSize() {
6047 if ( is_null( $this->mRevisionSize
) ) {
6048 $revObject = $this->getRevisionObject();
6050 # if this variable is subst: the revision id will be blank,
6051 # so just use the parser input size, because the own substituation
6052 # will change the size.
6054 $this->mRevisionSize
= $revObject->getSize();
6055 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6056 $this->mRevisionSize
= $this->mInputSize
;
6059 return $this->mRevisionSize
;
6063 * Mutator for $mDefaultSort
6065 * @param string $sort New value
6067 public function setDefaultSort( $sort ) {
6068 $this->mDefaultSort
= $sort;
6069 $this->mOutput
->setProperty( 'defaultsort', $sort );
6073 * Accessor for $mDefaultSort
6074 * Will use the empty string if none is set.
6076 * This value is treated as a prefix, so the
6077 * empty string is equivalent to sorting by
6082 public function getDefaultSort() {
6083 if ( $this->mDefaultSort
!== false ) {
6084 return $this->mDefaultSort
;
6091 * Accessor for $mDefaultSort
6092 * Unlike getDefaultSort(), will return false if none is set
6094 * @return string|bool
6096 public function getCustomDefaultSort() {
6097 return $this->mDefaultSort
;
6101 * Try to guess the section anchor name based on a wikitext fragment
6102 * presumably extracted from a heading, for example "Header" from
6105 * @param string $text
6109 public function guessSectionNameFromWikiText( $text ) {
6110 # Strip out wikitext links(they break the anchor)
6111 $text = $this->stripSectionName( $text );
6112 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6113 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
6117 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6118 * instead. For use in redirects, since IE6 interprets Redirect: headers
6119 * as something other than UTF-8 (apparently?), resulting in breakage.
6121 * @param string $text The section name
6122 * @return string An anchor
6124 public function guessLegacySectionNameFromWikiText( $text ) {
6125 # Strip out wikitext links(they break the anchor)
6126 $text = $this->stripSectionName( $text );
6127 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6128 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
6132 * Strips a text string of wikitext for use in a section anchor
6134 * Accepts a text string and then removes all wikitext from the
6135 * string and leaves only the resultant text (i.e. the result of
6136 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6137 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6138 * to create valid section anchors by mimicing the output of the
6139 * parser when headings are parsed.
6141 * @param string $text Text string to be stripped of wikitext
6142 * for use in a Section anchor
6143 * @return string Filtered text string
6145 public function stripSectionName( $text ) {
6146 # Strip internal link markup
6147 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6148 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6150 # Strip external link markup
6151 # @todo FIXME: Not tolerant to blank link text
6152 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6153 # on how many empty links there are on the page - need to figure that out.
6154 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6156 # Parse wikitext quotes (italics & bold)
6157 $text = $this->doQuotes( $text );
6160 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
6165 * strip/replaceVariables/unstrip for preprocessor regression testing
6167 * @param string $text
6168 * @param Title $title
6169 * @param ParserOptions $options
6170 * @param int $outputType
6174 public function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
6175 $magicScopeVariable = $this->lock();
6176 $this->startParse( $title, $options, $outputType, true );
6178 $text = $this->replaceVariables( $text );
6179 $text = $this->mStripState
->unstripBoth( $text );
6180 $text = Sanitizer
::removeHTMLtags( $text );
6185 * @param string $text
6186 * @param Title $title
6187 * @param ParserOptions $options
6190 public function testPst( $text, Title
$title, ParserOptions
$options ) {
6191 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6195 * @param string $text
6196 * @param Title $title
6197 * @param ParserOptions $options
6200 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
6201 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
6205 * Call a callback function on all regions of the given text that are not
6206 * inside strip markers, and replace those regions with the return value
6207 * of the callback. For example, with input:
6211 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6212 * two strings will be replaced with the value returned by the callback in
6216 * @param callable $callback
6220 public function markerSkipCallback( $s, $callback ) {
6223 while ( $i < strlen( $s ) ) {
6224 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
6225 if ( $markerStart === false ) {
6226 $out .= call_user_func( $callback, substr( $s, $i ) );
6229 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6230 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6231 if ( $markerEnd === false ) {
6232 $out .= substr( $s, $markerStart );
6235 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6236 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6245 * Remove any strip markers found in the given text.
6247 * @param string $text Input string
6250 public function killMarkers( $text ) {
6251 return $this->mStripState
->killMarkers( $text );
6255 * Save the parser state required to convert the given half-parsed text to
6256 * HTML. "Half-parsed" in this context means the output of
6257 * recursiveTagParse() or internalParse(). This output has strip markers
6258 * from replaceVariables (extensionSubstitution() etc.), and link
6259 * placeholders from replaceLinkHolders().
6261 * Returns an array which can be serialized and stored persistently. This
6262 * array can later be loaded into another parser instance with
6263 * unserializeHalfParsedText(). The text can then be safely incorporated into
6264 * the return value of a parser hook.
6266 * @param string $text
6270 public function serializeHalfParsedText( $text ) {
6271 wfProfileIn( __METHOD__
);
6274 'version' => self
::HALF_PARSED_VERSION
,
6275 'stripState' => $this->mStripState
->getSubState( $text ),
6276 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6278 wfProfileOut( __METHOD__
);
6283 * Load the parser state given in the $data array, which is assumed to
6284 * have been generated by serializeHalfParsedText(). The text contents is
6285 * extracted from the array, and its markers are transformed into markers
6286 * appropriate for the current Parser instance. This transformed text is
6287 * returned, and can be safely included in the return value of a parser
6290 * If the $data array has been stored persistently, the caller should first
6291 * check whether it is still valid, by calling isValidHalfParsedText().
6293 * @param array $data Serialized data
6294 * @throws MWException
6297 public function unserializeHalfParsedText( $data ) {
6298 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6299 throw new MWException( __METHOD__
. ': invalid version' );
6302 # First, extract the strip state.
6303 $texts = array( $data['text'] );
6304 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6306 # Now renumber links
6307 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6309 # Should be good to go.
6314 * Returns true if the given array, presumed to be generated by
6315 * serializeHalfParsedText(), is compatible with the current version of the
6318 * @param array $data
6322 public function isValidHalfParsedText( $data ) {
6323 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6327 * Parsed a width param of imagelink like 300px or 200x300px
6329 * @param string $value
6334 public function parseWidthParam( $value ) {
6335 $parsedWidthParam = array();
6336 if ( $value === '' ) {
6337 return $parsedWidthParam;
6340 # (bug 13500) In both cases (width/height and width only),
6341 # permit trailing "px" for backward compatibility.
6342 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6343 $width = intval( $m[1] );
6344 $height = intval( $m[2] );
6345 $parsedWidthParam['width'] = $width;
6346 $parsedWidthParam['height'] = $height;
6347 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6348 $width = intval( $value );
6349 $parsedWidthParam['width'] = $width;
6351 return $parsedWidthParam;
6355 * Lock the current instance of the parser.
6357 * This is meant to stop someone from calling the parser
6358 * recursively and messing up all the strip state.
6360 * @throws MWException If parser is in a parse
6361 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6363 protected function lock() {
6364 if ( $this->mInParse
) {
6365 throw new MWException( "Parser state cleared while parsing. "
6366 . "Did you call Parser::parse recursively?" );
6368 $this->mInParse
= true;
6371 $recursiveCheck = new ScopedCallback( function() use ( $that ) {
6372 $that->mInParse
= false;
6375 return $recursiveCheck;
6379 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6381 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6382 * or if there is more than one <p/> tag in the input HTML.
6384 * @param string $html
6388 public static function stripOuterParagraph( $html ) {
6390 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6391 if ( strpos( $m[1], '</p>' ) === false ) {
6400 * Return this parser if it is not doing anything, otherwise
6401 * get a fresh parser. You can use this method by doing
6402 * $myParser = $wgParser->getFreshParser(), or more simply
6403 * $wgParser->getFreshParser()->parse( ... );
6404 * if you're unsure if $wgParser is safe to use.
6407 * @return Parser A parser object that is not parsing anything
6409 public function getFreshParser() {
6410 global $wgParserConf;
6411 if ( $this->mInParse
) {
6412 return new $wgParserConf['class']( $wgParserConf );