3 * PHP parser that converts wiki markup to HTML.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * @defgroup Parser Parser
29 * PHP Parser - Processes wiki markup (which uses a more user-friendly
30 * syntax, such as "[[link]]" for making links), and provides a one-way
31 * transformation of that wiki markup it into (X)HTML output / markup
32 * (which in turn the browser understands, and can display).
34 * There are seven main entry points into the Parser class:
37 * produces HTML output
38 * - Parser::preSaveTransform()
39 * produces altered wiki markup
40 * - Parser::preprocess()
41 * removes HTML comments and expands templates
42 * - Parser::cleanSig() and Parser::cleanSigInSig()
43 * cleans a signature before saving it to preferences
44 * - Parser::getSection()
45 * return the content of a section from an article for section editing
46 * - Parser::replaceSection()
47 * replaces a section by number inside an article
48 * - Parser::getPreloadText()
49 * removes <noinclude> sections and <includeonly> tags
54 * @warning $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
57 * $wgNamespacesWithSubpages
59 * @par Settings only within ParserOptions:
60 * $wgAllowExternalImages
61 * $wgAllowSpecialInclusion
69 * Update this version number when the ParserOutput format
70 * changes in an incompatible way, so the parser cache
71 * can automatically discard old data.
73 const VERSION
= '1.6.4';
76 * Update this version number when the output of serialiseHalfParsedText()
77 * changes in an incompatible way
79 const HALF_PARSED_VERSION
= 2;
81 # Flags for Parser::setFunctionHook
82 const SFH_NO_HASH
= 1;
83 const SFH_OBJECT_ARGS
= 2;
85 # Constants needed for external link processing
86 # Everything except bracket, space, or control characters
87 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
88 # as well as U+3000 is IDEOGRAPHIC SPACE for bug 19052
89 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}]';
90 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F\p{Zs}]+)
91 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
93 # Regular expression for a non-newline space
94 const SPACE_NOT_NL
= '(?:\t| |&\#0*160;|&\#[Xx]0*[Aa]0;|\p{Zs})';
96 # State constants for the definition list colon extraction
97 const COLON_STATE_TEXT
= 0;
98 const COLON_STATE_TAG
= 1;
99 const COLON_STATE_TAGSTART
= 2;
100 const COLON_STATE_CLOSETAG
= 3;
101 const COLON_STATE_TAGSLASH
= 4;
102 const COLON_STATE_COMMENT
= 5;
103 const COLON_STATE_COMMENTDASH
= 6;
104 const COLON_STATE_COMMENTDASHDASH
= 7;
106 # Flags for preprocessToDom
107 const PTD_FOR_INCLUSION
= 1;
109 # Allowed values for $this->mOutputType
110 # Parameter to startExternalParse().
111 const OT_HTML
= 1; # like parse()
112 const OT_WIKI
= 2; # like preSaveTransform()
113 const OT_PREPROCESS
= 3; # like preprocess()
115 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
117 # Marker Suffix needs to be accessible staticly.
118 const MARKER_SUFFIX
= "-QINU\x7f";
120 # Markers used for wrapping the table of contents
121 const TOC_START
= '<mw:toc>';
122 const TOC_END
= '</mw:toc>';
125 public $mTagHooks = array();
126 public $mTransparentTagHooks = array();
127 public $mFunctionHooks = array();
128 public $mFunctionSynonyms = array( 0 => array(), 1 => array() );
129 public $mFunctionTagHooks = array();
130 public $mStripList = array();
131 public $mDefaultStripList = array();
132 public $mVarCache = array();
133 public $mImageParams = array();
134 public $mImageParamsMagicArray = array();
135 public $mMarkerIndex = 0;
136 public $mFirstCall = true;
138 # Initialised by initialiseVariables()
141 * @var MagicWordArray
146 * @var MagicWordArray
149 # Initialised in constructor
150 public $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols;
152 # Cleared with clearState():
157 public $mAutonumber, $mDTopen;
164 public $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
166 * @var LinkHolderArray
168 public $mLinkHolders;
171 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
172 public $mDefaultSort;
173 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
174 public $mExpensiveFunctionCount; # number of expensive parser function calls
175 public $mShowToc, $mForceTocPosition;
180 public $mUser; # User object; only used when doing pre-save transform
183 # These are variables reset at least once per parse regardless of $clearState
193 public $mTitle; # Title context, used for self-link rendering and similar things
194 public $mOutputType; # Output type, one of the OT_xxx constants
195 public $ot; # Shortcut alias, see setOutputType()
196 public $mRevisionObject; # The revision object of the specified revision ID
197 public $mRevisionId; # ID to display in {{REVISIONID}} tags
198 public $mRevisionTimestamp; # The timestamp of the specified revision ID
199 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag
200 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
201 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp
202 public $mInputSize = false; # For {{PAGESIZE}} on current page.
210 * @var array Array with the language name of each language link (i.e. the
211 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
212 * duplicate language links to the ParserOutput.
214 public $mLangLinkLanguages;
217 * @var MapCacheLRU|null
220 * A cache of the current revisions of titles. Keys are $title->getPrefixedDbKey()
222 public $currentRevisionCache;
225 * @var bool Recursive call protection.
226 * This variable should be treated as if it were private.
228 public $mInParse = false;
230 /** @var SectionProfiler */
231 protected $mProfiler;
236 public function __construct( $conf = array() ) {
237 $this->mConf
= $conf;
238 $this->mUrlProtocols
= wfUrlProtocols();
239 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
240 self
::EXT_LINK_URL_CLASS
. '+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
241 if ( isset( $conf['preprocessorClass'] ) ) {
242 $this->mPreprocessorClass
= $conf['preprocessorClass'];
243 } elseif ( defined( 'HPHP_VERSION' ) ) {
244 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
245 $this->mPreprocessorClass
= 'Preprocessor_Hash';
246 } elseif ( extension_loaded( 'domxml' ) ) {
247 # PECL extension that conflicts with the core DOM extension (bug 13770)
248 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
249 $this->mPreprocessorClass
= 'Preprocessor_Hash';
250 } elseif ( extension_loaded( 'dom' ) ) {
251 $this->mPreprocessorClass
= 'Preprocessor_DOM';
253 $this->mPreprocessorClass
= 'Preprocessor_Hash';
255 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
259 * Reduce memory usage to reduce the impact of circular references
261 public function __destruct() {
262 if ( isset( $this->mLinkHolders
) ) {
263 unset( $this->mLinkHolders
);
265 foreach ( $this as $name => $value ) {
266 unset( $this->$name );
271 * Allow extensions to clean up when the parser is cloned
273 public function __clone() {
274 $this->mInParse
= false;
276 // Bug 56226: When you create a reference "to" an object field, that
277 // makes the object field itself be a reference too (until the other
278 // reference goes out of scope). When cloning, any field that's a
279 // reference is copied as a reference in the new object. Both of these
280 // are defined PHP5 behaviors, as inconvenient as it is for us when old
281 // hooks from PHP4 days are passing fields by reference.
282 foreach ( array( 'mStripState', 'mVarCache' ) as $k ) {
283 // Make a non-reference copy of the field, then rebind the field to
284 // reference the new copy.
290 Hooks
::run( 'ParserCloned', array( $this ) );
294 * Do various kinds of initialisation on the first call of the parser
296 public function firstCallInit() {
297 if ( !$this->mFirstCall
) {
300 $this->mFirstCall
= false;
303 CoreParserFunctions
::register( $this );
304 CoreTagHooks
::register( $this );
305 $this->initialiseVariables();
307 Hooks
::run( 'ParserFirstCallInit', array( &$this ) );
315 public function clearState() {
316 if ( $this->mFirstCall
) {
317 $this->firstCallInit();
319 $this->mOutput
= new ParserOutput
;
320 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
321 $this->mAutonumber
= 0;
322 $this->mLastSection
= '';
323 $this->mDTopen
= false;
324 $this->mIncludeCount
= array();
325 $this->mArgStack
= false;
326 $this->mInPre
= false;
327 $this->mLinkHolders
= new LinkHolderArray( $this );
329 $this->mRevisionObject
= $this->mRevisionTimestamp
=
330 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
331 $this->mVarCache
= array();
333 $this->mLangLinkLanguages
= array();
334 $this->currentRevisionCache
= null;
337 * Prefix for temporary replacement strings for the multipass parser.
338 * \x07 should never appear in input as it's disallowed in XML.
339 * Using it at the front also gives us a little extra robustness
340 * since it shouldn't match when butted up against identifier-like
343 * Must not consist of all title characters, or else it will change
344 * the behavior of <nowiki> in a link.
346 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
347 $this->mStripState
= new StripState( $this->mUniqPrefix
);
349 # Clear these on every parse, bug 4549
350 $this->mTplRedirCache
= $this->mTplDomCache
= array();
352 $this->mShowToc
= true;
353 $this->mForceTocPosition
= false;
354 $this->mIncludeSizes
= array(
358 $this->mPPNodeCount
= 0;
359 $this->mGeneratedPPNodeCount
= 0;
360 $this->mHighestExpansionDepth
= 0;
361 $this->mDefaultSort
= false;
362 $this->mHeadings
= array();
363 $this->mDoubleUnderscores
= array();
364 $this->mExpensiveFunctionCount
= 0;
367 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
368 $this->mPreprocessor
= null;
371 $this->mProfiler
= new SectionProfiler();
373 Hooks
::run( 'ParserClearState', array( &$this ) );
377 * Convert wikitext to HTML
378 * Do not call this function recursively.
380 * @param string $text Text we want to parse
381 * @param Title $title
382 * @param ParserOptions $options
383 * @param bool $linestart
384 * @param bool $clearState
385 * @param int $revid Number to pass in {{REVISIONID}}
386 * @return ParserOutput A ParserOutput
388 public function parse( $text, Title
$title, ParserOptions
$options,
389 $linestart = true, $clearState = true, $revid = null
392 * First pass--just handle <nowiki> sections, pass the rest off
393 * to internalParse() which does all the real work.
396 global $wgShowHostnames;
397 $fname = __METHOD__
. '-' . wfGetCaller();
398 wfProfileIn( $fname );
401 $magicScopeVariable = $this->lock();
404 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
406 $this->currentRevisionCache
= null;
407 $this->mInputSize
= strlen( $text );
408 if ( $this->mOptions
->getEnableLimitReport() ) {
409 $this->mOutput
->resetParseStartTime();
412 # Remove the strip marker tag prefix from the input, if present.
414 $text = str_replace( $this->mUniqPrefix
, '', $text );
417 $oldRevisionId = $this->mRevisionId
;
418 $oldRevisionObject = $this->mRevisionObject
;
419 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
420 $oldRevisionUser = $this->mRevisionUser
;
421 $oldRevisionSize = $this->mRevisionSize
;
422 if ( $revid !== null ) {
423 $this->mRevisionId
= $revid;
424 $this->mRevisionObject
= null;
425 $this->mRevisionTimestamp
= null;
426 $this->mRevisionUser
= null;
427 $this->mRevisionSize
= null;
430 Hooks
::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
432 Hooks
::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
433 $text = $this->internalParse( $text );
434 Hooks
::run( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
436 $text = $this->internalParseHalfParsed( $text, true, $linestart );
439 * A converted title will be provided in the output object if title and
440 * content conversion are enabled, the article text does not contain
441 * a conversion-suppressing double-underscore tag, and no
442 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
443 * automatic link conversion.
445 if ( !( $options->getDisableTitleConversion()
446 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
447 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
448 ||
$this->mOutput
->getDisplayTitle() !== false )
450 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
451 if ( $convruletitle ) {
452 $this->mOutput
->setTitleText( $convruletitle );
454 $titleText = $this->getConverterLanguage()->convertTitle( $title );
455 $this->mOutput
->setTitleText( $titleText );
459 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
460 $this->limitationWarn( 'expensive-parserfunction',
461 $this->mExpensiveFunctionCount
,
462 $this->mOptions
->getExpensiveParserFunctionLimit()
466 # Information on include size limits, for the benefit of users who try to skirt them
467 if ( $this->mOptions
->getEnableLimitReport() ) {
468 $max = $this->mOptions
->getMaxIncludeSize();
470 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
471 if ( $cpuTime !== null ) {
472 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
473 sprintf( "%.3f", $cpuTime )
477 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
478 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
479 sprintf( "%.3f", $wallTime )
482 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
483 array( $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() )
485 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
486 array( $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() )
488 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
489 array( $this->mIncludeSizes
['post-expand'], $max )
491 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
492 array( $this->mIncludeSizes
['arg'], $max )
494 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
495 array( $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() )
497 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
498 array( $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() )
500 Hooks
::run( 'ParserLimitReportPrepare', array( $this, $this->mOutput
) );
502 $limitReport = "NewPP limit report\n";
503 if ( $wgShowHostnames ) {
504 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
506 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
507 if ( Hooks
::run( 'ParserLimitReportFormat',
508 array( $key, &$value, &$limitReport, false, false )
510 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
511 $valueMsg = wfMessage( array( "$key-value-text", "$key-value" ) )
512 ->inLanguage( 'en' )->useDatabase( false );
513 if ( !$valueMsg->exists() ) {
514 $valueMsg = new RawMessage( '$1' );
516 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
517 $valueMsg->params( $value );
518 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
522 // Since we're not really outputting HTML, decode the entities and
523 // then re-encode the things that need hiding inside HTML comments.
524 $limitReport = htmlspecialchars_decode( $limitReport );
525 Hooks
::run( 'ParserLimitReport', array( $this, &$limitReport ) );
527 // Sanitize for comment. Note '‐' in the replacement is U+2010,
528 // which looks much like the problematic '-'.
529 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&' ), $limitReport );
530 $text .= "\n<!-- \n$limitReport-->\n";
532 // Add on template profiling data
533 $dataByFunc = $this->mProfiler
->getFunctionStats();
534 uasort( $dataByFunc, function ( $a, $b ) {
535 return $a['real'] < $b['real']; // descending order
537 $profileReport = "Transclusion expansion time report (%,ms,calls,template)\n";
538 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
539 $profileReport .= sprintf( "%6.2f%% %8.3f %6d - %s\n",
540 $item['%real'], $item['real'], $item['calls'],
541 htmlspecialchars( $item['name'] ) );
543 $text .= "\n<!-- \n$profileReport-->\n";
545 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
546 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
547 $this->mTitle
->getPrefixedDBkey() );
550 $this->mOutput
->setText( $text );
552 $this->mRevisionId
= $oldRevisionId;
553 $this->mRevisionObject
= $oldRevisionObject;
554 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
555 $this->mRevisionUser
= $oldRevisionUser;
556 $this->mRevisionSize
= $oldRevisionSize;
557 $this->mInputSize
= false;
558 $this->currentRevisionCache
= null;
559 wfProfileOut( $fname );
561 return $this->mOutput
;
565 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
566 * can be called from an extension tag hook.
568 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
569 * instead, which means that lists and links have not been fully parsed yet,
570 * and strip markers are still present.
572 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
574 * Use this function if you're a parser tag hook and you want to parse
575 * wikitext before or after applying additional transformations, and you
576 * intend to *return the result as hook output*, which will cause it to go
577 * through the rest of parsing process automatically.
579 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
580 * $text are not expanded
582 * @param string $text Text extension wants to have parsed
583 * @param bool|PPFrame $frame The frame to use for expanding any template variables
584 * @return string UNSAFE half-parsed HTML
586 public function recursiveTagParse( $text, $frame = false ) {
587 Hooks
::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
588 Hooks
::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
589 $text = $this->internalParse( $text, false, $frame );
594 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
595 * point can be called from an extension tag hook.
597 * The output of this function is fully-parsed HTML that is safe for output.
598 * If you're a parser tag hook, you might want to use recursiveTagParse()
601 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
602 * $text are not expanded
606 * @param string $text Text extension wants to have parsed
607 * @param bool|PPFrame $frame The frame to use for expanding any template variables
608 * @return string Fully parsed HTML
610 public function recursiveTagParseFully( $text, $frame = false ) {
611 $text = $this->recursiveTagParse( $text, $frame );
612 $text = $this->internalParseHalfParsed( $text, false );
617 * Expand templates and variables in the text, producing valid, static wikitext.
618 * Also removes comments.
619 * Do not call this function recursively.
620 * @param string $text
621 * @param Title $title
622 * @param ParserOptions $options
623 * @param int|null $revid
624 * @param bool|PPFrame $frame
625 * @return mixed|string
627 public function preprocess( $text, Title
$title = null,
628 ParserOptions
$options, $revid = null, $frame = false
630 $magicScopeVariable = $this->lock();
631 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
632 if ( $revid !== null ) {
633 $this->mRevisionId
= $revid;
635 Hooks
::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
636 Hooks
::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
637 $text = $this->replaceVariables( $text, $frame );
638 $text = $this->mStripState
->unstripBoth( $text );
643 * Recursive parser entry point that can be called from an extension tag
646 * @param string $text Text to be expanded
647 * @param bool|PPFrame $frame The frame to use for expanding any template variables
651 public function recursivePreprocess( $text, $frame = false ) {
652 $text = $this->replaceVariables( $text, $frame );
653 $text = $this->mStripState
->unstripBoth( $text );
658 * Process the wikitext for the "?preload=" feature. (bug 5210)
660 * "<noinclude>", "<includeonly>" etc. are parsed as for template
661 * transclusion, comments, templates, arguments, tags hooks and parser
662 * functions are untouched.
664 * @param string $text
665 * @param Title $title
666 * @param ParserOptions $options
667 * @param array $params
670 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = array() ) {
671 $msg = new RawMessage( $text );
672 $text = $msg->params( $params )->plain();
674 # Parser (re)initialisation
675 $magicScopeVariable = $this->lock();
676 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
678 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
679 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
680 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
681 $text = $this->mStripState
->unstripBoth( $text );
686 * Get a random string
690 public static function getRandomString() {
691 return wfRandomString( 16 );
695 * Set the current user.
696 * Should only be used when doing pre-save transform.
698 * @param User|null $user User object or null (to reset)
700 public function setUser( $user ) {
701 $this->mUser
= $user;
705 * Accessor for mUniqPrefix.
709 public function uniqPrefix() {
710 if ( !isset( $this->mUniqPrefix
) ) {
711 # @todo FIXME: This is probably *horribly wrong*
712 # LanguageConverter seems to want $wgParser's uniqPrefix, however
713 # if this is called for a parser cache hit, the parser may not
714 # have ever been initialized in the first place.
715 # Not really sure what the heck is supposed to be going on here.
717 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
719 return $this->mUniqPrefix
;
723 * Set the context title
727 public function setTitle( $t ) {
729 $t = Title
::newFromText( 'NO TITLE' );
732 if ( $t->hasFragment() ) {
733 # Strip the fragment to avoid various odd effects
734 $this->mTitle
= clone $t;
735 $this->mTitle
->setFragment( '' );
742 * Accessor for the Title object
746 public function getTitle() {
747 return $this->mTitle
;
751 * Accessor/mutator for the Title object
753 * @param Title $x Title object or null to just get the current one
756 public function Title( $x = null ) {
757 return wfSetVar( $this->mTitle
, $x );
761 * Set the output type
763 * @param int $ot New value
765 public function setOutputType( $ot ) {
766 $this->mOutputType
= $ot;
769 'html' => $ot == self
::OT_HTML
,
770 'wiki' => $ot == self
::OT_WIKI
,
771 'pre' => $ot == self
::OT_PREPROCESS
,
772 'plain' => $ot == self
::OT_PLAIN
,
777 * Accessor/mutator for the output type
779 * @param int|null $x New value or null to just get the current one
782 public function OutputType( $x = null ) {
783 return wfSetVar( $this->mOutputType
, $x );
787 * Get the ParserOutput object
789 * @return ParserOutput
791 public function getOutput() {
792 return $this->mOutput
;
796 * Get the ParserOptions object
798 * @return ParserOptions
800 public function getOptions() {
801 return $this->mOptions
;
805 * Accessor/mutator for the ParserOptions object
807 * @param ParserOptions $x New value or null to just get the current one
808 * @return ParserOptions Current ParserOptions object
810 public function Options( $x = null ) {
811 return wfSetVar( $this->mOptions
, $x );
817 public function nextLinkID() {
818 return $this->mLinkID++
;
824 public function setLinkID( $id ) {
825 $this->mLinkID
= $id;
829 * Get a language object for use in parser functions such as {{FORMATNUM:}}
832 public function getFunctionLang() {
833 return $this->getTargetLanguage();
837 * Get the target language for the content being parsed. This is usually the
838 * language that the content is in.
842 * @throws MWException
845 public function getTargetLanguage() {
846 $target = $this->mOptions
->getTargetLanguage();
848 if ( $target !== null ) {
850 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
851 return $this->mOptions
->getUserLangObj();
852 } elseif ( is_null( $this->mTitle
) ) {
853 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
856 return $this->mTitle
->getPageLanguage();
860 * Get the language object for language conversion
861 * @return Language|null
863 public function getConverterLanguage() {
864 return $this->getTargetLanguage();
868 * Get a User object either from $this->mUser, if set, or from the
869 * ParserOptions object otherwise
873 public function getUser() {
874 if ( !is_null( $this->mUser
) ) {
877 return $this->mOptions
->getUser();
881 * Get a preprocessor object
883 * @return Preprocessor
885 public function getPreprocessor() {
886 if ( !isset( $this->mPreprocessor
) ) {
887 $class = $this->mPreprocessorClass
;
888 $this->mPreprocessor
= new $class( $this );
890 return $this->mPreprocessor
;
894 * Replaces all occurrences of HTML-style comments and the given tags
895 * in the text with a random marker and returns the next text. The output
896 * parameter $matches will be an associative array filled with data in
900 * 'UNIQ-xxxxx' => array(
903 * array( 'param' => 'x' ),
904 * '<element param="x">tag content</element>' ) )
907 * @param array $elements List of element names. Comments are always extracted.
908 * @param string $text Source text string.
909 * @param array $matches Out parameter, Array: extracted tags
910 * @param string $uniq_prefix
911 * @return string Stripped text
913 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
918 $taglist = implode( '|', $elements );
919 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
921 while ( $text != '' ) {
922 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
924 if ( count( $p ) < 5 ) {
927 if ( count( $p ) > 5 ) {
941 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
942 $stripped .= $marker;
944 if ( $close === '/>' ) {
945 # Empty element tag, <tag />
950 if ( $element === '!--' ) {
953 $end = "/(<\\/$element\\s*>)/i";
955 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
957 if ( count( $q ) < 3 ) {
958 # No end tag -- let it run out to the end of the text.
967 $matches[$marker] = array( $element,
969 Sanitizer
::decodeTagAttributes( $attributes ),
970 "<$element$attributes$close$content$tail" );
976 * Get a list of strippable XML-like elements
980 public function getStripList() {
981 return $this->mStripList
;
985 * Add an item to the strip state
986 * Returns the unique tag which must be inserted into the stripped text
987 * The tag will be replaced with the original text in unstrip()
989 * @param string $text
993 public function insertStripItem( $text ) {
994 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
995 $this->mMarkerIndex++
;
996 $this->mStripState
->addGeneral( $rnd, $text );
1001 * parse the wiki syntax used to render tables
1004 * @param string $text
1007 public function doTableStuff( $text ) {
1009 $lines = StringUtils
::explode( "\n", $text );
1011 $td_history = array(); # Is currently a td tag open?
1012 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
1013 $tr_history = array(); # Is currently a tr tag open?
1014 $tr_attributes = array(); # history of tr attributes
1015 $has_opened_tr = array(); # Did this table open a <tr> element?
1016 $indent_level = 0; # indent level of the table
1018 foreach ( $lines as $outLine ) {
1019 $line = trim( $outLine );
1021 if ( $line === '' ) { # empty line, go to next line
1022 $out .= $outLine . "\n";
1026 $first_character = $line[0];
1029 if ( preg_match( '/^(:*)\{\|(.*)$/', $line, $matches ) ) {
1030 # First check if we are starting a new table
1031 $indent_level = strlen( $matches[1] );
1033 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1034 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1036 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1037 array_push( $td_history, false );
1038 array_push( $last_tag_history, '' );
1039 array_push( $tr_history, false );
1040 array_push( $tr_attributes, '' );
1041 array_push( $has_opened_tr, false );
1042 } elseif ( count( $td_history ) == 0 ) {
1043 # Don't do any of the following
1044 $out .= $outLine . "\n";
1046 } elseif ( substr( $line, 0, 2 ) === '|}' ) {
1047 # We are ending a table
1048 $line = '</table>' . substr( $line, 2 );
1049 $last_tag = array_pop( $last_tag_history );
1051 if ( !array_pop( $has_opened_tr ) ) {
1052 $line = "<tr><td></td></tr>{$line}";
1055 if ( array_pop( $tr_history ) ) {
1056 $line = "</tr>{$line}";
1059 if ( array_pop( $td_history ) ) {
1060 $line = "</{$last_tag}>{$line}";
1062 array_pop( $tr_attributes );
1063 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
1064 } elseif ( substr( $line, 0, 2 ) === '|-' ) {
1065 # Now we have a table row
1066 $line = preg_replace( '#^\|-+#', '', $line );
1068 # Whats after the tag is now only attributes
1069 $attributes = $this->mStripState
->unstripBoth( $line );
1070 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1071 array_pop( $tr_attributes );
1072 array_push( $tr_attributes, $attributes );
1075 $last_tag = array_pop( $last_tag_history );
1076 array_pop( $has_opened_tr );
1077 array_push( $has_opened_tr, true );
1079 if ( array_pop( $tr_history ) ) {
1083 if ( array_pop( $td_history ) ) {
1084 $line = "</{$last_tag}>{$line}";
1088 array_push( $tr_history, false );
1089 array_push( $td_history, false );
1090 array_push( $last_tag_history, '' );
1091 } elseif ( $first_character === '|'
1092 ||
$first_character === '!'
1093 ||
substr( $line, 0, 2 ) === '|+'
1095 # This might be cell elements, td, th or captions
1096 if ( substr( $line, 0, 2 ) === '|+' ) {
1097 $first_character = '+';
1098 $line = substr( $line, 1 );
1101 $line = substr( $line, 1 );
1103 if ( $first_character === '!' ) {
1104 $line = str_replace( '!!', '||', $line );
1107 # Split up multiple cells on the same line.
1108 # FIXME : This can result in improper nesting of tags processed
1109 # by earlier parser steps, but should avoid splitting up eg
1110 # attribute values containing literal "||".
1111 $cells = StringUtils
::explodeMarkup( '||', $line );
1115 # Loop through each table cell
1116 foreach ( $cells as $cell ) {
1118 if ( $first_character !== '+' ) {
1119 $tr_after = array_pop( $tr_attributes );
1120 if ( !array_pop( $tr_history ) ) {
1121 $previous = "<tr{$tr_after}>\n";
1123 array_push( $tr_history, true );
1124 array_push( $tr_attributes, '' );
1125 array_pop( $has_opened_tr );
1126 array_push( $has_opened_tr, true );
1129 $last_tag = array_pop( $last_tag_history );
1131 if ( array_pop( $td_history ) ) {
1132 $previous = "</{$last_tag}>\n{$previous}";
1135 if ( $first_character === '|' ) {
1137 } elseif ( $first_character === '!' ) {
1139 } elseif ( $first_character === '+' ) {
1140 $last_tag = 'caption';
1145 array_push( $last_tag_history, $last_tag );
1147 # A cell could contain both parameters and data
1148 $cell_data = explode( '|', $cell, 2 );
1150 # Bug 553: Note that a '|' inside an invalid link should not
1151 # be mistaken as delimiting cell parameters
1152 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1153 $cell = "{$previous}<{$last_tag}>{$cell}";
1154 } elseif ( count( $cell_data ) == 1 ) {
1155 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1157 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1158 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1159 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1163 array_push( $td_history, true );
1166 $out .= $outLine . "\n";
1169 # Closing open td, tr && table
1170 while ( count( $td_history ) > 0 ) {
1171 if ( array_pop( $td_history ) ) {
1174 if ( array_pop( $tr_history ) ) {
1177 if ( !array_pop( $has_opened_tr ) ) {
1178 $out .= "<tr><td></td></tr>\n";
1181 $out .= "</table>\n";
1184 # Remove trailing line-ending (b/c)
1185 if ( substr( $out, -1 ) === "\n" ) {
1186 $out = substr( $out, 0, -1 );
1189 # special case: don't return empty table
1190 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1199 * Helper function for parse() that transforms wiki markup into half-parsed
1200 * HTML. Only called for $mOutputType == self::OT_HTML.
1204 * @param string $text
1205 * @param bool $isMain
1206 * @param bool $frame
1210 public function internalParse( $text, $isMain = true, $frame = false ) {
1214 # Hook to suspend the parser in this state
1215 if ( !Hooks
::run( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1219 # if $frame is provided, then use $frame for replacing any variables
1221 # use frame depth to infer how include/noinclude tags should be handled
1222 # depth=0 means this is the top-level document; otherwise it's an included document
1223 if ( !$frame->depth
) {
1226 $flag = Parser
::PTD_FOR_INCLUSION
;
1228 $dom = $this->preprocessToDom( $text, $flag );
1229 $text = $frame->expand( $dom );
1231 # if $frame is not provided, then use old-style replaceVariables
1232 $text = $this->replaceVariables( $text );
1235 Hooks
::run( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1236 $text = Sanitizer
::removeHTMLtags(
1238 array( &$this, 'attributeStripCallback' ),
1240 array_keys( $this->mTransparentTagHooks
)
1242 Hooks
::run( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1244 # Tables need to come after variable replacement for things to work
1245 # properly; putting them before other transformations should keep
1246 # exciting things like link expansions from showing up in surprising
1248 $text = $this->doTableStuff( $text );
1250 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1252 $text = $this->doDoubleUnderscore( $text );
1254 $text = $this->doHeadings( $text );
1255 $text = $this->replaceInternalLinks( $text );
1256 $text = $this->doAllQuotes( $text );
1257 $text = $this->replaceExternalLinks( $text );
1259 # replaceInternalLinks may sometimes leave behind
1260 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1261 $text = str_replace( $this->mUniqPrefix
. 'NOPARSE', '', $text );
1263 $text = $this->doMagicLinks( $text );
1264 $text = $this->formatHeadings( $text, $origText, $isMain );
1270 * Helper function for parse() that transforms half-parsed HTML into fully
1273 * @param string $text
1274 * @param bool $isMain
1275 * @param bool $linestart
1278 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1279 global $wgUseTidy, $wgAlwaysUseTidy;
1281 $text = $this->mStripState
->unstripGeneral( $text );
1283 # Clean up special characters, only run once, next-to-last before doBlockLevels
1285 # french spaces, last one Guillemet-left
1286 # only if there is something before the space
1287 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
1288 # french spaces, Guillemet-right
1289 '/(\\302\\253) /' => '\\1 ',
1290 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
1292 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
1294 $text = $this->doBlockLevels( $text, $linestart );
1296 $this->replaceLinkHolders( $text );
1299 * The input doesn't get language converted if
1301 * b) Content isn't converted
1302 * c) It's a conversion table
1303 * d) it is an interface message (which is in the user language)
1305 if ( !( $this->mOptions
->getDisableContentConversion()
1306 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
1308 if ( !$this->mOptions
->getInterfaceMessage() ) {
1309 # The position of the convert() call should not be changed. it
1310 # assumes that the links are all replaced and the only thing left
1311 # is the <nowiki> mark.
1312 $text = $this->getConverterLanguage()->convert( $text );
1316 $text = $this->mStripState
->unstripNoWiki( $text );
1319 Hooks
::run( 'ParserBeforeTidy', array( &$this, &$text ) );
1322 $text = $this->replaceTransparentTags( $text );
1323 $text = $this->mStripState
->unstripGeneral( $text );
1325 $text = Sanitizer
::normalizeCharReferences( $text );
1327 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
1328 $text = MWTidy
::tidy( $text );
1330 # attempt to sanitize at least some nesting problems
1331 # (bug #2702 and quite a few others)
1333 # ''Something [http://www.cool.com cool''] -->
1334 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1335 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1336 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1337 # fix up an anchor inside another anchor, only
1338 # at least for a single single nested link (bug 3695)
1339 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1340 '\\1\\2</a>\\3</a>\\1\\4</a>',
1341 # fix div inside inline elements- doBlockLevels won't wrap a line which
1342 # contains a div, so fix it up here; replace
1343 # div with escaped text
1344 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1345 '\\1\\3<div\\5>\\6</div>\\8\\9',
1346 # remove empty italic or bold tag pairs, some
1347 # introduced by rules above
1348 '/<([bi])><\/\\1>/' => '',
1351 $text = preg_replace(
1352 array_keys( $tidyregs ),
1353 array_values( $tidyregs ),
1358 Hooks
::run( 'ParserAfterTidy', array( &$this, &$text ) );
1365 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1366 * magic external links.
1371 * @param string $text
1375 public function doMagicLinks( $text ) {
1376 $prots = wfUrlProtocolsWithoutProtRel();
1377 $urlChar = self
::EXT_LINK_URL_CLASS
;
1378 $space = self
::SPACE_NOT_NL
; # non-newline space
1379 $spdash = "(?:-|$space)"; # a dash or a non-newline space
1380 $spaces = "$space++"; # possessive match of 1 or more spaces
1381 $text = preg_replace_callback(
1383 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1384 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1385 (\b(?i:$prots)$urlChar+) | # m[3]: Free external links
1386 \b(?:RFC|PMID) $spaces # m[4]: RFC or PMID, capture number
1388 \bISBN $spaces ( # m[5]: ISBN, capture number
1389 (?: 97[89] $spdash? )? # optional 13-digit ISBN prefix
1390 (?: [0-9] $spdash? ){9} # 9 digits with opt. delimiters
1391 [0-9Xx] # check digit
1393 )!xu", array( &$this, 'magicLinkCallback' ), $text );
1398 * @throws MWException
1400 * @return HTML|string
1402 public function magicLinkCallback( $m ) {
1403 if ( isset( $m[1] ) && $m[1] !== '' ) {
1406 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1409 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1410 # Free external link
1411 return $this->makeFreeExternalLink( $m[0] );
1412 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1414 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1417 $cssClass = 'mw-magiclink-rfc';
1419 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1421 $urlmsg = 'pubmedurl';
1422 $cssClass = 'mw-magiclink-pmid';
1425 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1426 substr( $m[0], 0, 20 ) . '"' );
1428 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1429 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass );
1430 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1433 $space = self
::SPACE_NOT_NL
; # non-newline space
1434 $isbn = preg_replace( "/$space/", ' ', $isbn );
1435 $num = strtr( $isbn, array(
1440 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1441 return '<a href="' .
1442 htmlspecialchars( $titleObj->getLocalURL() ) .
1443 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1450 * Make a free external link, given a user-supplied URL
1452 * @param string $url
1454 * @return string HTML
1457 public function makeFreeExternalLink( $url ) {
1461 # The characters '<' and '>' (which were escaped by
1462 # removeHTMLtags()) should not be included in
1463 # URLs, per RFC 2396.
1465 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1466 $trail = substr( $url, $m2[0][1] ) . $trail;
1467 $url = substr( $url, 0, $m2[0][1] );
1470 # Move trailing punctuation to $trail
1472 # If there is no left bracket, then consider right brackets fair game too
1473 if ( strpos( $url, '(' ) === false ) {
1477 $urlRev = strrev( $url );
1478 $numSepChars = strspn( $urlRev, $sep );
1479 # Don't break a trailing HTML entity by moving the ; into $trail
1480 # This is in hot code, so use substr_compare to avoid having to
1481 # create a new string object for the comparison
1482 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0) {
1483 # more optimization: instead of running preg_match with a $
1484 # anchor, which can be slow, do the match on the reversed
1485 # string starting at the desired offset.
1486 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1487 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1491 if ( $numSepChars ) {
1492 $trail = substr( $url, -$numSepChars ) . $trail;
1493 $url = substr( $url, 0, -$numSepChars );
1496 $url = Sanitizer
::cleanUrl( $url );
1498 # Is this an external image?
1499 $text = $this->maybeMakeExternalImage( $url );
1500 if ( $text === false ) {
1501 # Not an image, make a link
1502 $text = Linker
::makeExternalLink( $url,
1503 $this->getConverterLanguage()->markNoConversion( $url, true ),
1505 $this->getExternalLinkAttribs( $url ) );
1506 # Register it in the output object...
1507 # Replace unnecessary URL escape codes with their equivalent characters
1508 $pasteurized = self
::normalizeLinkUrl( $url );
1509 $this->mOutput
->addExternalLink( $pasteurized );
1511 return $text . $trail;
1515 * Parse headers and return html
1519 * @param string $text
1523 public function doHeadings( $text ) {
1524 for ( $i = 6; $i >= 1; --$i ) {
1525 $h = str_repeat( '=', $i );
1526 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1532 * Replace single quotes with HTML markup
1535 * @param string $text
1537 * @return string The altered text
1539 public function doAllQuotes( $text ) {
1541 $lines = StringUtils
::explode( "\n", $text );
1542 foreach ( $lines as $line ) {
1543 $outtext .= $this->doQuotes( $line ) . "\n";
1545 $outtext = substr( $outtext, 0, -1 );
1550 * Helper function for doAllQuotes()
1552 * @param string $text
1556 public function doQuotes( $text ) {
1557 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1558 $countarr = count( $arr );
1559 if ( $countarr == 1 ) {
1563 // First, do some preliminary work. This may shift some apostrophes from
1564 // being mark-up to being text. It also counts the number of occurrences
1565 // of bold and italics mark-ups.
1568 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1569 $thislen = strlen( $arr[$i] );
1570 // If there are ever four apostrophes, assume the first is supposed to
1571 // be text, and the remaining three constitute mark-up for bold text.
1572 // (bug 13227: ''''foo'''' turns into ' ''' foo ' ''')
1573 if ( $thislen == 4 ) {
1574 $arr[$i - 1] .= "'";
1577 } elseif ( $thislen > 5 ) {
1578 // If there are more than 5 apostrophes in a row, assume they're all
1579 // text except for the last 5.
1580 // (bug 13227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1581 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1585 // Count the number of occurrences of bold and italics mark-ups.
1586 if ( $thislen == 2 ) {
1588 } elseif ( $thislen == 3 ) {
1590 } elseif ( $thislen == 5 ) {
1596 // If there is an odd number of both bold and italics, it is likely
1597 // that one of the bold ones was meant to be an apostrophe followed
1598 // by italics. Which one we cannot know for certain, but it is more
1599 // likely to be one that has a single-letter word before it.
1600 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1601 $firstsingleletterword = -1;
1602 $firstmultiletterword = -1;
1604 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1605 if ( strlen( $arr[$i] ) == 3 ) {
1606 $x1 = substr( $arr[$i - 1], -1 );
1607 $x2 = substr( $arr[$i - 1], -2, 1 );
1608 if ( $x1 === ' ' ) {
1609 if ( $firstspace == -1 ) {
1612 } elseif ( $x2 === ' ' ) {
1613 if ( $firstsingleletterword == -1 ) {
1614 $firstsingleletterword = $i;
1615 // if $firstsingleletterword is set, we don't
1616 // look at the other options, so we can bail early.
1620 if ( $firstmultiletterword == -1 ) {
1621 $firstmultiletterword = $i;
1627 // If there is a single-letter word, use it!
1628 if ( $firstsingleletterword > -1 ) {
1629 $arr[$firstsingleletterword] = "''";
1630 $arr[$firstsingleletterword - 1] .= "'";
1631 } elseif ( $firstmultiletterword > -1 ) {
1632 // If not, but there's a multi-letter word, use that one.
1633 $arr[$firstmultiletterword] = "''";
1634 $arr[$firstmultiletterword - 1] .= "'";
1635 } elseif ( $firstspace > -1 ) {
1636 // ... otherwise use the first one that has neither.
1637 // (notice that it is possible for all three to be -1 if, for example,
1638 // there is only one pentuple-apostrophe in the line)
1639 $arr[$firstspace] = "''";
1640 $arr[$firstspace - 1] .= "'";
1644 // Now let's actually convert our apostrophic mush to HTML!
1649 foreach ( $arr as $r ) {
1650 if ( ( $i %
2 ) == 0 ) {
1651 if ( $state === 'both' ) {
1657 $thislen = strlen( $r );
1658 if ( $thislen == 2 ) {
1659 if ( $state === 'i' ) {
1662 } elseif ( $state === 'bi' ) {
1665 } elseif ( $state === 'ib' ) {
1666 $output .= '</b></i><b>';
1668 } elseif ( $state === 'both' ) {
1669 $output .= '<b><i>' . $buffer . '</i>';
1671 } else { // $state can be 'b' or ''
1675 } elseif ( $thislen == 3 ) {
1676 if ( $state === 'b' ) {
1679 } elseif ( $state === 'bi' ) {
1680 $output .= '</i></b><i>';
1682 } elseif ( $state === 'ib' ) {
1685 } elseif ( $state === 'both' ) {
1686 $output .= '<i><b>' . $buffer . '</b>';
1688 } else { // $state can be 'i' or ''
1692 } elseif ( $thislen == 5 ) {
1693 if ( $state === 'b' ) {
1694 $output .= '</b><i>';
1696 } elseif ( $state === 'i' ) {
1697 $output .= '</i><b>';
1699 } elseif ( $state === 'bi' ) {
1700 $output .= '</i></b>';
1702 } elseif ( $state === 'ib' ) {
1703 $output .= '</b></i>';
1705 } elseif ( $state === 'both' ) {
1706 $output .= '<i><b>' . $buffer . '</b></i>';
1708 } else { // ($state == '')
1716 // Now close all remaining tags. Notice that the order is important.
1717 if ( $state === 'b' ||
$state === 'ib' ) {
1720 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1723 if ( $state === 'bi' ) {
1726 // There might be lonely ''''', so make sure we have a buffer
1727 if ( $state === 'both' && $buffer ) {
1728 $output .= '<b><i>' . $buffer . '</i></b>';
1734 * Replace external links (REL)
1736 * Note: this is all very hackish and the order of execution matters a lot.
1737 * Make sure to run tests/parserTests.php if you change this code.
1741 * @param string $text
1743 * @throws MWException
1746 public function replaceExternalLinks( $text ) {
1748 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1749 if ( $bits === false ) {
1750 throw new MWException( "PCRE needs to be compiled with "
1751 . "--enable-unicode-properties in order for MediaWiki to function" );
1753 $s = array_shift( $bits );
1756 while ( $i < count( $bits ) ) {
1759 $text = $bits[$i++
];
1760 $trail = $bits[$i++
];
1762 # The characters '<' and '>' (which were escaped by
1763 # removeHTMLtags()) should not be included in
1764 # URLs, per RFC 2396.
1766 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1767 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1768 $url = substr( $url, 0, $m2[0][1] );
1771 # If the link text is an image URL, replace it with an <img> tag
1772 # This happened by accident in the original parser, but some people used it extensively
1773 $img = $this->maybeMakeExternalImage( $text );
1774 if ( $img !== false ) {
1780 # Set linktype for CSS - if URL==text, link is essentially free
1781 $linktype = ( $text === $url ) ?
'free' : 'text';
1783 # No link text, e.g. [http://domain.tld/some.link]
1784 if ( $text == '' ) {
1786 $langObj = $this->getTargetLanguage();
1787 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1788 $linktype = 'autonumber';
1790 # Have link text, e.g. [http://domain.tld/some.link text]s
1792 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1795 $text = $this->getConverterLanguage()->markNoConversion( $text );
1797 $url = Sanitizer
::cleanUrl( $url );
1799 # Use the encoded URL
1800 # This means that users can paste URLs directly into the text
1801 # Funny characters like ö aren't valid in URLs anyway
1802 # This was changed in August 2004
1803 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1804 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1806 # Register link in the output object.
1807 # Replace unnecessary URL escape codes with the referenced character
1808 # This prevents spammers from hiding links from the filters
1809 $pasteurized = self
::normalizeLinkUrl( $url );
1810 $this->mOutput
->addExternalLink( $pasteurized );
1817 * Get the rel attribute for a particular external link.
1820 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1821 * nofollow if appropriate
1822 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1823 * @return string|null Rel attribute for $url
1825 public static function getExternalLinkRel( $url = false, $title = null ) {
1826 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1827 $ns = $title ?
$title->getNamespace() : false;
1828 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1829 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1837 * Get an associative array of additional HTML attributes appropriate for a
1838 * particular external link. This currently may include rel => nofollow
1839 * (depending on configuration, namespace, and the URL's domain) and/or a
1840 * target attribute (depending on configuration).
1842 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1843 * nofollow if appropriate
1844 * @return array Associative array of HTML attributes
1846 public function getExternalLinkAttribs( $url = false ) {
1848 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1850 if ( $this->mOptions
->getExternalLinkTarget() ) {
1851 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1857 * Replace unusual escape codes in a URL with their equivalent characters
1859 * @deprecated since 1.24, use normalizeLinkUrl
1860 * @param string $url
1863 public static function replaceUnusualEscapes( $url ) {
1864 wfDeprecated( __METHOD__
, '1.24' );
1865 return self
::normalizeLinkUrl( $url );
1869 * Replace unusual escape codes in a URL with their equivalent characters
1871 * This generally follows the syntax defined in RFC 3986, with special
1872 * consideration for HTTP query strings.
1874 * @param string $url
1877 public static function normalizeLinkUrl( $url ) {
1878 # First, make sure unsafe characters are encoded
1879 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
1881 return rawurlencode( $m[0] );
1887 $end = strlen( $url );
1889 # Fragment part - 'fragment'
1890 $start = strpos( $url, '#' );
1891 if ( $start !== false && $start < $end ) {
1892 $ret = self
::normalizeUrlComponent(
1893 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
1897 # Query part - 'query' minus &=+;
1898 $start = strpos( $url, '?' );
1899 if ( $start !== false && $start < $end ) {
1900 $ret = self
::normalizeUrlComponent(
1901 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
1905 # Scheme and path part - 'pchar'
1906 # (we assume no userinfo or encoded colons in the host)
1907 $ret = self
::normalizeUrlComponent(
1908 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
1913 private static function normalizeUrlComponent( $component, $unsafe ) {
1914 $callback = function ( $matches ) use ( $unsafe ) {
1915 $char = urldecode( $matches[0] );
1916 $ord = ord( $char );
1917 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
1921 # Leave it escaped, but use uppercase for a-f
1922 return strtoupper( $matches[0] );
1925 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
1929 * make an image if it's allowed, either through the global
1930 * option, through the exception, or through the on-wiki whitelist
1932 * @param string $url
1936 private function maybeMakeExternalImage( $url ) {
1937 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1938 $imagesexception = !empty( $imagesfrom );
1940 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1941 if ( $imagesexception && is_array( $imagesfrom ) ) {
1942 $imagematch = false;
1943 foreach ( $imagesfrom as $match ) {
1944 if ( strpos( $url, $match ) === 0 ) {
1949 } elseif ( $imagesexception ) {
1950 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1952 $imagematch = false;
1955 if ( $this->mOptions
->getAllowExternalImages()
1956 ||
( $imagesexception && $imagematch )
1958 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1960 $text = Linker
::makeExternalImage( $url );
1963 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1964 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
1966 $whitelist = explode(
1968 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
1971 foreach ( $whitelist as $entry ) {
1972 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1973 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1976 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1977 # Image matches a whitelist entry
1978 $text = Linker
::makeExternalImage( $url );
1987 * Process [[ ]] wikilinks
1991 * @return string Processed text
1995 public function replaceInternalLinks( $s ) {
1996 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
2001 * Process [[ ]] wikilinks (RIL)
2003 * @throws MWException
2004 * @return LinkHolderArray
2008 public function replaceInternalLinks2( &$s ) {
2009 global $wgExtraInterlanguageLinkPrefixes;
2011 wfProfileIn( __METHOD__
. '-setup' );
2012 static $tc = false, $e1, $e1_img;
2013 # the % is needed to support urlencoded titles as well
2015 $tc = Title
::legalChars() . '#%';
2016 # Match a link having the form [[namespace:link|alternate]]trail
2017 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2018 # Match cases where there is no "]]", which might still be images
2019 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2022 $holders = new LinkHolderArray( $this );
2024 # split the entire text string on occurrences of [[
2025 $a = StringUtils
::explode( '[[', ' ' . $s );
2026 # get the first element (all text up to first [[), and remove the space we added
2029 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2030 $s = substr( $s, 1 );
2032 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2034 if ( $useLinkPrefixExtension ) {
2035 # Match the end of a line for a word that's not followed by whitespace,
2036 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2038 $charset = $wgContLang->linkPrefixCharset();
2039 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2042 if ( is_null( $this->mTitle
) ) {
2043 wfProfileOut( __METHOD__
. '-setup' );
2044 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
2046 $nottalk = !$this->mTitle
->isTalkPage();
2048 if ( $useLinkPrefixExtension ) {
2050 if ( preg_match( $e2, $s, $m ) ) {
2051 $first_prefix = $m[2];
2053 $first_prefix = false;
2059 $useSubpages = $this->areSubpagesAllowed();
2060 wfProfileOut( __METHOD__
. '-setup' );
2062 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
2063 # Loop for each link
2064 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2065 // @codingStandardsIgnoreStart
2067 # Check for excessive memory usage
2068 if ( $holders->isBig() ) {
2070 # Do the existence check, replace the link holders and clear the array
2071 $holders->replace( $s );
2075 if ( $useLinkPrefixExtension ) {
2076 wfProfileIn( __METHOD__
. '-prefixhandling' );
2077 if ( preg_match( $e2, $s, $m ) ) {
2084 if ( $first_prefix ) {
2085 $prefix = $first_prefix;
2086 $first_prefix = false;
2088 wfProfileOut( __METHOD__
. '-prefixhandling' );
2091 $might_be_img = false;
2093 wfProfileIn( __METHOD__
. "-e1" );
2094 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2096 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2097 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2098 # the real problem is with the $e1 regex
2101 # Still some problems for cases where the ] is meant to be outside punctuation,
2102 # and no image is in sight. See bug 2095.
2105 && substr( $m[3], 0, 1 ) === ']'
2106 && strpos( $text, '[' ) !== false
2108 $text .= ']'; # so that replaceExternalLinks($text) works later
2109 $m[3] = substr( $m[3], 1 );
2111 # fix up urlencoded title texts
2112 if ( strpos( $m[1], '%' ) !== false ) {
2113 # Should anchors '#' also be rejected?
2114 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) );
2117 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2118 # Invalid, but might be an image with a link in its caption
2119 $might_be_img = true;
2121 if ( strpos( $m[1], '%' ) !== false ) {
2122 $m[1] = rawurldecode( $m[1] );
2125 } else { # Invalid form; output directly
2126 $s .= $prefix . '[[' . $line;
2127 wfProfileOut( __METHOD__
. "-e1" );
2130 wfProfileOut( __METHOD__
. "-e1" );
2131 wfProfileIn( __METHOD__
. "-misc" );
2135 # Don't allow internal links to pages containing
2136 # PROTO: where PROTO is a valid URL protocol; these
2137 # should be external links.
2138 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2139 $s .= $prefix . '[[' . $line;
2140 wfProfileOut( __METHOD__
. "-misc" );
2144 # Make subpage if necessary
2145 if ( $useSubpages ) {
2146 $link = $this->maybeDoSubpageLink( $origLink, $text );
2151 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2153 # Strip off leading ':'
2154 $link = substr( $link, 1 );
2157 wfProfileOut( __METHOD__
. "-misc" );
2158 wfProfileIn( __METHOD__
. "-title" );
2159 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
2160 if ( $nt === null ) {
2161 $s .= $prefix . '[[' . $line;
2162 wfProfileOut( __METHOD__
. "-title" );
2166 $ns = $nt->getNamespace();
2167 $iw = $nt->getInterwiki();
2168 wfProfileOut( __METHOD__
. "-title" );
2170 if ( $might_be_img ) { # if this is actually an invalid link
2171 wfProfileIn( __METHOD__
. "-might_be_img" );
2172 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2175 # look at the next 'line' to see if we can close it there
2177 $next_line = $a->current();
2178 if ( $next_line === false ||
$next_line === null ) {
2181 $m = explode( ']]', $next_line, 3 );
2182 if ( count( $m ) == 3 ) {
2183 # the first ]] closes the inner link, the second the image
2185 $text .= "[[{$m[0]}]]{$m[1]}";
2188 } elseif ( count( $m ) == 2 ) {
2189 # if there's exactly one ]] that's fine, we'll keep looking
2190 $text .= "[[{$m[0]}]]{$m[1]}";
2192 # if $next_line is invalid too, we need look no further
2193 $text .= '[[' . $next_line;
2198 # we couldn't find the end of this imageLink, so output it raw
2199 # but don't ignore what might be perfectly normal links in the text we've examined
2200 $holders->merge( $this->replaceInternalLinks2( $text ) );
2201 $s .= "{$prefix}[[$link|$text";
2202 # note: no $trail, because without an end, there *is* no trail
2203 wfProfileOut( __METHOD__
. "-might_be_img" );
2206 } else { # it's not an image, so output it raw
2207 $s .= "{$prefix}[[$link|$text";
2208 # note: no $trail, because without an end, there *is* no trail
2209 wfProfileOut( __METHOD__
. "-might_be_img" );
2212 wfProfileOut( __METHOD__
. "-might_be_img" );
2215 $wasblank = ( $text == '' );
2219 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
2220 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2221 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2222 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2223 $text = $this->doQuotes( $text );
2226 # Link not escaped by : , create the various objects
2227 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2229 wfProfileIn( __METHOD__
. "-interwiki" );
2231 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2232 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2233 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2236 # Bug 24502: filter duplicates
2237 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2238 $this->mLangLinkLanguages
[$iw] = true;
2239 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2242 $s = rtrim( $s . $prefix );
2243 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2244 wfProfileOut( __METHOD__
. "-interwiki" );
2247 wfProfileOut( __METHOD__
. "-interwiki" );
2249 if ( $ns == NS_FILE
) {
2250 wfProfileIn( __METHOD__
. "-image" );
2251 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2253 # if no parameters were passed, $text
2254 # becomes something like "File:Foo.png",
2255 # which we don't want to pass on to the
2259 # recursively parse links inside the image caption
2260 # actually, this will parse them in any other parameters, too,
2261 # but it might be hard to fix that, and it doesn't matter ATM
2262 $text = $this->replaceExternalLinks( $text );
2263 $holders->merge( $this->replaceInternalLinks2( $text ) );
2265 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2266 $s .= $prefix . $this->armorLinks(
2267 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2269 $s .= $prefix . $trail;
2271 wfProfileOut( __METHOD__
. "-image" );
2275 if ( $ns == NS_CATEGORY
) {
2276 wfProfileIn( __METHOD__
. "-category" );
2277 $s = rtrim( $s . "\n" ); # bug 87
2280 $sortkey = $this->getDefaultSort();
2284 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2285 $sortkey = str_replace( "\n", '', $sortkey );
2286 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2287 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2290 * Strip the whitespace Category links produce, see bug 87
2292 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2294 wfProfileOut( __METHOD__
. "-category" );
2299 # Self-link checking. For some languages, variants of the title are checked in
2300 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2301 # for linking to a different variant.
2302 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2303 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2307 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2308 # @todo FIXME: Should do batch file existence checks, see comment below
2309 if ( $ns == NS_MEDIA
) {
2310 wfProfileIn( __METHOD__
. "-media" );
2311 # Give extensions a chance to select the file revision for us
2314 Hooks
::run( 'BeforeParserFetchFileAndTitle',
2315 array( $this, $nt, &$options, &$descQuery ) );
2316 # Fetch and register the file (file title may be different via hooks)
2317 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2318 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2319 $s .= $prefix . $this->armorLinks(
2320 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2321 wfProfileOut( __METHOD__
. "-media" );
2325 wfProfileIn( __METHOD__
. "-always_known" );
2326 # Some titles, such as valid special pages or files in foreign repos, should
2327 # be shown as bluelinks even though they're not included in the page table
2329 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2330 # batch file existence checks for NS_FILE and NS_MEDIA
2331 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2332 $this->mOutput
->addLink( $nt );
2333 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2335 # Links will be added to the output link list after checking
2336 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2338 wfProfileOut( __METHOD__
. "-always_known" );
2344 * Render a forced-blue link inline; protect against double expansion of
2345 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2346 * Since this little disaster has to split off the trail text to avoid
2347 * breaking URLs in the following text without breaking trails on the
2348 * wiki links, it's been made into a horrible function.
2351 * @param string $text
2352 * @param array|string $query
2353 * @param string $trail
2354 * @param string $prefix
2355 * @return string HTML-wikitext mix oh yuck
2357 public function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2358 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2360 if ( is_string( $query ) ) {
2361 $query = wfCgiToArray( $query );
2363 if ( $text == '' ) {
2364 $text = htmlspecialchars( $nt->getPrefixedText() );
2367 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2369 return $this->armorLinks( $link ) . $trail;
2373 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2374 * going to go through further parsing steps before inline URL expansion.
2376 * Not needed quite as much as it used to be since free links are a bit
2377 * more sensible these days. But bracketed links are still an issue.
2379 * @param string $text More-or-less HTML
2380 * @return string Less-or-more HTML with NOPARSE bits
2382 public function armorLinks( $text ) {
2383 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2384 "{$this->mUniqPrefix}NOPARSE$1", $text );
2388 * Return true if subpage links should be expanded on this page.
2391 public function areSubpagesAllowed() {
2392 # Some namespaces don't allow subpages
2393 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2397 * Handle link to subpage if necessary
2399 * @param string $target The source of the link
2400 * @param string &$text The link text, modified as necessary
2401 * @return string The full name of the link
2404 public function maybeDoSubpageLink( $target, &$text ) {
2405 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2409 * Used by doBlockLevels()
2414 public function closeParagraph() {
2416 if ( $this->mLastSection
!= '' ) {
2417 $result = '</' . $this->mLastSection
. ">\n";
2419 $this->mInPre
= false;
2420 $this->mLastSection
= '';
2425 * getCommon() returns the length of the longest common substring
2426 * of both arguments, starting at the beginning of both.
2429 * @param string $st1
2430 * @param string $st2
2434 public function getCommon( $st1, $st2 ) {
2435 $fl = strlen( $st1 );
2436 $shorter = strlen( $st2 );
2437 if ( $fl < $shorter ) {
2441 for ( $i = 0; $i < $shorter; ++
$i ) {
2442 if ( $st1[$i] != $st2[$i] ) {
2450 * These next three functions open, continue, and close the list
2451 * element appropriate to the prefix character passed into them.
2454 * @param string $char
2458 public function openList( $char ) {
2459 $result = $this->closeParagraph();
2461 if ( '*' === $char ) {
2462 $result .= "<ul><li>";
2463 } elseif ( '#' === $char ) {
2464 $result .= "<ol><li>";
2465 } elseif ( ':' === $char ) {
2466 $result .= "<dl><dd>";
2467 } elseif ( ';' === $char ) {
2468 $result .= "<dl><dt>";
2469 $this->mDTopen
= true;
2471 $result = '<!-- ERR 1 -->';
2479 * @param string $char
2484 public function nextItem( $char ) {
2485 if ( '*' === $char ||
'#' === $char ) {
2486 return "</li>\n<li>";
2487 } elseif ( ':' === $char ||
';' === $char ) {
2489 if ( $this->mDTopen
) {
2492 if ( ';' === $char ) {
2493 $this->mDTopen
= true;
2494 return $close . '<dt>';
2496 $this->mDTopen
= false;
2497 return $close . '<dd>';
2500 return '<!-- ERR 2 -->';
2505 * @param string $char
2510 public function closeList( $char ) {
2511 if ( '*' === $char ) {
2512 $text = "</li></ul>";
2513 } elseif ( '#' === $char ) {
2514 $text = "</li></ol>";
2515 } elseif ( ':' === $char ) {
2516 if ( $this->mDTopen
) {
2517 $this->mDTopen
= false;
2518 $text = "</dt></dl>";
2520 $text = "</dd></dl>";
2523 return '<!-- ERR 3 -->';
2530 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2532 * @param string $text
2533 * @param bool $linestart Whether or not this is at the start of a line.
2535 * @return string The lists rendered as HTML
2537 public function doBlockLevels( $text, $linestart ) {
2539 # Parsing through the text line by line. The main thing
2540 # happening here is handling of block-level elements p, pre,
2541 # and making lists from lines starting with * # : etc.
2543 $textLines = StringUtils
::explode( "\n", $text );
2545 $lastPrefix = $output = '';
2546 $this->mDTopen
= $inBlockElem = false;
2548 $paragraphStack = false;
2549 $inBlockquote = false;
2551 foreach ( $textLines as $oLine ) {
2553 if ( !$linestart ) {
2563 $lastPrefixLength = strlen( $lastPrefix );
2564 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2565 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2566 # If not in a <pre> element, scan for and figure out what prefixes are there.
2567 if ( !$this->mInPre
) {
2568 # Multiple prefixes may abut each other for nested lists.
2569 $prefixLength = strspn( $oLine, '*#:;' );
2570 $prefix = substr( $oLine, 0, $prefixLength );
2573 # ; and : are both from definition-lists, so they're equivalent
2574 # for the purposes of determining whether or not we need to open/close
2576 $prefix2 = str_replace( ';', ':', $prefix );
2577 $t = substr( $oLine, $prefixLength );
2578 $this->mInPre
= (bool)$preOpenMatch;
2580 # Don't interpret any other prefixes in preformatted text
2582 $prefix = $prefix2 = '';
2587 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2588 # Same as the last item, so no need to deal with nesting or opening stuff
2589 $output .= $this->nextItem( substr( $prefix, -1 ) );
2590 $paragraphStack = false;
2592 if ( substr( $prefix, -1 ) === ';' ) {
2593 # The one nasty exception: definition lists work like this:
2594 # ; title : definition text
2595 # So we check for : in the remainder text to split up the
2596 # title and definition, without b0rking links.
2598 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2600 $output .= $term . $this->nextItem( ':' );
2603 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2604 # We need to open or close prefixes, or both.
2606 # Either open or close a level...
2607 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2608 $paragraphStack = false;
2610 # Close all the prefixes which aren't shared.
2611 while ( $commonPrefixLength < $lastPrefixLength ) {
2612 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2613 --$lastPrefixLength;
2616 # Continue the current prefix if appropriate.
2617 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2618 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2621 # Open prefixes where appropriate.
2622 if ( $lastPrefix && $prefixLength > $commonPrefixLength ) {
2625 while ( $prefixLength > $commonPrefixLength ) {
2626 $char = substr( $prefix, $commonPrefixLength, 1 );
2627 $output .= $this->openList( $char );
2629 if ( ';' === $char ) {
2630 # @todo FIXME: This is dupe of code above
2631 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2633 $output .= $term . $this->nextItem( ':' );
2636 ++
$commonPrefixLength;
2638 if ( !$prefixLength && $lastPrefix ) {
2641 $lastPrefix = $prefix2;
2644 # If we have no prefixes, go to paragraph mode.
2645 if ( 0 == $prefixLength ) {
2646 wfProfileIn( __METHOD__
. "-paragraph" );
2647 # No prefix (not in list)--go to paragraph mode
2648 # XXX: use a stack for nestable elements like span, table and div
2649 $openmatch = preg_match(
2650 '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|'
2651 . '<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS',
2654 $closematch = preg_match(
2655 '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'
2656 . '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|<\\/mw:|'
2657 . $this->mUniqPrefix
2658 . '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS',
2662 if ( $openmatch ||
$closematch ) {
2663 $paragraphStack = false;
2664 # @todo bug 5718: paragraph closed
2665 $output .= $this->closeParagraph();
2666 if ( $preOpenMatch && !$preCloseMatch ) {
2667 $this->mInPre
= true;
2670 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t, $bqMatch, PREG_OFFSET_CAPTURE
, $bqOffset ) ) {
2671 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
2672 $bqOffset = $bqMatch[0][1] +
strlen( $bqMatch[0][0] );
2674 $inBlockElem = !$closematch;
2675 } elseif ( !$inBlockElem && !$this->mInPre
) {
2676 if ( ' ' == substr( $t, 0, 1 )
2677 && ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' )
2681 if ( $this->mLastSection
!== 'pre' ) {
2682 $paragraphStack = false;
2683 $output .= $this->closeParagraph() . '<pre>';
2684 $this->mLastSection
= 'pre';
2686 $t = substr( $t, 1 );
2689 if ( trim( $t ) === '' ) {
2690 if ( $paragraphStack ) {
2691 $output .= $paragraphStack . '<br />';
2692 $paragraphStack = false;
2693 $this->mLastSection
= 'p';
2695 if ( $this->mLastSection
!== 'p' ) {
2696 $output .= $this->closeParagraph();
2697 $this->mLastSection
= '';
2698 $paragraphStack = '<p>';
2700 $paragraphStack = '</p><p>';
2704 if ( $paragraphStack ) {
2705 $output .= $paragraphStack;
2706 $paragraphStack = false;
2707 $this->mLastSection
= 'p';
2708 } elseif ( $this->mLastSection
!== 'p' ) {
2709 $output .= $this->closeParagraph() . '<p>';
2710 $this->mLastSection
= 'p';
2715 wfProfileOut( __METHOD__
. "-paragraph" );
2717 # somewhere above we forget to get out of pre block (bug 785)
2718 if ( $preCloseMatch && $this->mInPre
) {
2719 $this->mInPre
= false;
2721 if ( $paragraphStack === false ) {
2723 if ( $prefixLength === 0 ) {
2728 while ( $prefixLength ) {
2729 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2731 if ( !$prefixLength ) {
2735 if ( $this->mLastSection
!= '' ) {
2736 $output .= '</' . $this->mLastSection
. '>';
2737 $this->mLastSection
= '';
2744 * Split up a string on ':', ignoring any occurrences inside tags
2745 * to prevent illegal overlapping.
2747 * @param string $str The string to split
2748 * @param string &$before Set to everything before the ':'
2749 * @param string &$after Set to everything after the ':'
2750 * @throws MWException
2751 * @return string The position of the ':', or false if none found
2753 public function findColonNoLinks( $str, &$before, &$after ) {
2755 $pos = strpos( $str, ':' );
2756 if ( $pos === false ) {
2761 $lt = strpos( $str, '<' );
2762 if ( $lt === false ||
$lt > $pos ) {
2763 # Easy; no tag nesting to worry about
2764 $before = substr( $str, 0, $pos );
2765 $after = substr( $str, $pos +
1 );
2769 # Ugly state machine to walk through avoiding tags.
2770 $state = self
::COLON_STATE_TEXT
;
2772 $len = strlen( $str );
2773 for ( $i = 0; $i < $len; $i++
) {
2777 # (Using the number is a performance hack for common cases)
2778 case 0: # self::COLON_STATE_TEXT:
2781 # Could be either a <start> tag or an </end> tag
2782 $state = self
::COLON_STATE_TAGSTART
;
2785 if ( $stack == 0 ) {
2787 $before = substr( $str, 0, $i );
2788 $after = substr( $str, $i +
1 );
2791 # Embedded in a tag; don't break it.
2794 # Skip ahead looking for something interesting
2795 $colon = strpos( $str, ':', $i );
2796 if ( $colon === false ) {
2797 # Nothing else interesting
2800 $lt = strpos( $str, '<', $i );
2801 if ( $stack === 0 ) {
2802 if ( $lt === false ||
$colon < $lt ) {
2804 $before = substr( $str, 0, $colon );
2805 $after = substr( $str, $colon +
1 );
2809 if ( $lt === false ) {
2810 # Nothing else interesting to find; abort!
2811 # We're nested, but there's no close tags left. Abort!
2814 # Skip ahead to next tag start
2816 $state = self
::COLON_STATE_TAGSTART
;
2819 case 1: # self::COLON_STATE_TAG:
2824 $state = self
::COLON_STATE_TEXT
;
2827 # Slash may be followed by >?
2828 $state = self
::COLON_STATE_TAGSLASH
;
2834 case 2: # self::COLON_STATE_TAGSTART:
2837 $state = self
::COLON_STATE_CLOSETAG
;
2840 $state = self
::COLON_STATE_COMMENT
;
2843 # Illegal early close? This shouldn't happen D:
2844 $state = self
::COLON_STATE_TEXT
;
2847 $state = self
::COLON_STATE_TAG
;
2850 case 3: # self::COLON_STATE_CLOSETAG:
2855 wfDebug( __METHOD__
. ": Invalid input; too many close tags\n" );
2858 $state = self
::COLON_STATE_TEXT
;
2861 case self
::COLON_STATE_TAGSLASH
:
2863 # Yes, a self-closed tag <blah/>
2864 $state = self
::COLON_STATE_TEXT
;
2866 # Probably we're jumping the gun, and this is an attribute
2867 $state = self
::COLON_STATE_TAG
;
2870 case 5: # self::COLON_STATE_COMMENT:
2872 $state = self
::COLON_STATE_COMMENTDASH
;
2875 case self
::COLON_STATE_COMMENTDASH
:
2877 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2879 $state = self
::COLON_STATE_COMMENT
;
2882 case self
::COLON_STATE_COMMENTDASHDASH
:
2884 $state = self
::COLON_STATE_TEXT
;
2886 $state = self
::COLON_STATE_COMMENT
;
2890 throw new MWException( "State machine error in " . __METHOD__
);
2894 wfDebug( __METHOD__
. ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2901 * Return value of a magic variable (like PAGENAME)
2906 * @param bool|PPFrame $frame
2908 * @throws MWException
2911 public function getVariableValue( $index, $frame = false ) {
2912 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2913 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2915 if ( is_null( $this->mTitle
) ) {
2916 // If no title set, bad things are going to happen
2917 // later. Title should always be set since this
2918 // should only be called in the middle of a parse
2919 // operation (but the unit-tests do funky stuff)
2920 throw new MWException( __METHOD__
. ' Should only be '
2921 . ' called while parsing (no title set)' );
2925 * Some of these require message or data lookups and can be
2926 * expensive to check many times.
2928 if ( Hooks
::run( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2929 if ( isset( $this->mVarCache
[$index] ) ) {
2930 return $this->mVarCache
[$index];
2934 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2935 Hooks
::run( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2937 $pageLang = $this->getFunctionLang();
2943 case 'currentmonth':
2944 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ) );
2946 case 'currentmonth1':
2947 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2949 case 'currentmonthname':
2950 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2952 case 'currentmonthnamegen':
2953 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2955 case 'currentmonthabbrev':
2956 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2959 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ) );
2962 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ) );
2965 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ) );
2968 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2970 case 'localmonthname':
2971 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2973 case 'localmonthnamegen':
2974 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2976 case 'localmonthabbrev':
2977 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2980 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ) );
2983 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ) );
2986 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2989 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2991 case 'fullpagename':
2992 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2994 case 'fullpagenamee':
2995 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2998 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
3000 case 'subpagenamee':
3001 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
3003 case 'rootpagename':
3004 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
3006 case 'rootpagenamee':
3007 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
3010 $this->mTitle
->getRootText()
3013 case 'basepagename':
3014 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
3016 case 'basepagenamee':
3017 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
3020 $this->mTitle
->getBaseText()
3023 case 'talkpagename':
3024 if ( $this->mTitle
->canTalk() ) {
3025 $talkPage = $this->mTitle
->getTalkPage();
3026 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
3031 case 'talkpagenamee':
3032 if ( $this->mTitle
->canTalk() ) {
3033 $talkPage = $this->mTitle
->getTalkPage();
3034 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
3039 case 'subjectpagename':
3040 $subjPage = $this->mTitle
->getSubjectPage();
3041 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
3043 case 'subjectpagenamee':
3044 $subjPage = $this->mTitle
->getSubjectPage();
3045 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
3047 case 'pageid': // requested in bug 23427
3048 $pageid = $this->getTitle()->getArticleID();
3049 if ( $pageid == 0 ) {
3050 # 0 means the page doesn't exist in the database,
3051 # which means the user is previewing a new page.
3052 # The vary-revision flag must be set, because the magic word
3053 # will have a different value once the page is saved.
3054 $this->mOutput
->setFlag( 'vary-revision' );
3055 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
3057 $value = $pageid ?
$pageid : null;
3060 # Let the edit saving system know we should parse the page
3061 # *after* a revision ID has been assigned.
3062 $this->mOutput
->setFlag( 'vary-revision' );
3063 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
3064 $value = $this->mRevisionId
;
3067 # Let the edit saving system know we should parse the page
3068 # *after* a revision ID has been assigned. This is for null edits.
3069 $this->mOutput
->setFlag( 'vary-revision' );
3070 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
3071 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
3073 case 'revisionday2':
3074 # Let the edit saving system know we should parse the page
3075 # *after* a revision ID has been assigned. This is for null edits.
3076 $this->mOutput
->setFlag( 'vary-revision' );
3077 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
3078 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
3080 case 'revisionmonth':
3081 # Let the edit saving system know we should parse the page
3082 # *after* a revision ID has been assigned. This is for null edits.
3083 $this->mOutput
->setFlag( 'vary-revision' );
3084 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
3085 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
3087 case 'revisionmonth1':
3088 # Let the edit saving system know we should parse the page
3089 # *after* a revision ID has been assigned. This is for null edits.
3090 $this->mOutput
->setFlag( 'vary-revision' );
3091 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
3092 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
3094 case 'revisionyear':
3095 # Let the edit saving system know we should parse the page
3096 # *after* a revision ID has been assigned. This is for null edits.
3097 $this->mOutput
->setFlag( 'vary-revision' );
3098 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
3099 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
3101 case 'revisiontimestamp':
3102 # Let the edit saving system know we should parse the page
3103 # *after* a revision ID has been assigned. This is for null edits.
3104 $this->mOutput
->setFlag( 'vary-revision' );
3105 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
3106 $value = $this->getRevisionTimestamp();
3108 case 'revisionuser':
3109 # Let the edit saving system know we should parse the page
3110 # *after* a revision ID has been assigned. This is for null edits.
3111 $this->mOutput
->setFlag( 'vary-revision' );
3112 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
3113 $value = $this->getRevisionUser();
3115 case 'revisionsize':
3116 # Let the edit saving system know we should parse the page
3117 # *after* a revision ID has been assigned. This is for null edits.
3118 $this->mOutput
->setFlag( 'vary-revision' );
3119 wfDebug( __METHOD__
. ": {{REVISIONSIZE}} used, setting vary-revision...\n" );
3120 $value = $this->getRevisionSize();
3123 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3126 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3128 case 'namespacenumber':
3129 $value = $this->mTitle
->getNamespace();
3132 $value = $this->mTitle
->canTalk()
3133 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
3137 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
3139 case 'subjectspace':
3140 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
3142 case 'subjectspacee':
3143 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
3145 case 'currentdayname':
3146 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
3149 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
3152 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
3155 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
3158 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3159 # int to remove the padding
3160 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
3163 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
3165 case 'localdayname':
3166 $value = $pageLang->getWeekdayName(
3167 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
3171 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
3174 $value = $pageLang->time(
3175 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
3181 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
3184 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3185 # int to remove the padding
3186 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
3189 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
3191 case 'numberofarticles':
3192 $value = $pageLang->formatNum( SiteStats
::articles() );
3194 case 'numberoffiles':
3195 $value = $pageLang->formatNum( SiteStats
::images() );
3197 case 'numberofusers':
3198 $value = $pageLang->formatNum( SiteStats
::users() );
3200 case 'numberofactiveusers':
3201 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
3203 case 'numberofpages':
3204 $value = $pageLang->formatNum( SiteStats
::pages() );
3206 case 'numberofadmins':
3207 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
3209 case 'numberofedits':
3210 $value = $pageLang->formatNum( SiteStats
::edits() );
3212 case 'currenttimestamp':
3213 $value = wfTimestamp( TS_MW
, $ts );
3215 case 'localtimestamp':
3216 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
3218 case 'currentversion':
3219 $value = SpecialVersion
::getVersion();
3222 return $wgArticlePath;
3228 return $wgServerName;
3230 return $wgScriptPath;
3232 return $wgStylePath;
3233 case 'directionmark':
3234 return $pageLang->getDirMark();
3235 case 'contentlanguage':
3236 global $wgLanguageCode;
3237 return $wgLanguageCode;
3238 case 'cascadingsources':
3239 $value = CoreParserFunctions
::cascadingsources( $this );
3244 'ParserGetVariableValueSwitch',
3245 array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame )
3252 $this->mVarCache
[$index] = $value;
3259 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3263 public function initialiseVariables() {
3264 $variableIDs = MagicWord
::getVariableIDs();
3265 $substIDs = MagicWord
::getSubstIDs();
3267 $this->mVariables
= new MagicWordArray( $variableIDs );
3268 $this->mSubstWords
= new MagicWordArray( $substIDs );
3272 * Preprocess some wikitext and return the document tree.
3273 * This is the ghost of replace_variables().
3275 * @param string $text The text to parse
3276 * @param int $flags Bitwise combination of:
3277 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
3278 * included. Default is to assume a direct page view.
3280 * The generated DOM tree must depend only on the input text and the flags.
3281 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3283 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3284 * change in the DOM tree for a given text, must be passed through the section identifier
3285 * in the section edit link and thus back to extractSections().
3287 * The output of this function is currently only cached in process memory, but a persistent
3288 * cache may be implemented at a later date which takes further advantage of these strict
3289 * dependency requirements.
3293 public function preprocessToDom( $text, $flags = 0 ) {
3294 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3299 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3305 public static function splitWhitespace( $s ) {
3306 $ltrimmed = ltrim( $s );
3307 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3308 $trimmed = rtrim( $ltrimmed );
3309 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3311 $w2 = substr( $ltrimmed, -$diff );
3315 return array( $w1, $trimmed, $w2 );
3319 * Replace magic variables, templates, and template arguments
3320 * with the appropriate text. Templates are substituted recursively,
3321 * taking care to avoid infinite loops.
3323 * Note that the substitution depends on value of $mOutputType:
3324 * self::OT_WIKI: only {{subst:}} templates
3325 * self::OT_PREPROCESS: templates but not extension tags
3326 * self::OT_HTML: all templates and extension tags
3328 * @param string $text The text to transform
3329 * @param bool|PPFrame $frame Object describing the arguments passed to the
3330 * template. Arguments may also be provided as an associative array, as
3331 * was the usual case before MW1.12. Providing arguments this way may be
3332 * useful for extensions wishing to perform variable replacement
3334 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3335 * double-brace expansion.
3338 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3339 # Is there any text? Also, Prevent too big inclusions!
3340 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3344 if ( $frame === false ) {
3345 $frame = $this->getPreprocessor()->newFrame();
3346 } elseif ( !( $frame instanceof PPFrame
) ) {
3347 wfDebug( __METHOD__
. " called using plain parameters instead of "
3348 . "a PPFrame instance. Creating custom frame.\n" );
3349 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3352 $dom = $this->preprocessToDom( $text );
3353 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3354 $text = $frame->expand( $dom, $flags );
3360 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3362 * @param array $args
3366 public static function createAssocArgs( $args ) {
3367 $assocArgs = array();
3369 foreach ( $args as $arg ) {
3370 $eqpos = strpos( $arg, '=' );
3371 if ( $eqpos === false ) {
3372 $assocArgs[$index++
] = $arg;
3374 $name = trim( substr( $arg, 0, $eqpos ) );
3375 $value = trim( substr( $arg, $eqpos +
1 ) );
3376 if ( $value === false ) {
3379 if ( $name !== false ) {
3380 $assocArgs[$name] = $value;
3389 * Warn the user when a parser limitation is reached
3390 * Will warn at most once the user per limitation type
3392 * @param string $limitationType Should be one of:
3393 * 'expensive-parserfunction' (corresponding messages:
3394 * 'expensive-parserfunction-warning',
3395 * 'expensive-parserfunction-category')
3396 * 'post-expand-template-argument' (corresponding messages:
3397 * 'post-expand-template-argument-warning',
3398 * 'post-expand-template-argument-category')
3399 * 'post-expand-template-inclusion' (corresponding messages:
3400 * 'post-expand-template-inclusion-warning',
3401 * 'post-expand-template-inclusion-category')
3402 * 'node-count-exceeded' (corresponding messages:
3403 * 'node-count-exceeded-warning',
3404 * 'node-count-exceeded-category')
3405 * 'expansion-depth-exceeded' (corresponding messages:
3406 * 'expansion-depth-exceeded-warning',
3407 * 'expansion-depth-exceeded-category')
3408 * @param string|int|null $current Current value
3409 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3410 * exceeded, provide the values (optional)
3412 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3413 # does no harm if $current and $max are present but are unnecessary for the message
3414 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3415 ->inLanguage( $this->mOptions
->getUserLangObj() )->text();
3416 $this->mOutput
->addWarning( $warning );
3417 $this->addTrackingCategory( "$limitationType-category" );
3421 * Return the text of a template, after recursively
3422 * replacing any variables or templates within the template.
3424 * @param array $piece The parts of the template
3425 * $piece['title']: the title, i.e. the part before the |
3426 * $piece['parts']: the parameter array
3427 * $piece['lineStart']: whether the brace was at the start of a line
3428 * @param PPFrame $frame The current frame, contains template arguments
3430 * @return string The text of the template
3432 public function braceSubstitution( $piece, $frame ) {
3433 wfProfileIn( __METHOD__
. '-setup' );
3437 // $text has been filled
3439 // wiki markup in $text should be escaped
3441 // $text is HTML, armour it against wikitext transformation
3443 // Force interwiki transclusion to be done in raw mode not rendered
3444 $forceRawInterwiki = false;
3445 // $text is a DOM node needing expansion in a child frame
3446 $isChildObj = false;
3447 // $text is a DOM node needing expansion in the current frame
3448 $isLocalObj = false;
3450 # Title object, where $text came from
3453 # $part1 is the bit before the first |, and must contain only title characters.
3454 # Various prefixes will be stripped from it later.
3455 $titleWithSpaces = $frame->expand( $piece['title'] );
3456 $part1 = trim( $titleWithSpaces );
3459 # Original title text preserved for various purposes
3460 $originalTitle = $part1;
3462 # $args is a list of argument nodes, starting from index 0, not including $part1
3463 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3464 # below won't work b/c this $args isn't an object
3465 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3466 wfProfileOut( __METHOD__
. '-setup' );
3468 $profileSection = null; // profile templates
3471 wfProfileIn( __METHOD__
. '-modifiers' );
3474 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3476 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3477 # Decide whether to expand template or keep wikitext as-is.
3478 if ( $this->ot
['wiki'] ) {
3479 if ( $substMatch === false ) {
3480 $literal = true; # literal when in PST with no prefix
3482 $literal = false; # expand when in PST with subst: or safesubst:
3485 if ( $substMatch == 'subst' ) {
3486 $literal = true; # literal when not in PST with plain subst:
3488 $literal = false; # expand when not in PST with safesubst: or no prefix
3492 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3499 if ( !$found && $args->getLength() == 0 ) {
3500 $id = $this->mVariables
->matchStartToEnd( $part1 );
3501 if ( $id !== false ) {
3502 $text = $this->getVariableValue( $id, $frame );
3503 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3504 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3510 # MSG, MSGNW and RAW
3513 $mwMsgnw = MagicWord
::get( 'msgnw' );
3514 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3517 # Remove obsolete MSG:
3518 $mwMsg = MagicWord
::get( 'msg' );
3519 $mwMsg->matchStartAndRemove( $part1 );
3523 $mwRaw = MagicWord
::get( 'raw' );
3524 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3525 $forceRawInterwiki = true;
3528 wfProfileOut( __METHOD__
. '-modifiers' );
3532 wfProfileIn( __METHOD__
. '-pfunc' );
3534 $colonPos = strpos( $part1, ':' );
3535 if ( $colonPos !== false ) {
3536 $func = substr( $part1, 0, $colonPos );
3537 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3538 for ( $i = 0; $i < $args->getLength(); $i++
) {
3539 $funcArgs[] = $args->item( $i );
3542 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3543 } catch ( Exception
$ex ) {
3544 wfProfileOut( __METHOD__
. '-pfunc' );
3548 # The interface for parser functions allows for extracting
3549 # flags into the local scope. Extract any forwarded flags
3553 wfProfileOut( __METHOD__
. '-pfunc' );
3556 # Finish mangling title and then check for loops.
3557 # Set $title to a Title object and $titleText to the PDBK
3560 # Split the title into page and subpage
3562 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3563 if ( $part1 !== $relative ) {
3565 $ns = $this->mTitle
->getNamespace();
3567 $title = Title
::newFromText( $part1, $ns );
3569 $titleText = $title->getPrefixedText();
3570 # Check for language variants if the template is not found
3571 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3572 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3574 # Do recursion depth check
3575 $limit = $this->mOptions
->getMaxTemplateDepth();
3576 if ( $frame->depth
>= $limit ) {
3578 $text = '<span class="error">'
3579 . wfMessage( 'parser-template-recursion-depth-warning' )
3580 ->numParams( $limit )->inContentLanguage()->text()
3586 # Load from database
3587 if ( !$found && $title ) {
3588 $profileSection = $this->mProfiler
->scopedProfileIn( $title->getPrefixedDBkey() );
3589 wfProfileIn( __METHOD__
. '-loadtpl' );
3590 if ( !$title->isExternal() ) {
3591 if ( $title->isSpecialPage()
3592 && $this->mOptions
->getAllowSpecialInclusion()
3593 && $this->ot
['html']
3595 // Pass the template arguments as URL parameters.
3596 // "uselang" will have no effect since the Language object
3597 // is forced to the one defined in ParserOptions.
3598 $pageArgs = array();
3599 $argsLength = $args->getLength();
3600 for ( $i = 0; $i < $argsLength; $i++
) {
3601 $bits = $args->item( $i )->splitArg();
3602 if ( strval( $bits['index'] ) === '' ) {
3603 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3604 $value = trim( $frame->expand( $bits['value'] ) );
3605 $pageArgs[$name] = $value;
3609 // Create a new context to execute the special page
3610 $context = new RequestContext
;
3611 $context->setTitle( $title );
3612 $context->setRequest( new FauxRequest( $pageArgs ) );
3613 $context->setUser( $this->getUser() );
3614 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3615 $ret = SpecialPageFactory
::capturePath( $title, $context );
3617 $text = $context->getOutput()->getHTML();
3618 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3621 $this->disableCache();
3623 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3624 $found = false; # access denied
3625 wfDebug( __METHOD__
. ": template inclusion denied for " .
3626 $title->getPrefixedDBkey() . "\n" );
3628 list( $text, $title ) = $this->getTemplateDom( $title );
3629 if ( $text !== false ) {
3635 # If the title is valid but undisplayable, make a link to it
3636 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3637 $text = "[[:$titleText]]";
3640 } elseif ( $title->isTrans() ) {
3641 # Interwiki transclusion
3642 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3643 $text = $this->interwikiTransclude( $title, 'render' );
3646 $text = $this->interwikiTransclude( $title, 'raw' );
3647 # Preprocess it like a template
3648 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3654 # Do infinite loop check
3655 # This has to be done after redirect resolution to avoid infinite loops via redirects
3656 if ( !$frame->loopCheck( $title ) ) {
3658 $text = '<span class="error">'
3659 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3661 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3663 wfProfileOut( __METHOD__
. '-loadtpl' );
3666 # If we haven't found text to substitute by now, we're done
3667 # Recover the source wikitext and return it
3669 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3670 if ( $profileSection ) {
3671 $this->mProfiler
->scopedProfileOut( $profileSection );
3673 return array( 'object' => $text );
3676 # Expand DOM-style return values in a child frame
3677 if ( $isChildObj ) {
3678 # Clean up argument array
3679 $newFrame = $frame->newChild( $args, $title );
3682 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3683 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3684 # Expansion is eligible for the empty-frame cache
3685 $text = $newFrame->cachedExpand( $titleText, $text );
3687 # Uncached expansion
3688 $text = $newFrame->expand( $text );
3691 if ( $isLocalObj && $nowiki ) {
3692 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3693 $isLocalObj = false;
3696 if ( $profileSection ) {
3697 $this->mProfiler
->scopedProfileOut( $profileSection );
3700 # Replace raw HTML by a placeholder
3702 $text = $this->insertStripItem( $text );
3703 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3704 # Escape nowiki-style return values
3705 $text = wfEscapeWikiText( $text );
3706 } elseif ( is_string( $text )
3707 && !$piece['lineStart']
3708 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3710 # Bug 529: if the template begins with a table or block-level
3711 # element, it should be treated as beginning a new line.
3712 # This behavior is somewhat controversial.
3713 $text = "\n" . $text;
3716 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3717 # Error, oversize inclusion
3718 if ( $titleText !== false ) {
3719 # Make a working, properly escaped link if possible (bug 23588)
3720 $text = "[[:$titleText]]";
3722 # This will probably not be a working link, but at least it may
3723 # provide some hint of where the problem is
3724 preg_replace( '/^:/', '', $originalTitle );
3725 $text = "[[:$originalTitle]]";
3727 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3728 . 'post-expand include size too large -->' );
3729 $this->limitationWarn( 'post-expand-template-inclusion' );
3732 if ( $isLocalObj ) {
3733 $ret = array( 'object' => $text );
3735 $ret = array( 'text' => $text );
3742 * Call a parser function and return an array with text and flags.
3744 * The returned array will always contain a boolean 'found', indicating
3745 * whether the parser function was found or not. It may also contain the
3747 * text: string|object, resulting wikitext or PP DOM object
3748 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3749 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3750 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3751 * nowiki: bool, wiki markup in $text should be escaped
3754 * @param PPFrame $frame The current frame, contains template arguments
3755 * @param string $function Function name
3756 * @param array $args Arguments to the function
3757 * @throws MWException
3760 public function callParserFunction( $frame, $function, array $args = array() ) {
3764 # Case sensitive functions
3765 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3766 $function = $this->mFunctionSynonyms
[1][$function];
3768 # Case insensitive functions
3769 $function = $wgContLang->lc( $function );
3770 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3771 $function = $this->mFunctionSynonyms
[0][$function];
3773 return array( 'found' => false );
3777 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3778 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3780 # Workaround for PHP bug 35229 and similar
3781 if ( !is_callable( $callback ) ) {
3782 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3783 throw new MWException( "Tag hook for $function is not callable\n" );
3786 $allArgs = array( &$this );
3787 if ( $flags & self
::SFH_OBJECT_ARGS
) {
3788 # Convert arguments to PPNodes and collect for appending to $allArgs
3789 $funcArgs = array();
3790 foreach ( $args as $k => $v ) {
3791 if ( $v instanceof PPNode ||
$k === 0 ) {
3794 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( array( $k => $v ) )->item( 0 );
3798 # Add a frame parameter, and pass the arguments as an array
3799 $allArgs[] = $frame;
3800 $allArgs[] = $funcArgs;
3802 # Convert arguments to plain text and append to $allArgs
3803 foreach ( $args as $k => $v ) {
3804 if ( $v instanceof PPNode
) {
3805 $allArgs[] = trim( $frame->expand( $v ) );
3806 } elseif ( is_int( $k ) && $k >= 0 ) {
3807 $allArgs[] = trim( $v );
3809 $allArgs[] = trim( "$k=$v" );
3814 $result = call_user_func_array( $callback, $allArgs );
3816 # The interface for function hooks allows them to return a wikitext
3817 # string or an array containing the string and any flags. This mungs
3818 # things around to match what this method should return.
3819 if ( !is_array( $result ) ) {
3825 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3826 $result['text'] = $result[0];
3828 unset( $result[0] );
3835 $preprocessFlags = 0;
3836 if ( isset( $result['noparse'] ) ) {
3837 $noparse = $result['noparse'];
3839 if ( isset( $result['preprocessFlags'] ) ) {
3840 $preprocessFlags = $result['preprocessFlags'];
3844 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3845 $result['isChildObj'] = true;
3847 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3853 * Get the semi-parsed DOM representation of a template with a given title,
3854 * and its redirect destination title. Cached.
3856 * @param Title $title
3860 public function getTemplateDom( $title ) {
3861 $cacheTitle = $title;
3862 $titleText = $title->getPrefixedDBkey();
3864 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3865 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3866 $title = Title
::makeTitle( $ns, $dbk );
3867 $titleText = $title->getPrefixedDBkey();
3869 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3870 return array( $this->mTplDomCache
[$titleText], $title );
3873 # Cache miss, go to the database
3874 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3876 if ( $text === false ) {
3877 $this->mTplDomCache
[$titleText] = false;
3878 return array( false, $title );
3881 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3882 $this->mTplDomCache
[$titleText] = $dom;
3884 if ( !$title->equals( $cacheTitle ) ) {
3885 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3886 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3889 return array( $dom, $title );
3893 * Fetch the current revision of a given title. Note that the revision
3894 * (and even the title) may not exist in the database, so everything
3895 * contributing to the output of the parser should use this method
3896 * where possible, rather than getting the revisions themselves. This
3897 * method also caches its results, so using it benefits performance.
3900 * @param Title $title
3903 public function fetchCurrentRevisionOfTitle( $title ) {
3904 $cacheKey = $title->getPrefixedDBkey();
3905 if ( !$this->currentRevisionCache
) {
3906 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3908 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3909 $this->currentRevisionCache
->set( $cacheKey,
3910 // Defaults to Parser::statelessFetchRevision()
3911 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3914 return $this->currentRevisionCache
->get( $cacheKey );
3918 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3919 * without passing them on to it.
3922 * @param Title $title
3923 * @param Parser|bool $parser
3926 public static function statelessFetchRevision( $title, $parser = false ) {
3927 return Revision
::newFromTitle( $title );
3931 * Fetch the unparsed text of a template and register a reference to it.
3932 * @param Title $title
3933 * @return array ( string or false, Title )
3935 public function fetchTemplateAndTitle( $title ) {
3936 // Defaults to Parser::statelessFetchTemplate()
3937 $templateCb = $this->mOptions
->getTemplateCallback();
3938 $stuff = call_user_func( $templateCb, $title, $this );
3939 $text = $stuff['text'];
3940 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3941 if ( isset( $stuff['deps'] ) ) {
3942 foreach ( $stuff['deps'] as $dep ) {
3943 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3944 if ( $dep['title']->equals( $this->getTitle() ) ) {
3945 // If we transclude ourselves, the final result
3946 // will change based on the new version of the page
3947 $this->mOutput
->setFlag( 'vary-revision' );
3951 return array( $text, $finalTitle );
3955 * Fetch the unparsed text of a template and register a reference to it.
3956 * @param Title $title
3957 * @return string|bool
3959 public function fetchTemplate( $title ) {
3960 $rv = $this->fetchTemplateAndTitle( $title );
3965 * Static function to get a template
3966 * Can be overridden via ParserOptions::setTemplateCallback().
3968 * @param Title $title
3969 * @param bool|Parser $parser
3973 public static function statelessFetchTemplate( $title, $parser = false ) {
3974 $text = $skip = false;
3975 $finalTitle = $title;
3978 # Loop to fetch the article, with up to 1 redirect
3979 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3980 # Give extensions a chance to select the revision instead
3981 $id = false; # Assume current
3982 Hooks
::run( 'BeforeParserFetchTemplateAndtitle',
3983 array( $parser, $title, &$skip, &$id ) );
3989 'page_id' => $title->getArticleID(),
3996 $rev = Revision
::newFromId( $id );
3997 } elseif ( $parser ) {
3998 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
4000 $rev = Revision
::newFromTitle( $title );
4002 $rev_id = $rev ?
$rev->getId() : 0;
4003 # If there is no current revision, there is no page
4004 if ( $id === false && !$rev ) {
4005 $linkCache = LinkCache
::singleton();
4006 $linkCache->addBadLinkObj( $title );
4011 'page_id' => $title->getArticleID(),
4012 'rev_id' => $rev_id );
4013 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
4014 # We fetched a rev from a different title; register it too...
4016 'title' => $rev->getTitle(),
4017 'page_id' => $rev->getPage(),
4018 'rev_id' => $rev_id );
4022 $content = $rev->getContent();
4023 $text = $content ?
$content->getWikitextForTransclusion() : null;
4025 if ( $text === false ||
$text === null ) {
4029 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
4031 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
4032 if ( !$message->exists() ) {
4036 $content = $message->content();
4037 $text = $message->plain();
4045 $finalTitle = $title;
4046 $title = $content->getRedirectTarget();
4050 'finalTitle' => $finalTitle,
4055 * Fetch a file and its title and register a reference to it.
4056 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4057 * @param Title $title
4058 * @param array $options Array of options to RepoGroup::findFile
4061 public function fetchFile( $title, $options = array() ) {
4062 $res = $this->fetchFileAndTitle( $title, $options );
4067 * Fetch a file and its title and register a reference to it.
4068 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4069 * @param Title $title
4070 * @param array $options Array of options to RepoGroup::findFile
4071 * @return array ( File or false, Title of file )
4073 public function fetchFileAndTitle( $title, $options = array() ) {
4074 $file = $this->fetchFileNoRegister( $title, $options );
4076 $time = $file ?
$file->getTimestamp() : false;
4077 $sha1 = $file ?
$file->getSha1() : false;
4078 # Register the file as a dependency...
4079 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4080 if ( $file && !$title->equals( $file->getTitle() ) ) {
4081 # Update fetched file title
4082 $title = $file->getTitle();
4083 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4085 return array( $file, $title );
4089 * Helper function for fetchFileAndTitle.
4091 * Also useful if you need to fetch a file but not use it yet,
4092 * for example to get the file's handler.
4094 * @param Title $title
4095 * @param array $options Array of options to RepoGroup::findFile
4098 protected function fetchFileNoRegister( $title, $options = array() ) {
4099 if ( isset( $options['broken'] ) ) {
4100 $file = false; // broken thumbnail forced by hook
4101 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
4102 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
4103 } else { // get by (name,timestamp)
4104 $file = wfFindFile( $title, $options );
4110 * Transclude an interwiki link.
4112 * @param Title $title
4113 * @param string $action
4117 public function interwikiTransclude( $title, $action ) {
4118 global $wgEnableScaryTranscluding;
4120 if ( !$wgEnableScaryTranscluding ) {
4121 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
4124 $url = $title->getFullURL( array( 'action' => $action ) );
4126 if ( strlen( $url ) > 255 ) {
4127 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
4129 return $this->fetchScaryTemplateMaybeFromCache( $url );
4133 * @param string $url
4134 * @return mixed|string
4136 public function fetchScaryTemplateMaybeFromCache( $url ) {
4137 global $wgTranscludeCacheExpiry;
4138 $dbr = wfGetDB( DB_SLAVE
);
4139 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
4140 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
4141 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
4143 return $obj->tc_contents
;
4146 $req = MWHttpRequest
::factory( $url );
4147 $status = $req->execute(); // Status object
4148 if ( $status->isOK() ) {
4149 $text = $req->getContent();
4150 } elseif ( $req->getStatus() != 200 ) {
4151 // Though we failed to fetch the content, this status is useless.
4152 return wfMessage( 'scarytranscludefailed-httpstatus' )
4153 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
4155 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
4158 $dbw = wfGetDB( DB_MASTER
);
4159 $dbw->replace( 'transcache', array( 'tc_url' ), array(
4161 'tc_time' => $dbw->timestamp( time() ),
4162 'tc_contents' => $text
4168 * Triple brace replacement -- used for template arguments
4171 * @param array $piece
4172 * @param PPFrame $frame
4176 public function argSubstitution( $piece, $frame ) {
4179 $parts = $piece['parts'];
4180 $nameWithSpaces = $frame->expand( $piece['title'] );
4181 $argName = trim( $nameWithSpaces );
4183 $text = $frame->getArgument( $argName );
4184 if ( $text === false && $parts->getLength() > 0
4185 && ( $this->ot
['html']
4187 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
4190 # No match in frame, use the supplied default
4191 $object = $parts->item( 0 )->getChildren();
4193 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
4194 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
4195 $this->limitationWarn( 'post-expand-template-argument' );
4198 if ( $text === false && $object === false ) {
4200 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
4202 if ( $error !== false ) {
4205 if ( $object !== false ) {
4206 $ret = array( 'object' => $object );
4208 $ret = array( 'text' => $text );
4215 * Return the text to be used for a given extension tag.
4216 * This is the ghost of strip().
4218 * @param array $params Associative array of parameters:
4219 * name PPNode for the tag name
4220 * attr PPNode for unparsed text where tag attributes are thought to be
4221 * attributes Optional associative array of parsed attributes
4222 * inner Contents of extension element
4223 * noClose Original text did not have a close tag
4224 * @param PPFrame $frame
4226 * @throws MWException
4229 public function extensionSubstitution( $params, $frame ) {
4230 $name = $frame->expand( $params['name'] );
4231 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
4232 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
4233 $marker = "{$this->mUniqPrefix}-$name-"
4234 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
4236 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
4237 ( $this->ot
['html'] ||
$this->ot
['pre'] );
4238 if ( $isFunctionTag ) {
4239 $markerType = 'none';
4241 $markerType = 'general';
4243 if ( $this->ot
['html'] ||
$isFunctionTag ) {
4244 $name = strtolower( $name );
4245 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
4246 if ( isset( $params['attributes'] ) ) {
4247 $attributes = $attributes +
$params['attributes'];
4250 if ( isset( $this->mTagHooks
[$name] ) ) {
4251 # Workaround for PHP bug 35229 and similar
4252 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
4253 throw new MWException( "Tag hook for $name is not callable\n" );
4255 $output = call_user_func_array( $this->mTagHooks
[$name],
4256 array( $content, $attributes, $this, $frame ) );
4257 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
4258 list( $callback, ) = $this->mFunctionTagHooks
[$name];
4259 if ( !is_callable( $callback ) ) {
4260 throw new MWException( "Tag hook for $name is not callable\n" );
4263 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
4265 $output = '<span class="error">Invalid tag extension name: ' .
4266 htmlspecialchars( $name ) . '</span>';
4269 if ( is_array( $output ) ) {
4270 # Extract flags to local scope (to override $markerType)
4272 $output = $flags[0];
4277 if ( is_null( $attrText ) ) {
4280 if ( isset( $params['attributes'] ) ) {
4281 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4282 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4283 htmlspecialchars( $attrValue ) . '"';
4286 if ( $content === null ) {
4287 $output = "<$name$attrText/>";
4289 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4290 $output = "<$name$attrText>$content$close";
4294 if ( $markerType === 'none' ) {
4296 } elseif ( $markerType === 'nowiki' ) {
4297 $this->mStripState
->addNoWiki( $marker, $output );
4298 } elseif ( $markerType === 'general' ) {
4299 $this->mStripState
->addGeneral( $marker, $output );
4301 throw new MWException( __METHOD__
. ': invalid marker type' );
4307 * Increment an include size counter
4309 * @param string $type The type of expansion
4310 * @param int $size The size of the text
4311 * @return bool False if this inclusion would take it over the maximum, true otherwise
4313 public function incrementIncludeSize( $type, $size ) {
4314 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4317 $this->mIncludeSizes
[$type] +
= $size;
4323 * Increment the expensive function count
4325 * @return bool False if the limit has been exceeded
4327 public function incrementExpensiveFunctionCount() {
4328 $this->mExpensiveFunctionCount++
;
4329 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4333 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4334 * Fills $this->mDoubleUnderscores, returns the modified text
4336 * @param string $text
4340 public function doDoubleUnderscore( $text ) {
4342 # The position of __TOC__ needs to be recorded
4343 $mw = MagicWord
::get( 'toc' );
4344 if ( $mw->match( $text ) ) {
4345 $this->mShowToc
= true;
4346 $this->mForceTocPosition
= true;
4348 # Set a placeholder. At the end we'll fill it in with the TOC.
4349 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4351 # Only keep the first one.
4352 $text = $mw->replace( '', $text );
4355 # Now match and remove the rest of them
4356 $mwa = MagicWord
::getDoubleUnderscoreArray();
4357 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4359 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4360 $this->mOutput
->mNoGallery
= true;
4362 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4363 $this->mShowToc
= false;
4365 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4366 && $this->mTitle
->getNamespace() == NS_CATEGORY
4368 $this->addTrackingCategory( 'hidden-category-category' );
4370 # (bug 8068) Allow control over whether robots index a page.
4372 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4373 # is not desirable, the last one on the page should win.
4374 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4375 $this->mOutput
->setIndexPolicy( 'noindex' );
4376 $this->addTrackingCategory( 'noindex-category' );
4378 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4379 $this->mOutput
->setIndexPolicy( 'index' );
4380 $this->addTrackingCategory( 'index-category' );
4383 # Cache all double underscores in the database
4384 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4385 $this->mOutput
->setProperty( $key, '' );
4392 * @see ParserOutput::addTrackingCategory()
4393 * @param string $msg Message key
4394 * @return bool Whether the addition was successful
4396 public function addTrackingCategory( $msg ) {
4397 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4401 * This function accomplishes several tasks:
4402 * 1) Auto-number headings if that option is enabled
4403 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4404 * 3) Add a Table of contents on the top for users who have enabled the option
4405 * 4) Auto-anchor headings
4407 * It loops through all headlines, collects the necessary data, then splits up the
4408 * string and re-inserts the newly formatted headlines.
4410 * @param string $text
4411 * @param string $origText Original, untouched wikitext
4412 * @param bool $isMain
4413 * @return mixed|string
4416 public function formatHeadings( $text, $origText, $isMain = true ) {
4417 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4419 # Inhibit editsection links if requested in the page
4420 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4421 $maybeShowEditLink = $showEditLink = false;
4423 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4424 $showEditLink = $this->mOptions
->getEditSection();
4426 if ( $showEditLink ) {
4427 $this->mOutput
->setEditSectionTokens( true );
4430 # Get all headlines for numbering them and adding funky stuff like [edit]
4431 # links - this is for later, but we need the number of headlines right now
4433 $numMatches = preg_match_all(
4434 '/<H(?P<level>[1-6])(?P<attrib>.*?' . '>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i',
4439 # if there are fewer than 4 headlines in the article, do not show TOC
4440 # unless it's been explicitly enabled.
4441 $enoughToc = $this->mShowToc
&&
4442 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4444 # Allow user to stipulate that a page should have a "new section"
4445 # link added via __NEWSECTIONLINK__
4446 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4447 $this->mOutput
->setNewSection( true );
4450 # Allow user to remove the "new section"
4451 # link via __NONEWSECTIONLINK__
4452 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4453 $this->mOutput
->hideNewSection( true );
4456 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4457 # override above conditions and always show TOC above first header
4458 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4459 $this->mShowToc
= true;
4467 # Ugh .. the TOC should have neat indentation levels which can be
4468 # passed to the skin functions. These are determined here
4472 $sublevelCount = array();
4473 $levelCount = array();
4478 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4479 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4480 $oldType = $this->mOutputType
;
4481 $this->setOutputType( self
::OT_WIKI
);
4482 $frame = $this->getPreprocessor()->newFrame();
4483 $root = $this->preprocessToDom( $origText );
4484 $node = $root->getFirstChild();
4489 foreach ( $matches[3] as $headline ) {
4490 $isTemplate = false;
4492 $sectionIndex = false;
4494 $markerMatches = array();
4495 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4496 $serial = $markerMatches[1];
4497 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4498 $isTemplate = ( $titleText != $baseTitleText );
4499 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4503 $prevlevel = $level;
4505 $level = $matches[1][$headlineCount];
4507 if ( $level > $prevlevel ) {
4508 # Increase TOC level
4510 $sublevelCount[$toclevel] = 0;
4511 if ( $toclevel < $wgMaxTocLevel ) {
4512 $prevtoclevel = $toclevel;
4513 $toc .= Linker
::tocIndent();
4516 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4517 # Decrease TOC level, find level to jump to
4519 for ( $i = $toclevel; $i > 0; $i-- ) {
4520 if ( $levelCount[$i] == $level ) {
4521 # Found last matching level
4524 } elseif ( $levelCount[$i] < $level ) {
4525 # Found first matching level below current level
4533 if ( $toclevel < $wgMaxTocLevel ) {
4534 if ( $prevtoclevel < $wgMaxTocLevel ) {
4535 # Unindent only if the previous toc level was shown :p
4536 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4537 $prevtoclevel = $toclevel;
4539 $toc .= Linker
::tocLineEnd();
4543 # No change in level, end TOC line
4544 if ( $toclevel < $wgMaxTocLevel ) {
4545 $toc .= Linker
::tocLineEnd();
4549 $levelCount[$toclevel] = $level;
4551 # count number of headlines for each level
4552 $sublevelCount[$toclevel]++
;
4554 for ( $i = 1; $i <= $toclevel; $i++
) {
4555 if ( !empty( $sublevelCount[$i] ) ) {
4559 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4564 # The safe header is a version of the header text safe to use for links
4566 # Remove link placeholders by the link text.
4567 # <!--LINK number-->
4569 # link text with suffix
4570 # Do this before unstrip since link text can contain strip markers
4571 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4573 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4574 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4576 # Strip out HTML (first regex removes any tag not allowed)
4578 # * <sup> and <sub> (bug 8393)
4581 # * <bdi> (bug 72884)
4582 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4584 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4585 # to allow setting directionality in toc items.
4586 $tocline = preg_replace(
4588 '#<(?!/?(span|sup|sub|bdi|i|b)(?: [^>]*)?>).*?' . '>#',
4589 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|bdi|i|b))(?: .*?)?' . '>#'
4591 array( '', '<$1>' ),
4594 $tocline = trim( $tocline );
4596 # For the anchor, strip out HTML-y stuff period
4597 $safeHeadline = preg_replace( '/<.*?' . '>/', '', $safeHeadline );
4598 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4600 # Save headline for section edit hint before it's escaped
4601 $headlineHint = $safeHeadline;
4603 if ( $wgExperimentalHtmlIds ) {
4604 # For reverse compatibility, provide an id that's
4605 # HTML4-compatible, like we used to.
4607 # It may be worth noting, academically, that it's possible for
4608 # the legacy anchor to conflict with a non-legacy headline
4609 # anchor on the page. In this case likely the "correct" thing
4610 # would be to either drop the legacy anchors or make sure
4611 # they're numbered first. However, this would require people
4612 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4613 # manually, so let's not bother worrying about it.
4614 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4615 array( 'noninitial', 'legacy' ) );
4616 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4618 if ( $legacyHeadline == $safeHeadline ) {
4619 # No reason to have both (in fact, we can't)
4620 $legacyHeadline = false;
4623 $legacyHeadline = false;
4624 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4628 # HTML names must be case-insensitively unique (bug 10721).
4629 # This does not apply to Unicode characters per
4630 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4631 # @todo FIXME: We may be changing them depending on the current locale.
4632 $arrayKey = strtolower( $safeHeadline );
4633 if ( $legacyHeadline === false ) {
4634 $legacyArrayKey = false;
4636 $legacyArrayKey = strtolower( $legacyHeadline );
4639 # count how many in assoc. array so we can track dupes in anchors
4640 if ( isset( $refers[$arrayKey] ) ) {
4641 $refers[$arrayKey]++
;
4643 $refers[$arrayKey] = 1;
4645 if ( isset( $refers[$legacyArrayKey] ) ) {
4646 $refers[$legacyArrayKey]++
;
4648 $refers[$legacyArrayKey] = 1;
4651 # Don't number the heading if it is the only one (looks silly)
4652 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4653 # the two are different if the line contains a link
4654 $headline = Html
::element(
4656 array( 'class' => 'mw-headline-number' ),
4658 ) . ' ' . $headline;
4661 # Create the anchor for linking from the TOC to the section
4662 $anchor = $safeHeadline;
4663 $legacyAnchor = $legacyHeadline;
4664 if ( $refers[$arrayKey] > 1 ) {
4665 $anchor .= '_' . $refers[$arrayKey];
4667 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4668 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4670 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4671 $toc .= Linker
::tocLine( $anchor, $tocline,
4672 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4675 # Add the section to the section tree
4676 # Find the DOM node for this header
4677 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4678 while ( $node && !$noOffset ) {
4679 if ( $node->getName() === 'h' ) {
4680 $bits = $node->splitHeading();
4681 if ( $bits['i'] == $sectionIndex ) {
4685 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4686 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4687 $node = $node->getNextSibling();
4690 'toclevel' => $toclevel,
4693 'number' => $numbering,
4694 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4695 'fromtitle' => $titleText,
4696 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4697 'anchor' => $anchor,
4700 # give headline the correct <h#> tag
4701 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4702 // Output edit section links as markers with styles that can be customized by skins
4703 if ( $isTemplate ) {
4704 # Put a T flag in the section identifier, to indicate to extractSections()
4705 # that sections inside <includeonly> should be counted.
4706 $editsectionPage = $titleText;
4707 $editsectionSection = "T-$sectionIndex";
4708 $editsectionContent = null;
4710 $editsectionPage = $this->mTitle
->getPrefixedText();
4711 $editsectionSection = $sectionIndex;
4712 $editsectionContent = $headlineHint;
4714 // We use a bit of pesudo-xml for editsection markers. The
4715 // language converter is run later on. Using a UNIQ style marker
4716 // leads to the converter screwing up the tokens when it
4717 // converts stuff. And trying to insert strip tags fails too. At
4718 // this point all real inputted tags have already been escaped,
4719 // so we don't have to worry about a user trying to input one of
4720 // these markers directly. We use a page and section attribute
4721 // to stop the language converter from converting these
4722 // important bits of data, but put the headline hint inside a
4723 // content block because the language converter is supposed to
4724 // be able to convert that piece of data.
4725 // Gets replaced with html in ParserOutput::getText
4726 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4727 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4728 if ( $editsectionContent !== null ) {
4729 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4736 $head[$headlineCount] = Linker
::makeHeadline( $level,
4737 $matches['attrib'][$headlineCount], $anchor, $headline,
4738 $editlink, $legacyAnchor );
4743 $this->setOutputType( $oldType );
4745 # Never ever show TOC if no headers
4746 if ( $numVisible < 1 ) {
4751 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4752 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4754 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4755 $this->mOutput
->setTOCHTML( $toc );
4756 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4757 $this->mOutput
->addModules( 'mediawiki.toc' );
4761 $this->mOutput
->setSections( $tocraw );
4764 # split up and insert constructed headlines
4765 $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text );
4768 // build an array of document sections
4769 $sections = array();
4770 foreach ( $blocks as $block ) {
4771 // $head is zero-based, sections aren't.
4772 if ( empty( $head[$i - 1] ) ) {
4773 $sections[$i] = $block;
4775 $sections[$i] = $head[$i - 1] . $block;
4779 * Send a hook, one per section.
4780 * The idea here is to be able to make section-level DIVs, but to do so in a
4781 * lower-impact, more correct way than r50769
4784 * $section : the section number
4785 * &$sectionContent : ref to the content of the section
4786 * $showEditLinks : boolean describing whether this section has an edit link
4788 Hooks
::run( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4793 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4794 // append the TOC at the beginning
4795 // Top anchor now in skin
4796 $sections[0] = $sections[0] . $toc . "\n";
4799 $full .= join( '', $sections );
4801 if ( $this->mForceTocPosition
) {
4802 return str_replace( '<!--MWTOC-->', $toc, $full );
4809 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4810 * conversion, substituting signatures, {{subst:}} templates, etc.
4812 * @param string $text The text to transform
4813 * @param Title $title The Title object for the current article
4814 * @param User $user The User object describing the current user
4815 * @param ParserOptions $options Parsing options
4816 * @param bool $clearState Whether to clear the parser state first
4817 * @return string The altered wiki markup
4819 public function preSaveTransform( $text, Title
$title, User
$user,
4820 ParserOptions
$options, $clearState = true
4822 if ( $clearState ) {
4823 $magicScopeVariable = $this->lock();
4825 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4826 $this->setUser( $user );
4832 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4833 if ( $options->getPreSaveTransform() ) {
4834 $text = $this->pstPass2( $text, $user );
4836 $text = $this->mStripState
->unstripBoth( $text );
4838 $this->setUser( null ); #Reset
4844 * Pre-save transform helper function
4846 * @param string $text
4851 private function pstPass2( $text, $user ) {
4854 # Note: This is the timestamp saved as hardcoded wikitext to
4855 # the database, we use $wgContLang here in order to give
4856 # everyone the same signature and use the default one rather
4857 # than the one selected in each user's preferences.
4858 # (see also bug 12815)
4859 $ts = $this->mOptions
->getTimestamp();
4860 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4861 $ts = $timestamp->format( 'YmdHis' );
4862 $tzMsg = $timestamp->format( 'T' ); # might vary on DST changeover!
4864 # Allow translation of timezones through wiki. format() can return
4865 # whatever crap the system uses, localised or not, so we cannot
4866 # ship premade translations.
4867 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4868 $msg = wfMessage( $key )->inContentLanguage();
4869 if ( $msg->exists() ) {
4870 $tzMsg = $msg->text();
4873 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4875 # Variable replacement
4876 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4877 $text = $this->replaceVariables( $text );
4879 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4880 # which may corrupt this parser instance via its wfMessage()->text() call-
4883 $sigText = $this->getUserSig( $user );
4884 $text = strtr( $text, array(
4886 '~~~~' => "$sigText $d",
4890 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4891 $tc = '[' . Title
::legalChars() . ']';
4892 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4894 // [[ns:page (context)|]]
4895 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4896 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4897 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4898 // [[ns:page (context), context|]] (using either single or double-width comma)
4899 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4900 // [[|page]] (reverse pipe trick: add context from page title)
4901 $p2 = "/\[\[\\|($tc+)]]/";
4903 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4904 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4905 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4906 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4908 $t = $this->mTitle
->getText();
4910 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4911 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4912 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4913 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4915 # if there's no context, don't bother duplicating the title
4916 $text = preg_replace( $p2, '[[\\1]]', $text );
4919 # Trim trailing whitespace
4920 $text = rtrim( $text );
4926 * Fetch the user's signature text, if any, and normalize to
4927 * validated, ready-to-insert wikitext.
4928 * If you have pre-fetched the nickname or the fancySig option, you can
4929 * specify them here to save a database query.
4930 * Do not reuse this parser instance after calling getUserSig(),
4931 * as it may have changed if it's the $wgParser.
4934 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4935 * @param bool|null $fancySig whether the nicknname is the complete signature
4936 * or null to use default value
4939 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4940 global $wgMaxSigChars;
4942 $username = $user->getName();
4944 # If not given, retrieve from the user object.
4945 if ( $nickname === false ) {
4946 $nickname = $user->getOption( 'nickname' );
4949 if ( is_null( $fancySig ) ) {
4950 $fancySig = $user->getBoolOption( 'fancysig' );
4953 $nickname = $nickname == null ?
$username : $nickname;
4955 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4956 $nickname = $username;
4957 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4958 } elseif ( $fancySig !== false ) {
4959 # Sig. might contain markup; validate this
4960 if ( $this->validateSig( $nickname ) !== false ) {
4961 # Validated; clean up (if needed) and return it
4962 return $this->cleanSig( $nickname, true );
4964 # Failed to validate; fall back to the default
4965 $nickname = $username;
4966 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4970 # Make sure nickname doesnt get a sig in a sig
4971 $nickname = self
::cleanSigInSig( $nickname );
4973 # If we're still here, make it a link to the user page
4974 $userText = wfEscapeWikiText( $username );
4975 $nickText = wfEscapeWikiText( $nickname );
4976 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4978 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4979 ->title( $this->getTitle() )->text();
4983 * Check that the user's signature contains no bad XML
4985 * @param string $text
4986 * @return string|bool An expanded string, or false if invalid.
4988 public function validateSig( $text ) {
4989 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4993 * Clean up signature text
4995 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4996 * 2) Substitute all transclusions
4998 * @param string $text
4999 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
5000 * @return string Signature text
5002 public function cleanSig( $text, $parsing = false ) {
5005 $magicScopeVariable = $this->lock();
5006 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
5009 # Option to disable this feature
5010 if ( !$this->mOptions
->getCleanSignatures() ) {
5014 # @todo FIXME: Regex doesn't respect extension tags or nowiki
5015 # => Move this logic to braceSubstitution()
5016 $substWord = MagicWord
::get( 'subst' );
5017 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
5018 $substText = '{{' . $substWord->getSynonym( 0 );
5020 $text = preg_replace( $substRegex, $substText, $text );
5021 $text = self
::cleanSigInSig( $text );
5022 $dom = $this->preprocessToDom( $text );
5023 $frame = $this->getPreprocessor()->newFrame();
5024 $text = $frame->expand( $dom );
5027 $text = $this->mStripState
->unstripBoth( $text );
5034 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
5036 * @param string $text
5037 * @return string Signature text with /~{3,5}/ removed
5039 public static function cleanSigInSig( $text ) {
5040 $text = preg_replace( '/~{3,5}/', '', $text );
5045 * Set up some variables which are usually set up in parse()
5046 * so that an external function can call some class members with confidence
5048 * @param Title|null $title
5049 * @param ParserOptions $options
5050 * @param int $outputType
5051 * @param bool $clearState
5053 public function startExternalParse( Title
$title = null, ParserOptions
$options,
5054 $outputType, $clearState = true
5056 $this->startParse( $title, $options, $outputType, $clearState );
5060 * @param Title|null $title
5061 * @param ParserOptions $options
5062 * @param int $outputType
5063 * @param bool $clearState
5065 private function startParse( Title
$title = null, ParserOptions
$options,
5066 $outputType, $clearState = true
5068 $this->setTitle( $title );
5069 $this->mOptions
= $options;
5070 $this->setOutputType( $outputType );
5071 if ( $clearState ) {
5072 $this->clearState();
5077 * Wrapper for preprocess()
5079 * @param string $text The text to preprocess
5080 * @param ParserOptions $options Options
5081 * @param Title|null $title Title object or null to use $wgTitle
5084 public function transformMsg( $text, $options, $title = null ) {
5085 static $executing = false;
5087 # Guard against infinite recursion
5098 $text = $this->preprocess( $text, $title, $options );
5105 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
5106 * The callback should have the following form:
5107 * function myParserHook( $text, $params, $parser, $frame ) { ... }
5109 * Transform and return $text. Use $parser for any required context, e.g. use
5110 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
5112 * Hooks may return extended information by returning an array, of which the
5113 * first numbered element (index 0) must be the return string, and all other
5114 * entries are extracted into local variables within an internal function
5115 * in the Parser class.
5117 * This interface (introduced r61913) appears to be undocumented, but
5118 * 'markerName' is used by some core tag hooks to override which strip
5119 * array their results are placed in. **Use great caution if attempting
5120 * this interface, as it is not documented and injudicious use could smash
5121 * private variables.**
5123 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5124 * @param callable $callback The callback function (and object) to use for the tag
5125 * @throws MWException
5126 * @return callable|null The old value of the mTagHooks array associated with the hook
5128 public function setHook( $tag, $callback ) {
5129 $tag = strtolower( $tag );
5130 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5131 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
5133 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
5134 $this->mTagHooks
[$tag] = $callback;
5135 if ( !in_array( $tag, $this->mStripList
) ) {
5136 $this->mStripList
[] = $tag;
5143 * As setHook(), but letting the contents be parsed.
5145 * Transparent tag hooks are like regular XML-style tag hooks, except they
5146 * operate late in the transformation sequence, on HTML instead of wikitext.
5148 * This is probably obsoleted by things dealing with parser frames?
5149 * The only extension currently using it is geoserver.
5152 * @todo better document or deprecate this
5154 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5155 * @param callable $callback The callback function (and object) to use for the tag
5156 * @throws MWException
5157 * @return callable|null The old value of the mTagHooks array associated with the hook
5159 public function setTransparentTagHook( $tag, $callback ) {
5160 $tag = strtolower( $tag );
5161 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5162 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
5164 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
5165 $this->mTransparentTagHooks
[$tag] = $callback;
5171 * Remove all tag hooks
5173 public function clearTagHooks() {
5174 $this->mTagHooks
= array();
5175 $this->mFunctionTagHooks
= array();
5176 $this->mStripList
= $this->mDefaultStripList
;
5180 * Create a function, e.g. {{sum:1|2|3}}
5181 * The callback function should have the form:
5182 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
5184 * Or with Parser::SFH_OBJECT_ARGS:
5185 * function myParserFunction( $parser, $frame, $args ) { ... }
5187 * The callback may either return the text result of the function, or an array with the text
5188 * in element 0, and a number of flags in the other elements. The names of the flags are
5189 * specified in the keys. Valid flags are:
5190 * found The text returned is valid, stop processing the template. This
5192 * nowiki Wiki markup in the return value should be escaped
5193 * isHTML The returned text is HTML, armour it against wikitext transformation
5195 * @param string $id The magic word ID
5196 * @param callable $callback The callback function (and object) to use
5197 * @param int $flags A combination of the following flags:
5198 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
5200 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
5201 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
5202 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
5203 * the arguments, and to control the way they are expanded.
5205 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
5206 * arguments, for instance:
5207 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
5209 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
5210 * future versions. Please call $frame->expand() on it anyway so that your code keeps
5211 * working if/when this is changed.
5213 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
5216 * Please read the documentation in includes/parser/Preprocessor.php for more information
5217 * about the methods available in PPFrame and PPNode.
5219 * @throws MWException
5220 * @return string|callable The old callback function for this name, if any
5222 public function setFunctionHook( $id, $callback, $flags = 0 ) {
5225 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
5226 $this->mFunctionHooks
[$id] = array( $callback, $flags );
5228 # Add to function cache
5229 $mw = MagicWord
::get( $id );
5231 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
5234 $synonyms = $mw->getSynonyms();
5235 $sensitive = intval( $mw->isCaseSensitive() );
5237 foreach ( $synonyms as $syn ) {
5239 if ( !$sensitive ) {
5240 $syn = $wgContLang->lc( $syn );
5243 if ( !( $flags & self
::SFH_NO_HASH
) ) {
5246 # Remove trailing colon
5247 if ( substr( $syn, -1, 1 ) === ':' ) {
5248 $syn = substr( $syn, 0, -1 );
5250 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
5256 * Get all registered function hook identifiers
5260 public function getFunctionHooks() {
5261 return array_keys( $this->mFunctionHooks
);
5265 * Create a tag function, e.g. "<test>some stuff</test>".
5266 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5267 * Unlike parser functions, their content is not preprocessed.
5268 * @param string $tag
5269 * @param callable $callback
5271 * @throws MWException
5274 public function setFunctionTagHook( $tag, $callback, $flags ) {
5275 $tag = strtolower( $tag );
5276 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5277 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5279 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
5280 $this->mFunctionTagHooks
[$tag] : null;
5281 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
5283 if ( !in_array( $tag, $this->mStripList
) ) {
5284 $this->mStripList
[] = $tag;
5291 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
5292 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5293 * Placeholders created in Skin::makeLinkObj()
5295 * @param string $text
5296 * @param int $options
5298 public function replaceLinkHolders( &$text, $options = 0 ) {
5299 $this->mLinkHolders
->replace( $text );
5303 * Replace "<!--LINK-->" link placeholders with plain text of links
5304 * (not HTML-formatted).
5306 * @param string $text
5309 public function replaceLinkHoldersText( $text ) {
5310 return $this->mLinkHolders
->replaceText( $text );
5314 * Renders an image gallery from a text with one line per image.
5315 * text labels may be given by using |-style alternative text. E.g.
5316 * Image:one.jpg|The number "1"
5317 * Image:tree.jpg|A tree
5318 * given as text will return the HTML of a gallery with two images,
5319 * labeled 'The number "1"' and
5322 * @param string $text
5323 * @param array $params
5324 * @return string HTML
5326 public function renderImageGallery( $text, $params ) {
5329 if ( isset( $params['mode'] ) ) {
5330 $mode = $params['mode'];
5334 $ig = ImageGalleryBase
::factory( $mode );
5335 } catch ( MWException
$e ) {
5336 // If invalid type set, fallback to default.
5337 $ig = ImageGalleryBase
::factory( false );
5340 $ig->setContextTitle( $this->mTitle
);
5341 $ig->setShowBytes( false );
5342 $ig->setShowFilename( false );
5343 $ig->setParser( $this );
5344 $ig->setHideBadImages();
5345 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
5347 if ( isset( $params['showfilename'] ) ) {
5348 $ig->setShowFilename( true );
5350 $ig->setShowFilename( false );
5352 if ( isset( $params['caption'] ) ) {
5353 $caption = $params['caption'];
5354 $caption = htmlspecialchars( $caption );
5355 $caption = $this->replaceInternalLinks( $caption );
5356 $ig->setCaptionHtml( $caption );
5358 if ( isset( $params['perrow'] ) ) {
5359 $ig->setPerRow( $params['perrow'] );
5361 if ( isset( $params['widths'] ) ) {
5362 $ig->setWidths( $params['widths'] );
5364 if ( isset( $params['heights'] ) ) {
5365 $ig->setHeights( $params['heights'] );
5367 $ig->setAdditionalOptions( $params );
5369 Hooks
::run( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5371 $lines = StringUtils
::explode( "\n", $text );
5372 foreach ( $lines as $line ) {
5373 # match lines like these:
5374 # Image:someimage.jpg|This is some image
5376 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5378 if ( count( $matches ) == 0 ) {
5382 if ( strpos( $matches[0], '%' ) !== false ) {
5383 $matches[1] = rawurldecode( $matches[1] );
5385 $title = Title
::newFromText( $matches[1], NS_FILE
);
5386 if ( is_null( $title ) ) {
5387 # Bogus title. Ignore these so we don't bomb out later.
5391 # We need to get what handler the file uses, to figure out parameters.
5392 # Note, a hook can overide the file name, and chose an entirely different
5393 # file (which potentially could be of a different type and have different handler).
5396 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5397 array( $this, $title, &$options, &$descQuery ) );
5398 # Don't register it now, as ImageGallery does that later.
5399 $file = $this->fetchFileNoRegister( $title, $options );
5400 $handler = $file ?
$file->getHandler() : false;
5402 wfProfileIn( __METHOD__
. '-getMagicWord' );
5404 'img_alt' => 'gallery-internal-alt',
5405 'img_link' => 'gallery-internal-link',
5408 $paramMap = $paramMap +
$handler->getParamMap();
5409 // We don't want people to specify per-image widths.
5410 // Additionally the width parameter would need special casing anyhow.
5411 unset( $paramMap['img_width'] );
5414 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5415 wfProfileOut( __METHOD__
. '-getMagicWord' );
5420 $handlerOptions = array();
5421 if ( isset( $matches[3] ) ) {
5422 // look for an |alt= definition while trying not to break existing
5423 // captions with multiple pipes (|) in it, until a more sensible grammar
5424 // is defined for images in galleries
5426 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5427 // splitting on '|' is a bit odd, and different from makeImage.
5428 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5429 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
5431 foreach ( $parameterMatches as $parameterMatch ) {
5432 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5434 $paramName = $paramMap[$magicName];
5436 switch ( $paramName ) {
5437 case 'gallery-internal-alt':
5438 $alt = $this->stripAltText( $match, false );
5440 case 'gallery-internal-link':
5441 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5442 $chars = self
::EXT_LINK_URL_CLASS
;
5443 $prots = $this->mUrlProtocols
;
5444 //check to see if link matches an absolute url, if not then it must be a wiki link.
5445 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5448 $localLinkTitle = Title
::newFromText( $linkValue );
5449 if ( $localLinkTitle !== null ) {
5450 $link = $localLinkTitle->getLinkURL();
5455 // Must be a handler specific parameter.
5456 if ( $handler->validateParam( $paramName, $match ) ) {
5457 $handlerOptions[$paramName] = $match;
5459 // Guess not. Append it to the caption.
5460 wfDebug( "$parameterMatch failed parameter validation\n" );
5461 $label .= '|' . $parameterMatch;
5466 // concatenate all other pipes
5467 $label .= '|' . $parameterMatch;
5470 // remove the first pipe
5471 $label = substr( $label, 1 );
5474 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5476 $html = $ig->toHTML();
5477 Hooks
::run( 'AfterParserFetchFileAndTitle', array( $this, $ig, &$html ) );
5482 * @param string $handler
5485 public function getImageParams( $handler ) {
5487 $handlerClass = get_class( $handler );
5491 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5492 # Initialise static lists
5493 static $internalParamNames = array(
5494 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5495 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5496 'bottom', 'text-bottom' ),
5497 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5498 'upright', 'border', 'link', 'alt', 'class' ),
5500 static $internalParamMap;
5501 if ( !$internalParamMap ) {
5502 $internalParamMap = array();
5503 foreach ( $internalParamNames as $type => $names ) {
5504 foreach ( $names as $name ) {
5505 $magicName = str_replace( '-', '_', "img_$name" );
5506 $internalParamMap[$magicName] = array( $type, $name );
5511 # Add handler params
5512 $paramMap = $internalParamMap;
5514 $handlerParamMap = $handler->getParamMap();
5515 foreach ( $handlerParamMap as $magic => $paramName ) {
5516 $paramMap[$magic] = array( 'handler', $paramName );
5519 $this->mImageParams
[$handlerClass] = $paramMap;
5520 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5522 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5526 * Parse image options text and use it to make an image
5528 * @param Title $title
5529 * @param string $options
5530 * @param LinkHolderArray|bool $holders
5531 * @return string HTML
5533 public function makeImage( $title, $options, $holders = false ) {
5534 # Check if the options text is of the form "options|alt text"
5536 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5537 # * left no resizing, just left align. label is used for alt= only
5538 # * right same, but right aligned
5539 # * none same, but not aligned
5540 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5541 # * center center the image
5542 # * frame Keep original image size, no magnify-button.
5543 # * framed Same as "frame"
5544 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5545 # * upright reduce width for upright images, rounded to full __0 px
5546 # * border draw a 1px border around the image
5547 # * alt Text for HTML alt attribute (defaults to empty)
5548 # * class Set a class for img node
5549 # * link Set the target of the image link. Can be external, interwiki, or local
5550 # vertical-align values (no % or length right now):
5560 $parts = StringUtils
::explode( "|", $options );
5562 # Give extensions a chance to select the file revision for us
5565 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5566 array( $this, $title, &$options, &$descQuery ) );
5567 # Fetch and register the file (file title may be different via hooks)
5568 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5571 $handler = $file ?
$file->getHandler() : false;
5573 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5576 $this->addTrackingCategory( 'broken-file-category' );
5579 # Process the input parameters
5581 $params = array( 'frame' => array(), 'handler' => array(),
5582 'horizAlign' => array(), 'vertAlign' => array() );
5583 $seenformat = false;
5584 foreach ( $parts as $part ) {
5585 $part = trim( $part );
5586 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5588 if ( isset( $paramMap[$magicName] ) ) {
5589 list( $type, $paramName ) = $paramMap[$magicName];
5591 # Special case; width and height come in one variable together
5592 if ( $type === 'handler' && $paramName === 'width' ) {
5593 $parsedWidthParam = $this->parseWidthParam( $value );
5594 if ( isset( $parsedWidthParam['width'] ) ) {
5595 $width = $parsedWidthParam['width'];
5596 if ( $handler->validateParam( 'width', $width ) ) {
5597 $params[$type]['width'] = $width;
5601 if ( isset( $parsedWidthParam['height'] ) ) {
5602 $height = $parsedWidthParam['height'];
5603 if ( $handler->validateParam( 'height', $height ) ) {
5604 $params[$type]['height'] = $height;
5608 # else no validation -- bug 13436
5610 if ( $type === 'handler' ) {
5611 # Validate handler parameter
5612 $validated = $handler->validateParam( $paramName, $value );
5614 # Validate internal parameters
5615 switch ( $paramName ) {
5619 # @todo FIXME: Possibly check validity here for
5620 # manualthumb? downstream behavior seems odd with
5621 # missing manual thumbs.
5623 $value = $this->stripAltText( $value, $holders );
5626 $chars = self
::EXT_LINK_URL_CLASS
;
5627 $prots = $this->mUrlProtocols
;
5628 if ( $value === '' ) {
5629 $paramName = 'no-link';
5632 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5633 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5634 $paramName = 'link-url';
5635 $this->mOutput
->addExternalLink( $value );
5636 if ( $this->mOptions
->getExternalLinkTarget() ) {
5637 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5642 $linkTitle = Title
::newFromText( $value );
5644 $paramName = 'link-title';
5645 $value = $linkTitle;
5646 $this->mOutput
->addLink( $linkTitle );
5654 // use first appearing option, discard others.
5655 $validated = ! $seenformat;
5659 # Most other things appear to be empty or numeric...
5660 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5665 $params[$type][$paramName] = $value;
5669 if ( !$validated ) {
5674 # Process alignment parameters
5675 if ( $params['horizAlign'] ) {
5676 $params['frame']['align'] = key( $params['horizAlign'] );
5678 if ( $params['vertAlign'] ) {
5679 $params['frame']['valign'] = key( $params['vertAlign'] );
5682 $params['frame']['caption'] = $caption;
5684 # Will the image be presented in a frame, with the caption below?
5685 $imageIsFramed = isset( $params['frame']['frame'] )
5686 ||
isset( $params['frame']['framed'] )
5687 ||
isset( $params['frame']['thumbnail'] )
5688 ||
isset( $params['frame']['manualthumb'] );
5690 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5691 # came to also set the caption, ordinary text after the image -- which
5692 # makes no sense, because that just repeats the text multiple times in
5693 # screen readers. It *also* came to set the title attribute.
5695 # Now that we have an alt attribute, we should not set the alt text to
5696 # equal the caption: that's worse than useless, it just repeats the
5697 # text. This is the framed/thumbnail case. If there's no caption, we
5698 # use the unnamed parameter for alt text as well, just for the time be-
5699 # ing, if the unnamed param is set and the alt param is not.
5701 # For the future, we need to figure out if we want to tweak this more,
5702 # e.g., introducing a title= parameter for the title; ignoring the un-
5703 # named parameter entirely for images without a caption; adding an ex-
5704 # plicit caption= parameter and preserving the old magic unnamed para-
5706 if ( $imageIsFramed ) { # Framed image
5707 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5708 # No caption or alt text, add the filename as the alt text so
5709 # that screen readers at least get some description of the image
5710 $params['frame']['alt'] = $title->getText();
5712 # Do not set $params['frame']['title'] because tooltips don't make sense
5714 } else { # Inline image
5715 if ( !isset( $params['frame']['alt'] ) ) {
5716 # No alt text, use the "caption" for the alt text
5717 if ( $caption !== '' ) {
5718 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5720 # No caption, fall back to using the filename for the
5722 $params['frame']['alt'] = $title->getText();
5725 # Use the "caption" for the tooltip text
5726 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5729 Hooks
::run( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5731 # Linker does the rest
5732 $time = isset( $options['time'] ) ?
$options['time'] : false;
5733 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5734 $time, $descQuery, $this->mOptions
->getThumbSize() );
5736 # Give the handler a chance to modify the parser object
5738 $handler->parserTransformHook( $this, $file );
5745 * @param string $caption
5746 * @param LinkHolderArray|bool $holders
5747 * @return mixed|string
5749 protected function stripAltText( $caption, $holders ) {
5750 # Strip bad stuff out of the title (tooltip). We can't just use
5751 # replaceLinkHoldersText() here, because if this function is called
5752 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5754 $tooltip = $holders->replaceText( $caption );
5756 $tooltip = $this->replaceLinkHoldersText( $caption );
5759 # make sure there are no placeholders in thumbnail attributes
5760 # that are later expanded to html- so expand them now and
5762 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5763 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5769 * Set a flag in the output object indicating that the content is dynamic and
5770 * shouldn't be cached.
5772 public function disableCache() {
5773 wfDebug( "Parser output marked as uncacheable.\n" );
5774 if ( !$this->mOutput
) {
5775 throw new MWException( __METHOD__
.
5776 " can only be called when actually parsing something" );
5778 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5779 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5783 * Callback from the Sanitizer for expanding items found in HTML attribute
5784 * values, so they can be safely tested and escaped.
5786 * @param string $text
5787 * @param bool|PPFrame $frame
5790 public function attributeStripCallback( &$text, $frame = false ) {
5791 $text = $this->replaceVariables( $text, $frame );
5792 $text = $this->mStripState
->unstripBoth( $text );
5801 public function getTags() {
5803 array_keys( $this->mTransparentTagHooks
),
5804 array_keys( $this->mTagHooks
),
5805 array_keys( $this->mFunctionTagHooks
)
5810 * Replace transparent tags in $text with the values given by the callbacks.
5812 * Transparent tag hooks are like regular XML-style tag hooks, except they
5813 * operate late in the transformation sequence, on HTML instead of wikitext.
5815 * @param string $text
5819 public function replaceTransparentTags( $text ) {
5821 $elements = array_keys( $this->mTransparentTagHooks
);
5822 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5823 $replacements = array();
5825 foreach ( $matches as $marker => $data ) {
5826 list( $element, $content, $params, $tag ) = $data;
5827 $tagName = strtolower( $element );
5828 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5829 $output = call_user_func_array(
5830 $this->mTransparentTagHooks
[$tagName],
5831 array( $content, $params, $this )
5836 $replacements[$marker] = $output;
5838 return strtr( $text, $replacements );
5842 * Break wikitext input into sections, and either pull or replace
5843 * some particular section's text.
5845 * External callers should use the getSection and replaceSection methods.
5847 * @param string $text Page wikitext
5848 * @param string|number $sectionId A section identifier string of the form:
5849 * "<flag1> - <flag2> - ... - <section number>"
5851 * Currently the only recognised flag is "T", which means the target section number
5852 * was derived during a template inclusion parse, in other words this is a template
5853 * section edit link. If no flags are given, it was an ordinary section edit link.
5854 * This flag is required to avoid a section numbering mismatch when a section is
5855 * enclosed by "<includeonly>" (bug 6563).
5857 * The section number 0 pulls the text before the first heading; other numbers will
5858 * pull the given section along with its lower-level subsections. If the section is
5859 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5861 * Section 0 is always considered to exist, even if it only contains the empty
5862 * string. If $text is the empty string and section 0 is replaced, $newText is
5865 * @param string $mode One of "get" or "replace"
5866 * @param string $newText Replacement text for section data.
5867 * @return string For "get", the extracted section text.
5868 * for "replace", the whole page with the section replaced.
5870 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5871 global $wgTitle; # not generally used but removes an ugly failure mode
5873 $magicScopeVariable = $this->lock();
5874 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5876 $frame = $this->getPreprocessor()->newFrame();
5878 # Process section extraction flags
5880 $sectionParts = explode( '-', $sectionId );
5881 $sectionIndex = array_pop( $sectionParts );
5882 foreach ( $sectionParts as $part ) {
5883 if ( $part === 'T' ) {
5884 $flags |
= self
::PTD_FOR_INCLUSION
;
5888 # Check for empty input
5889 if ( strval( $text ) === '' ) {
5890 # Only sections 0 and T-0 exist in an empty document
5891 if ( $sectionIndex == 0 ) {
5892 if ( $mode === 'get' ) {
5898 if ( $mode === 'get' ) {
5906 # Preprocess the text
5907 $root = $this->preprocessToDom( $text, $flags );
5909 # <h> nodes indicate section breaks
5910 # They can only occur at the top level, so we can find them by iterating the root's children
5911 $node = $root->getFirstChild();
5913 # Find the target section
5914 if ( $sectionIndex == 0 ) {
5915 # Section zero doesn't nest, level=big
5916 $targetLevel = 1000;
5919 if ( $node->getName() === 'h' ) {
5920 $bits = $node->splitHeading();
5921 if ( $bits['i'] == $sectionIndex ) {
5922 $targetLevel = $bits['level'];
5926 if ( $mode === 'replace' ) {
5927 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5929 $node = $node->getNextSibling();
5935 if ( $mode === 'get' ) {
5942 # Find the end of the section, including nested sections
5944 if ( $node->getName() === 'h' ) {
5945 $bits = $node->splitHeading();
5946 $curLevel = $bits['level'];
5947 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5951 if ( $mode === 'get' ) {
5952 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5954 $node = $node->getNextSibling();
5957 # Write out the remainder (in replace mode only)
5958 if ( $mode === 'replace' ) {
5959 # Output the replacement text
5960 # Add two newlines on -- trailing whitespace in $newText is conventionally
5961 # stripped by the editor, so we need both newlines to restore the paragraph gap
5962 # Only add trailing whitespace if there is newText
5963 if ( $newText != "" ) {
5964 $outText .= $newText . "\n\n";
5968 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5969 $node = $node->getNextSibling();
5973 if ( is_string( $outText ) ) {
5974 # Re-insert stripped tags
5975 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5982 * This function returns the text of a section, specified by a number ($section).
5983 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5984 * the first section before any such heading (section 0).
5986 * If a section contains subsections, these are also returned.
5988 * @param string $text Text to look in
5989 * @param string|number $sectionId Section identifier as a number or string
5990 * (e.g. 0, 1 or 'T-1').
5991 * @param string $defaultText Default to return if section is not found
5993 * @return string Text of the requested section
5995 public function getSection( $text, $sectionId, $defaultText = '' ) {
5996 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
6000 * This function returns $oldtext after the content of the section
6001 * specified by $section has been replaced with $text. If the target
6002 * section does not exist, $oldtext is returned unchanged.
6004 * @param string $oldText Former text of the article
6005 * @param string|number $sectionId Section identifier as a number or string
6006 * (e.g. 0, 1 or 'T-1').
6007 * @param string $newText Replacing text
6009 * @return string Modified text
6011 public function replaceSection( $oldText, $sectionId, $newText ) {
6012 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
6016 * Get the ID of the revision we are parsing
6020 public function getRevisionId() {
6021 return $this->mRevisionId
;
6025 * Get the revision object for $this->mRevisionId
6027 * @return Revision|null Either a Revision object or null
6028 * @since 1.23 (public since 1.23)
6030 public function getRevisionObject() {
6031 if ( !is_null( $this->mRevisionObject
) ) {
6032 return $this->mRevisionObject
;
6034 if ( is_null( $this->mRevisionId
) ) {
6038 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
6039 return $this->mRevisionObject
;
6043 * Get the timestamp associated with the current revision, adjusted for
6044 * the default server-local timestamp
6047 public function getRevisionTimestamp() {
6048 if ( is_null( $this->mRevisionTimestamp
) ) {
6052 $revObject = $this->getRevisionObject();
6053 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
6055 # The cryptic '' timezone parameter tells to use the site-default
6056 # timezone offset instead of the user settings.
6058 # Since this value will be saved into the parser cache, served
6059 # to other users, and potentially even used inside links and such,
6060 # it needs to be consistent for all visitors.
6061 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
6064 return $this->mRevisionTimestamp
;
6068 * Get the name of the user that edited the last revision
6070 * @return string User name
6072 public function getRevisionUser() {
6073 if ( is_null( $this->mRevisionUser
) ) {
6074 $revObject = $this->getRevisionObject();
6076 # if this template is subst: the revision id will be blank,
6077 # so just use the current user's name
6079 $this->mRevisionUser
= $revObject->getUserText();
6080 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6081 $this->mRevisionUser
= $this->getUser()->getName();
6084 return $this->mRevisionUser
;
6088 * Get the size of the revision
6090 * @return int|null Revision size
6092 public function getRevisionSize() {
6093 if ( is_null( $this->mRevisionSize
) ) {
6094 $revObject = $this->getRevisionObject();
6096 # if this variable is subst: the revision id will be blank,
6097 # so just use the parser input size, because the own substituation
6098 # will change the size.
6100 $this->mRevisionSize
= $revObject->getSize();
6101 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6102 $this->mRevisionSize
= $this->mInputSize
;
6105 return $this->mRevisionSize
;
6109 * Mutator for $mDefaultSort
6111 * @param string $sort New value
6113 public function setDefaultSort( $sort ) {
6114 $this->mDefaultSort
= $sort;
6115 $this->mOutput
->setProperty( 'defaultsort', $sort );
6119 * Accessor for $mDefaultSort
6120 * Will use the empty string if none is set.
6122 * This value is treated as a prefix, so the
6123 * empty string is equivalent to sorting by
6128 public function getDefaultSort() {
6129 if ( $this->mDefaultSort
!== false ) {
6130 return $this->mDefaultSort
;
6137 * Accessor for $mDefaultSort
6138 * Unlike getDefaultSort(), will return false if none is set
6140 * @return string|bool
6142 public function getCustomDefaultSort() {
6143 return $this->mDefaultSort
;
6147 * Try to guess the section anchor name based on a wikitext fragment
6148 * presumably extracted from a heading, for example "Header" from
6151 * @param string $text
6155 public function guessSectionNameFromWikiText( $text ) {
6156 # Strip out wikitext links(they break the anchor)
6157 $text = $this->stripSectionName( $text );
6158 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6159 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
6163 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6164 * instead. For use in redirects, since IE6 interprets Redirect: headers
6165 * as something other than UTF-8 (apparently?), resulting in breakage.
6167 * @param string $text The section name
6168 * @return string An anchor
6170 public function guessLegacySectionNameFromWikiText( $text ) {
6171 # Strip out wikitext links(they break the anchor)
6172 $text = $this->stripSectionName( $text );
6173 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6174 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
6178 * Strips a text string of wikitext for use in a section anchor
6180 * Accepts a text string and then removes all wikitext from the
6181 * string and leaves only the resultant text (i.e. the result of
6182 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6183 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6184 * to create valid section anchors by mimicing the output of the
6185 * parser when headings are parsed.
6187 * @param string $text Text string to be stripped of wikitext
6188 * for use in a Section anchor
6189 * @return string Filtered text string
6191 public function stripSectionName( $text ) {
6192 # Strip internal link markup
6193 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6194 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6196 # Strip external link markup
6197 # @todo FIXME: Not tolerant to blank link text
6198 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6199 # on how many empty links there are on the page - need to figure that out.
6200 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6202 # Parse wikitext quotes (italics & bold)
6203 $text = $this->doQuotes( $text );
6206 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
6211 * strip/replaceVariables/unstrip for preprocessor regression testing
6213 * @param string $text
6214 * @param Title $title
6215 * @param ParserOptions $options
6216 * @param int $outputType
6220 public function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
6221 $magicScopeVariable = $this->lock();
6222 $this->startParse( $title, $options, $outputType, true );
6224 $text = $this->replaceVariables( $text );
6225 $text = $this->mStripState
->unstripBoth( $text );
6226 $text = Sanitizer
::removeHTMLtags( $text );
6231 * @param string $text
6232 * @param Title $title
6233 * @param ParserOptions $options
6236 public function testPst( $text, Title
$title, ParserOptions
$options ) {
6237 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6241 * @param string $text
6242 * @param Title $title
6243 * @param ParserOptions $options
6246 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
6247 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
6251 * Call a callback function on all regions of the given text that are not
6252 * inside strip markers, and replace those regions with the return value
6253 * of the callback. For example, with input:
6257 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6258 * two strings will be replaced with the value returned by the callback in
6262 * @param callable $callback
6266 public function markerSkipCallback( $s, $callback ) {
6269 while ( $i < strlen( $s ) ) {
6270 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
6271 if ( $markerStart === false ) {
6272 $out .= call_user_func( $callback, substr( $s, $i ) );
6275 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6276 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6277 if ( $markerEnd === false ) {
6278 $out .= substr( $s, $markerStart );
6281 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6282 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6291 * Remove any strip markers found in the given text.
6293 * @param string $text Input string
6296 public function killMarkers( $text ) {
6297 return $this->mStripState
->killMarkers( $text );
6301 * Save the parser state required to convert the given half-parsed text to
6302 * HTML. "Half-parsed" in this context means the output of
6303 * recursiveTagParse() or internalParse(). This output has strip markers
6304 * from replaceVariables (extensionSubstitution() etc.), and link
6305 * placeholders from replaceLinkHolders().
6307 * Returns an array which can be serialized and stored persistently. This
6308 * array can later be loaded into another parser instance with
6309 * unserializeHalfParsedText(). The text can then be safely incorporated into
6310 * the return value of a parser hook.
6312 * @param string $text
6316 public function serializeHalfParsedText( $text ) {
6319 'version' => self
::HALF_PARSED_VERSION
,
6320 'stripState' => $this->mStripState
->getSubState( $text ),
6321 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6327 * Load the parser state given in the $data array, which is assumed to
6328 * have been generated by serializeHalfParsedText(). The text contents is
6329 * extracted from the array, and its markers are transformed into markers
6330 * appropriate for the current Parser instance. This transformed text is
6331 * returned, and can be safely included in the return value of a parser
6334 * If the $data array has been stored persistently, the caller should first
6335 * check whether it is still valid, by calling isValidHalfParsedText().
6337 * @param array $data Serialized data
6338 * @throws MWException
6341 public function unserializeHalfParsedText( $data ) {
6342 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6343 throw new MWException( __METHOD__
. ': invalid version' );
6346 # First, extract the strip state.
6347 $texts = array( $data['text'] );
6348 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6350 # Now renumber links
6351 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6353 # Should be good to go.
6358 * Returns true if the given array, presumed to be generated by
6359 * serializeHalfParsedText(), is compatible with the current version of the
6362 * @param array $data
6366 public function isValidHalfParsedText( $data ) {
6367 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6371 * Parsed a width param of imagelink like 300px or 200x300px
6373 * @param string $value
6378 public function parseWidthParam( $value ) {
6379 $parsedWidthParam = array();
6380 if ( $value === '' ) {
6381 return $parsedWidthParam;
6384 # (bug 13500) In both cases (width/height and width only),
6385 # permit trailing "px" for backward compatibility.
6386 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6387 $width = intval( $m[1] );
6388 $height = intval( $m[2] );
6389 $parsedWidthParam['width'] = $width;
6390 $parsedWidthParam['height'] = $height;
6391 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6392 $width = intval( $value );
6393 $parsedWidthParam['width'] = $width;
6395 return $parsedWidthParam;
6399 * Lock the current instance of the parser.
6401 * This is meant to stop someone from calling the parser
6402 * recursively and messing up all the strip state.
6404 * @throws MWException If parser is in a parse
6405 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6407 protected function lock() {
6408 if ( $this->mInParse
) {
6409 throw new MWException( "Parser state cleared while parsing. "
6410 . "Did you call Parser::parse recursively?" );
6412 $this->mInParse
= true;
6415 $recursiveCheck = new ScopedCallback( function() use ( $that ) {
6416 $that->mInParse
= false;
6419 return $recursiveCheck;
6423 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6425 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6426 * or if there is more than one <p/> tag in the input HTML.
6428 * @param string $html
6432 public static function stripOuterParagraph( $html ) {
6434 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6435 if ( strpos( $m[1], '</p>' ) === false ) {
6444 * Return this parser if it is not doing anything, otherwise
6445 * get a fresh parser. You can use this method by doing
6446 * $myParser = $wgParser->getFreshParser(), or more simply
6447 * $wgParser->getFreshParser()->parse( ... );
6448 * if you're unsure if $wgParser is safe to use.
6451 * @return Parser A parser object that is not parsing anything
6453 public function getFreshParser() {
6454 global $wgParserConf;
6455 if ( $this->mInParse
) {
6456 return new $wgParserConf['class']( $wgParserConf );