3 * PHP parser that converts wiki markup to HTML.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * @defgroup Parser Parser
29 * PHP Parser - Processes wiki markup (which uses a more user-friendly
30 * syntax, such as "[[link]]" for making links), and provides a one-way
31 * transformation of that wiki markup it into (X)HTML output / markup
32 * (which in turn the browser understands, and can display).
34 * There are seven main entry points into the Parser class:
37 * produces HTML output
38 * - Parser::preSaveTransform()
39 * produces altered wiki markup
40 * - Parser::preprocess()
41 * removes HTML comments and expands templates
42 * - Parser::cleanSig() and Parser::cleanSigInSig()
43 * cleans a signature before saving it to preferences
44 * - Parser::getSection()
45 * return the content of a section from an article for section editing
46 * - Parser::replaceSection()
47 * replaces a section by number inside an article
48 * - Parser::getPreloadText()
49 * removes <noinclude> sections and <includeonly> tags
54 * @warning $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
57 * $wgNamespacesWithSubpages
59 * @par Settings only within ParserOptions:
60 * $wgAllowExternalImages
61 * $wgAllowSpecialInclusion
69 * Update this version number when the ParserOutput format
70 * changes in an incompatible way, so the parser cache
71 * can automatically discard old data.
73 const VERSION
= '1.6.4';
76 * Update this version number when the output of serialiseHalfParsedText()
77 * changes in an incompatible way
79 const HALF_PARSED_VERSION
= 2;
81 # Flags for Parser::setFunctionHook
82 # Also available as global constants from Defines.php
83 const SFH_NO_HASH
= 1;
84 const SFH_OBJECT_ARGS
= 2;
86 # Constants needed for external link processing
87 # Everything except bracket, space, or control characters
88 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
89 # as well as U+3000 is IDEOGRAPHIC SPACE for bug 19052
90 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}]';
91 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F\p{Zs}]+)
92 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
94 # State constants for the definition list colon extraction
95 const COLON_STATE_TEXT
= 0;
96 const COLON_STATE_TAG
= 1;
97 const COLON_STATE_TAGSTART
= 2;
98 const COLON_STATE_CLOSETAG
= 3;
99 const COLON_STATE_TAGSLASH
= 4;
100 const COLON_STATE_COMMENT
= 5;
101 const COLON_STATE_COMMENTDASH
= 6;
102 const COLON_STATE_COMMENTDASHDASH
= 7;
104 # Flags for preprocessToDom
105 const PTD_FOR_INCLUSION
= 1;
107 # Allowed values for $this->mOutputType
108 # Parameter to startExternalParse().
109 const OT_HTML
= 1; # like parse()
110 const OT_WIKI
= 2; # like preSaveTransform()
111 const OT_PREPROCESS
= 3; # like preprocess()
113 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
115 # Marker Suffix needs to be accessible staticly.
116 const MARKER_SUFFIX
= "-QINU\x7f";
118 # Markers used for wrapping the table of contents
119 const TOC_START
= '<mw:toc>';
120 const TOC_END
= '</mw:toc>';
123 public $mTagHooks = array();
124 public $mTransparentTagHooks = array();
125 public $mFunctionHooks = array();
126 public $mFunctionSynonyms = array( 0 => array(), 1 => array() );
127 public $mFunctionTagHooks = array();
128 public $mStripList = array();
129 public $mDefaultStripList = array();
130 public $mVarCache = array();
131 public $mImageParams = array();
132 public $mImageParamsMagicArray = array();
133 public $mMarkerIndex = 0;
134 public $mFirstCall = true;
136 # Initialised by initialiseVariables()
139 * @var MagicWordArray
144 * @var MagicWordArray
147 public $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
149 # Cleared with clearState():
154 public $mAutonumber, $mDTopen;
161 public $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
163 * @var LinkHolderArray
165 public $mLinkHolders;
168 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
169 public $mDefaultSort;
170 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
171 public $mExpensiveFunctionCount; # number of expensive parser function calls
172 public $mShowToc, $mForceTocPosition;
177 public $mUser; # User object; only used when doing pre-save transform
180 # These are variables reset at least once per parse regardless of $clearState
190 public $mTitle; # Title context, used for self-link rendering and similar things
191 public $mOutputType; # Output type, one of the OT_xxx constants
192 public $ot; # Shortcut alias, see setOutputType()
193 public $mRevisionObject; # The revision object of the specified revision ID
194 public $mRevisionId; # ID to display in {{REVISIONID}} tags
195 public $mRevisionTimestamp; # The timestamp of the specified revision ID
196 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag
197 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
198 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp
199 public $mInputSize = false; # For {{PAGESIZE}} on current page.
207 * @var array Array with the language name of each language link (i.e. the
208 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
209 * duplicate language links to the ParserOutput.
211 public $mLangLinkLanguages;
214 * @var MapCacheLRU|null
217 * A cache of the current revisions of titles. Keys are $title->getPrefixedDbKey()
219 public $currentRevisionCache;
222 * @var bool Recursive call protection.
223 * This variable should be treated as if it were private.
225 public $mInParse = false;
227 /** @var SectionProfiler */
228 protected $mProfiler;
233 public function __construct( $conf = array() ) {
234 $this->mConf
= $conf;
235 $this->mUrlProtocols
= wfUrlProtocols();
236 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
237 self
::EXT_LINK_URL_CLASS
. '+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
238 if ( isset( $conf['preprocessorClass'] ) ) {
239 $this->mPreprocessorClass
= $conf['preprocessorClass'];
240 } elseif ( defined( 'HPHP_VERSION' ) ) {
241 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
242 $this->mPreprocessorClass
= 'Preprocessor_Hash';
243 } elseif ( extension_loaded( 'domxml' ) ) {
244 # PECL extension that conflicts with the core DOM extension (bug 13770)
245 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
246 $this->mPreprocessorClass
= 'Preprocessor_Hash';
247 } elseif ( extension_loaded( 'dom' ) ) {
248 $this->mPreprocessorClass
= 'Preprocessor_DOM';
250 $this->mPreprocessorClass
= 'Preprocessor_Hash';
252 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
256 * Reduce memory usage to reduce the impact of circular references
258 public function __destruct() {
259 if ( isset( $this->mLinkHolders
) ) {
260 unset( $this->mLinkHolders
);
262 foreach ( $this as $name => $value ) {
263 unset( $this->$name );
268 * Allow extensions to clean up when the parser is cloned
270 public function __clone() {
271 $this->mInParse
= false;
273 // Bug 56226: When you create a reference "to" an object field, that
274 // makes the object field itself be a reference too (until the other
275 // reference goes out of scope). When cloning, any field that's a
276 // reference is copied as a reference in the new object. Both of these
277 // are defined PHP5 behaviors, as inconvenient as it is for us when old
278 // hooks from PHP4 days are passing fields by reference.
279 foreach ( array( 'mStripState', 'mVarCache' ) as $k ) {
280 // Make a non-reference copy of the field, then rebind the field to
281 // reference the new copy.
287 wfRunHooks( 'ParserCloned', array( $this ) );
291 * Do various kinds of initialisation on the first call of the parser
293 public function firstCallInit() {
294 if ( !$this->mFirstCall
) {
297 $this->mFirstCall
= false;
299 wfProfileIn( __METHOD__
);
301 CoreParserFunctions
::register( $this );
302 CoreTagHooks
::register( $this );
303 $this->initialiseVariables();
305 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
306 wfProfileOut( __METHOD__
);
314 public function clearState() {
315 wfProfileIn( __METHOD__
);
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 wfRunHooks( 'ParserClearState', array( &$this ) );
374 wfProfileOut( __METHOD__
);
378 * Convert wikitext to HTML
379 * Do not call this function recursively.
381 * @param string $text Text we want to parse
382 * @param Title $title
383 * @param ParserOptions $options
384 * @param bool $linestart
385 * @param bool $clearState
386 * @param int $revid Number to pass in {{REVISIONID}}
387 * @return ParserOutput A ParserOutput
389 public function parse( $text, Title
$title, ParserOptions
$options,
390 $linestart = true, $clearState = true, $revid = null
393 * First pass--just handle <nowiki> sections, pass the rest off
394 * to internalParse() which does all the real work.
397 global $wgShowHostnames;
398 $fname = __METHOD__
. '-' . wfGetCaller();
399 wfProfileIn( __METHOD__
);
400 wfProfileIn( $fname );
403 $magicScopeVariable = $this->lock();
406 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
408 $this->currentRevisionCache
= null;
409 $this->mInputSize
= strlen( $text );
410 if ( $this->mOptions
->getEnableLimitReport() ) {
411 $this->mOutput
->resetParseStartTime();
414 # Remove the strip marker tag prefix from the input, if present.
416 $text = str_replace( $this->mUniqPrefix
, '', $text );
419 $oldRevisionId = $this->mRevisionId
;
420 $oldRevisionObject = $this->mRevisionObject
;
421 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
422 $oldRevisionUser = $this->mRevisionUser
;
423 $oldRevisionSize = $this->mRevisionSize
;
424 if ( $revid !== null ) {
425 $this->mRevisionId
= $revid;
426 $this->mRevisionObject
= null;
427 $this->mRevisionTimestamp
= null;
428 $this->mRevisionUser
= null;
429 $this->mRevisionSize
= null;
432 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
434 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
435 $text = $this->internalParse( $text );
436 wfRunHooks( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
438 $text = $this->internalParseHalfParsed( $text, true, $linestart );
441 * A converted title will be provided in the output object if title and
442 * content conversion are enabled, the article text does not contain
443 * a conversion-suppressing double-underscore tag, and no
444 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
445 * automatic link conversion.
447 if ( !( $options->getDisableTitleConversion()
448 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
449 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
450 ||
$this->mOutput
->getDisplayTitle() !== false )
452 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
453 if ( $convruletitle ) {
454 $this->mOutput
->setTitleText( $convruletitle );
456 $titleText = $this->getConverterLanguage()->convertTitle( $title );
457 $this->mOutput
->setTitleText( $titleText );
461 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
462 $this->limitationWarn( 'expensive-parserfunction',
463 $this->mExpensiveFunctionCount
,
464 $this->mOptions
->getExpensiveParserFunctionLimit()
468 # Information on include size limits, for the benefit of users who try to skirt them
469 if ( $this->mOptions
->getEnableLimitReport() ) {
470 $max = $this->mOptions
->getMaxIncludeSize();
472 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
473 if ( $cpuTime !== null ) {
474 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
475 sprintf( "%.3f", $cpuTime )
479 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
480 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
481 sprintf( "%.3f", $wallTime )
484 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
485 array( $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() )
487 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
488 array( $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() )
490 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
491 array( $this->mIncludeSizes
['post-expand'], $max )
493 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
494 array( $this->mIncludeSizes
['arg'], $max )
496 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
497 array( $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() )
499 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
500 array( $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() )
502 wfRunHooks( 'ParserLimitReportPrepare', array( $this, $this->mOutput
) );
504 $limitReport = "NewPP limit report\n";
505 if ( $wgShowHostnames ) {
506 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
508 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
509 if ( wfRunHooks( 'ParserLimitReportFormat',
510 array( $key, &$value, &$limitReport, false, false )
512 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
513 $valueMsg = wfMessage( array( "$key-value-text", "$key-value" ) )
514 ->inLanguage( 'en' )->useDatabase( false );
515 if ( !$valueMsg->exists() ) {
516 $valueMsg = new RawMessage( '$1' );
518 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
519 $valueMsg->params( $value );
520 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
524 // Since we're not really outputting HTML, decode the entities and
525 // then re-encode the things that need hiding inside HTML comments.
526 $limitReport = htmlspecialchars_decode( $limitReport );
527 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
529 // Sanitize for comment. Note '‐' in the replacement is U+2010,
530 // which looks much like the problematic '-'.
531 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&' ), $limitReport );
532 $text .= "\n<!-- \n$limitReport-->\n";
534 // Add on template profiling data
535 $dataByFunc = $this->mProfiler
->getFunctionStats();
536 uasort( $dataByFunc, function( $a, $b ) {
537 return $a['real'] < $b['real']; // descending order
539 $profileReport = "Transclusion expansion time report (%,ms,calls,template)\n";
540 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
541 $profileReport .= sprintf( "%6.2f%% %8.3f %6d - %s\n",
542 $item['%real'], $item['real'], $item['calls'],
543 htmlspecialchars($item['name'] ) );
545 $text .= "\n<!-- \n$profileReport-->\n";
547 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
548 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
549 $this->mTitle
->getPrefixedDBkey() );
552 $this->mOutput
->setText( $text );
554 $this->mRevisionId
= $oldRevisionId;
555 $this->mRevisionObject
= $oldRevisionObject;
556 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
557 $this->mRevisionUser
= $oldRevisionUser;
558 $this->mRevisionSize
= $oldRevisionSize;
559 $this->mInputSize
= false;
560 $this->currentRevisionCache
= null;
561 wfProfileOut( $fname );
562 wfProfileOut( __METHOD__
);
564 return $this->mOutput
;
568 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
569 * can be called from an extension tag hook.
571 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
572 * instead, which means that lists and links have not been fully parsed yet,
573 * and strip markers are still present.
575 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
577 * Use this function if you're a parser tag hook and you want to parse
578 * wikitext before or after applying additional transformations, and you
579 * intend to *return the result as hook output*, which will cause it to go
580 * through the rest of parsing process automatically.
582 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
583 * $text are not expanded
585 * @param string $text Text extension wants to have parsed
586 * @param bool|PPFrame $frame The frame to use for expanding any template variables
587 * @return string UNSAFE half-parsed HTML
589 public function recursiveTagParse( $text, $frame = false ) {
590 wfProfileIn( __METHOD__
);
591 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
592 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
593 $text = $this->internalParse( $text, false, $frame );
594 wfProfileOut( __METHOD__
);
599 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
600 * point can be called from an extension tag hook.
602 * The output of this function is fully-parsed HTML that is safe for output.
603 * If you're a parser tag hook, you might want to use recursiveTagParse()
606 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
607 * $text are not expanded
611 * @param string $text Text extension wants to have parsed
612 * @param bool|PPFrame $frame The frame to use for expanding any template variables
613 * @return string Fully parsed HTML
615 public function recursiveTagParseFully( $text, $frame = false ) {
616 wfProfileIn( __METHOD__
);
617 $text = $this->recursiveTagParse( $text, $frame );
618 $text = $this->internalParseHalfParsed( $text, false );
619 wfProfileOut( __METHOD__
);
624 * Expand templates and variables in the text, producing valid, static wikitext.
625 * Also removes comments.
626 * Do not call this function recursively.
627 * @param string $text
628 * @param Title $title
629 * @param ParserOptions $options
630 * @param int|null $revid
631 * @param bool|PPFrame $frame
632 * @return mixed|string
634 public function preprocess( $text, Title
$title = null, ParserOptions
$options, $revid = null, $frame = false ) {
635 wfProfileIn( __METHOD__
);
636 $magicScopeVariable = $this->lock();
637 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
638 if ( $revid !== null ) {
639 $this->mRevisionId
= $revid;
641 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
642 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
643 $text = $this->replaceVariables( $text, $frame );
644 $text = $this->mStripState
->unstripBoth( $text );
645 wfProfileOut( __METHOD__
);
650 * Recursive parser entry point that can be called from an extension tag
653 * @param string $text Text to be expanded
654 * @param bool|PPFrame $frame The frame to use for expanding any template variables
658 public function recursivePreprocess( $text, $frame = false ) {
659 wfProfileIn( __METHOD__
);
660 $text = $this->replaceVariables( $text, $frame );
661 $text = $this->mStripState
->unstripBoth( $text );
662 wfProfileOut( __METHOD__
);
667 * Process the wikitext for the "?preload=" feature. (bug 5210)
669 * "<noinclude>", "<includeonly>" etc. are parsed as for template
670 * transclusion, comments, templates, arguments, tags hooks and parser
671 * functions are untouched.
673 * @param string $text
674 * @param Title $title
675 * @param ParserOptions $options
676 * @param array $params
679 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = array() ) {
680 $msg = new RawMessage( $text );
681 $text = $msg->params( $params )->plain();
683 # Parser (re)initialisation
684 $magicScopeVariable = $this->lock();
685 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
687 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
688 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
689 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
690 $text = $this->mStripState
->unstripBoth( $text );
695 * Get a random string
699 public static function getRandomString() {
700 return wfRandomString( 16 );
704 * Set the current user.
705 * Should only be used when doing pre-save transform.
707 * @param User|null $user User object or null (to reset)
709 public function setUser( $user ) {
710 $this->mUser
= $user;
714 * Accessor for mUniqPrefix.
718 public function uniqPrefix() {
719 if ( !isset( $this->mUniqPrefix
) ) {
720 # @todo FIXME: This is probably *horribly wrong*
721 # LanguageConverter seems to want $wgParser's uniqPrefix, however
722 # if this is called for a parser cache hit, the parser may not
723 # have ever been initialized in the first place.
724 # Not really sure what the heck is supposed to be going on here.
726 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
728 return $this->mUniqPrefix
;
732 * Set the context title
736 public function setTitle( $t ) {
738 $t = Title
::newFromText( 'NO TITLE' );
741 if ( $t->hasFragment() ) {
742 # Strip the fragment to avoid various odd effects
743 $this->mTitle
= clone $t;
744 $this->mTitle
->setFragment( '' );
751 * Accessor for the Title object
755 public function getTitle() {
756 return $this->mTitle
;
760 * Accessor/mutator for the Title object
762 * @param Title $x Title object or null to just get the current one
765 public function Title( $x = null ) {
766 return wfSetVar( $this->mTitle
, $x );
770 * Set the output type
772 * @param int $ot New value
774 public function setOutputType( $ot ) {
775 $this->mOutputType
= $ot;
778 'html' => $ot == self
::OT_HTML
,
779 'wiki' => $ot == self
::OT_WIKI
,
780 'pre' => $ot == self
::OT_PREPROCESS
,
781 'plain' => $ot == self
::OT_PLAIN
,
786 * Accessor/mutator for the output type
788 * @param int|null $x New value or null to just get the current one
791 public function OutputType( $x = null ) {
792 return wfSetVar( $this->mOutputType
, $x );
796 * Get the ParserOutput object
798 * @return ParserOutput
800 public function getOutput() {
801 return $this->mOutput
;
805 * Get the ParserOptions object
807 * @return ParserOptions
809 public function getOptions() {
810 return $this->mOptions
;
814 * Accessor/mutator for the ParserOptions object
816 * @param ParserOptions $x New value or null to just get the current one
817 * @return ParserOptions Current ParserOptions object
819 public function Options( $x = null ) {
820 return wfSetVar( $this->mOptions
, $x );
826 public function nextLinkID() {
827 return $this->mLinkID++
;
833 public function setLinkID( $id ) {
834 $this->mLinkID
= $id;
838 * Get a language object for use in parser functions such as {{FORMATNUM:}}
841 public function getFunctionLang() {
842 return $this->getTargetLanguage();
846 * Get the target language for the content being parsed. This is usually the
847 * language that the content is in.
851 * @throws MWException
854 public function getTargetLanguage() {
855 $target = $this->mOptions
->getTargetLanguage();
857 if ( $target !== null ) {
859 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
860 return $this->mOptions
->getUserLangObj();
861 } elseif ( is_null( $this->mTitle
) ) {
862 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
865 return $this->mTitle
->getPageLanguage();
869 * Get the language object for language conversion
870 * @return Language|null
872 public function getConverterLanguage() {
873 return $this->getTargetLanguage();
877 * Get a User object either from $this->mUser, if set, or from the
878 * ParserOptions object otherwise
882 public function getUser() {
883 if ( !is_null( $this->mUser
) ) {
886 return $this->mOptions
->getUser();
890 * Get a preprocessor object
892 * @return Preprocessor
894 public function getPreprocessor() {
895 if ( !isset( $this->mPreprocessor
) ) {
896 $class = $this->mPreprocessorClass
;
897 $this->mPreprocessor
= new $class( $this );
899 return $this->mPreprocessor
;
903 * Replaces all occurrences of HTML-style comments and the given tags
904 * in the text with a random marker and returns the next text. The output
905 * parameter $matches will be an associative array filled with data in
909 * 'UNIQ-xxxxx' => array(
912 * array( 'param' => 'x' ),
913 * '<element param="x">tag content</element>' ) )
916 * @param array $elements List of element names. Comments are always extracted.
917 * @param string $text Source text string.
918 * @param array $matches Out parameter, Array: extracted tags
919 * @param string $uniq_prefix
920 * @return string Stripped text
922 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
927 $taglist = implode( '|', $elements );
928 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
930 while ( $text != '' ) {
931 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
933 if ( count( $p ) < 5 ) {
936 if ( count( $p ) > 5 ) {
950 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
951 $stripped .= $marker;
953 if ( $close === '/>' ) {
954 # Empty element tag, <tag />
959 if ( $element === '!--' ) {
962 $end = "/(<\\/$element\\s*>)/i";
964 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
966 if ( count( $q ) < 3 ) {
967 # No end tag -- let it run out to the end of the text.
976 $matches[$marker] = array( $element,
978 Sanitizer
::decodeTagAttributes( $attributes ),
979 "<$element$attributes$close$content$tail" );
985 * Get a list of strippable XML-like elements
989 public function getStripList() {
990 return $this->mStripList
;
994 * Add an item to the strip state
995 * Returns the unique tag which must be inserted into the stripped text
996 * The tag will be replaced with the original text in unstrip()
998 * @param string $text
1002 public function insertStripItem( $text ) {
1003 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
1004 $this->mMarkerIndex++
;
1005 $this->mStripState
->addGeneral( $rnd, $text );
1010 * parse the wiki syntax used to render tables
1013 * @param string $text
1016 public function doTableStuff( $text ) {
1017 wfProfileIn( __METHOD__
);
1019 $lines = StringUtils
::explode( "\n", $text );
1021 $td_history = array(); # Is currently a td tag open?
1022 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
1023 $tr_history = array(); # Is currently a tr tag open?
1024 $tr_attributes = array(); # history of tr attributes
1025 $has_opened_tr = array(); # Did this table open a <tr> element?
1026 $indent_level = 0; # indent level of the table
1028 foreach ( $lines as $outLine ) {
1029 $line = trim( $outLine );
1031 if ( $line === '' ) { # empty line, go to next line
1032 $out .= $outLine . "\n";
1036 $first_character = $line[0];
1039 if ( preg_match( '/^(:*)\{\|(.*)$/', $line, $matches ) ) {
1040 # First check if we are starting a new table
1041 $indent_level = strlen( $matches[1] );
1043 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1044 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1046 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1047 array_push( $td_history, false );
1048 array_push( $last_tag_history, '' );
1049 array_push( $tr_history, false );
1050 array_push( $tr_attributes, '' );
1051 array_push( $has_opened_tr, false );
1052 } elseif ( count( $td_history ) == 0 ) {
1053 # Don't do any of the following
1054 $out .= $outLine . "\n";
1056 } elseif ( substr( $line, 0, 2 ) === '|}' ) {
1057 # We are ending a table
1058 $line = '</table>' . substr( $line, 2 );
1059 $last_tag = array_pop( $last_tag_history );
1061 if ( !array_pop( $has_opened_tr ) ) {
1062 $line = "<tr><td></td></tr>{$line}";
1065 if ( array_pop( $tr_history ) ) {
1066 $line = "</tr>{$line}";
1069 if ( array_pop( $td_history ) ) {
1070 $line = "</{$last_tag}>{$line}";
1072 array_pop( $tr_attributes );
1073 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
1074 } elseif ( substr( $line, 0, 2 ) === '|-' ) {
1075 # Now we have a table row
1076 $line = preg_replace( '#^\|-+#', '', $line );
1078 # Whats after the tag is now only attributes
1079 $attributes = $this->mStripState
->unstripBoth( $line );
1080 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1081 array_pop( $tr_attributes );
1082 array_push( $tr_attributes, $attributes );
1085 $last_tag = array_pop( $last_tag_history );
1086 array_pop( $has_opened_tr );
1087 array_push( $has_opened_tr, true );
1089 if ( array_pop( $tr_history ) ) {
1093 if ( array_pop( $td_history ) ) {
1094 $line = "</{$last_tag}>{$line}";
1098 array_push( $tr_history, false );
1099 array_push( $td_history, false );
1100 array_push( $last_tag_history, '' );
1101 } elseif ( $first_character === '|'
1102 ||
$first_character === '!'
1103 ||
substr( $line, 0, 2 ) === '|+'
1105 # This might be cell elements, td, th or captions
1106 if ( substr( $line, 0, 2 ) === '|+' ) {
1107 $first_character = '+';
1108 $line = substr( $line, 1 );
1111 $line = substr( $line, 1 );
1113 if ( $first_character === '!' ) {
1114 $line = str_replace( '!!', '||', $line );
1117 # Split up multiple cells on the same line.
1118 # FIXME : This can result in improper nesting of tags processed
1119 # by earlier parser steps, but should avoid splitting up eg
1120 # attribute values containing literal "||".
1121 $cells = StringUtils
::explodeMarkup( '||', $line );
1125 # Loop through each table cell
1126 foreach ( $cells as $cell ) {
1128 if ( $first_character !== '+' ) {
1129 $tr_after = array_pop( $tr_attributes );
1130 if ( !array_pop( $tr_history ) ) {
1131 $previous = "<tr{$tr_after}>\n";
1133 array_push( $tr_history, true );
1134 array_push( $tr_attributes, '' );
1135 array_pop( $has_opened_tr );
1136 array_push( $has_opened_tr, true );
1139 $last_tag = array_pop( $last_tag_history );
1141 if ( array_pop( $td_history ) ) {
1142 $previous = "</{$last_tag}>\n{$previous}";
1145 if ( $first_character === '|' ) {
1147 } elseif ( $first_character === '!' ) {
1149 } elseif ( $first_character === '+' ) {
1150 $last_tag = 'caption';
1155 array_push( $last_tag_history, $last_tag );
1157 # A cell could contain both parameters and data
1158 $cell_data = explode( '|', $cell, 2 );
1160 # Bug 553: Note that a '|' inside an invalid link should not
1161 # be mistaken as delimiting cell parameters
1162 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1163 $cell = "{$previous}<{$last_tag}>{$cell}";
1164 } elseif ( count( $cell_data ) == 1 ) {
1165 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1167 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1168 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1169 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1173 array_push( $td_history, true );
1176 $out .= $outLine . "\n";
1179 # Closing open td, tr && table
1180 while ( count( $td_history ) > 0 ) {
1181 if ( array_pop( $td_history ) ) {
1184 if ( array_pop( $tr_history ) ) {
1187 if ( !array_pop( $has_opened_tr ) ) {
1188 $out .= "<tr><td></td></tr>\n";
1191 $out .= "</table>\n";
1194 # Remove trailing line-ending (b/c)
1195 if ( substr( $out, -1 ) === "\n" ) {
1196 $out = substr( $out, 0, -1 );
1199 # special case: don't return empty table
1200 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1204 wfProfileOut( __METHOD__
);
1210 * Helper function for parse() that transforms wiki markup into half-parsed
1211 * HTML. Only called for $mOutputType == self::OT_HTML.
1215 * @param string $text
1216 * @param bool $isMain
1217 * @param bool $frame
1221 public function internalParse( $text, $isMain = true, $frame = false ) {
1222 wfProfileIn( __METHOD__
);
1226 # Hook to suspend the parser in this state
1227 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1228 wfProfileOut( __METHOD__
);
1232 # if $frame is provided, then use $frame for replacing any variables
1234 # use frame depth to infer how include/noinclude tags should be handled
1235 # depth=0 means this is the top-level document; otherwise it's an included document
1236 if ( !$frame->depth
) {
1239 $flag = Parser
::PTD_FOR_INCLUSION
;
1241 $dom = $this->preprocessToDom( $text, $flag );
1242 $text = $frame->expand( $dom );
1244 # if $frame is not provided, then use old-style replaceVariables
1245 $text = $this->replaceVariables( $text );
1248 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1249 $text = Sanitizer
::removeHTMLtags(
1251 array( &$this, 'attributeStripCallback' ),
1253 array_keys( $this->mTransparentTagHooks
)
1255 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1257 # Tables need to come after variable replacement for things to work
1258 # properly; putting them before other transformations should keep
1259 # exciting things like link expansions from showing up in surprising
1261 $text = $this->doTableStuff( $text );
1263 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1265 $text = $this->doDoubleUnderscore( $text );
1267 $text = $this->doHeadings( $text );
1268 $text = $this->replaceInternalLinks( $text );
1269 $text = $this->doAllQuotes( $text );
1270 $text = $this->replaceExternalLinks( $text );
1272 # replaceInternalLinks may sometimes leave behind
1273 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1274 $text = str_replace( $this->mUniqPrefix
. 'NOPARSE', '', $text );
1276 $text = $this->doMagicLinks( $text );
1277 $text = $this->formatHeadings( $text, $origText, $isMain );
1279 wfProfileOut( __METHOD__
);
1284 * Helper function for parse() that transforms half-parsed HTML into fully
1287 * @param string $text
1288 * @param bool $isMain
1289 * @param bool $linestart
1292 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1293 global $wgUseTidy, $wgAlwaysUseTidy;
1295 $text = $this->mStripState
->unstripGeneral( $text );
1297 # Clean up special characters, only run once, next-to-last before doBlockLevels
1299 # french spaces, last one Guillemet-left
1300 # only if there is something before the space
1301 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
1302 # french spaces, Guillemet-right
1303 '/(\\302\\253) /' => '\\1 ',
1304 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
1306 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
1308 $text = $this->doBlockLevels( $text, $linestart );
1310 $this->replaceLinkHolders( $text );
1313 * The input doesn't get language converted if
1315 * b) Content isn't converted
1316 * c) It's a conversion table
1317 * d) it is an interface message (which is in the user language)
1319 if ( !( $this->mOptions
->getDisableContentConversion()
1320 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
1322 if ( !$this->mOptions
->getInterfaceMessage() ) {
1323 # The position of the convert() call should not be changed. it
1324 # assumes that the links are all replaced and the only thing left
1325 # is the <nowiki> mark.
1326 $text = $this->getConverterLanguage()->convert( $text );
1330 $text = $this->mStripState
->unstripNoWiki( $text );
1333 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
1336 $text = $this->replaceTransparentTags( $text );
1337 $text = $this->mStripState
->unstripGeneral( $text );
1339 $text = Sanitizer
::normalizeCharReferences( $text );
1341 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
1342 $text = MWTidy
::tidy( $text );
1344 # attempt to sanitize at least some nesting problems
1345 # (bug #2702 and quite a few others)
1347 # ''Something [http://www.cool.com cool''] -->
1348 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1349 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1350 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1351 # fix up an anchor inside another anchor, only
1352 # at least for a single single nested link (bug 3695)
1353 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1354 '\\1\\2</a>\\3</a>\\1\\4</a>',
1355 # fix div inside inline elements- doBlockLevels won't wrap a line which
1356 # contains a div, so fix it up here; replace
1357 # div with escaped text
1358 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1359 '\\1\\3<div\\5>\\6</div>\\8\\9',
1360 # remove empty italic or bold tag pairs, some
1361 # introduced by rules above
1362 '/<([bi])><\/\\1>/' => '',
1365 $text = preg_replace(
1366 array_keys( $tidyregs ),
1367 array_values( $tidyregs ),
1372 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
1379 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1380 * magic external links.
1385 * @param string $text
1389 public function doMagicLinks( $text ) {
1390 wfProfileIn( __METHOD__
);
1391 $prots = wfUrlProtocolsWithoutProtRel();
1392 $urlChar = self
::EXT_LINK_URL_CLASS
;
1393 $text = preg_replace_callback(
1395 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1396 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1397 (\\b(?i:$prots)$urlChar+) | # m[3]: Free external links" . '
1398 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1399 ISBN\s+(\b # m[5]: ISBN, capture number
1400 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1401 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1402 [0-9Xx] # check digit
1404 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1405 wfProfileOut( __METHOD__
);
1410 * @throws MWException
1412 * @return HTML|string
1414 public function magicLinkCallback( $m ) {
1415 if ( isset( $m[1] ) && $m[1] !== '' ) {
1418 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1421 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1422 # Free external link
1423 return $this->makeFreeExternalLink( $m[0] );
1424 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1426 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1429 $cssClass = 'mw-magiclink-rfc';
1431 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1433 $urlmsg = 'pubmedurl';
1434 $cssClass = 'mw-magiclink-pmid';
1437 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1438 substr( $m[0], 0, 20 ) . '"' );
1440 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1441 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass );
1442 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1445 $num = strtr( $isbn, array(
1450 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1451 return '<a href="' .
1452 htmlspecialchars( $titleObj->getLocalURL() ) .
1453 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1460 * Make a free external link, given a user-supplied URL
1462 * @param string $url
1464 * @return string HTML
1467 public function makeFreeExternalLink( $url ) {
1468 wfProfileIn( __METHOD__
);
1472 # The characters '<' and '>' (which were escaped by
1473 # removeHTMLtags()) should not be included in
1474 # URLs, per RFC 2396.
1476 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1477 $trail = substr( $url, $m2[0][1] ) . $trail;
1478 $url = substr( $url, 0, $m2[0][1] );
1481 # Move trailing punctuation to $trail
1483 # If there is no left bracket, then consider right brackets fair game too
1484 if ( strpos( $url, '(' ) === false ) {
1488 $numSepChars = strspn( strrev( $url ), $sep );
1489 if ( $numSepChars ) {
1490 $trail = substr( $url, -$numSepChars ) . $trail;
1491 $url = substr( $url, 0, -$numSepChars );
1494 $url = Sanitizer
::cleanUrl( $url );
1496 # Is this an external image?
1497 $text = $this->maybeMakeExternalImage( $url );
1498 if ( $text === false ) {
1499 # Not an image, make a link
1500 $text = Linker
::makeExternalLink( $url,
1501 $this->getConverterLanguage()->markNoConversion( $url, true ),
1503 $this->getExternalLinkAttribs( $url ) );
1504 # Register it in the output object...
1505 # Replace unnecessary URL escape codes with their equivalent characters
1506 $pasteurized = self
::normalizeLinkUrl( $url );
1507 $this->mOutput
->addExternalLink( $pasteurized );
1509 wfProfileOut( __METHOD__
);
1510 return $text . $trail;
1514 * Parse headers and return html
1518 * @param string $text
1522 public function doHeadings( $text ) {
1523 wfProfileIn( __METHOD__
);
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 );
1528 wfProfileOut( __METHOD__
);
1533 * Replace single quotes with HTML markup
1536 * @param string $text
1538 * @return string The altered text
1540 public function doAllQuotes( $text ) {
1541 wfProfileIn( __METHOD__
);
1543 $lines = StringUtils
::explode( "\n", $text );
1544 foreach ( $lines as $line ) {
1545 $outtext .= $this->doQuotes( $line ) . "\n";
1547 $outtext = substr( $outtext, 0, -1 );
1548 wfProfileOut( __METHOD__
);
1553 * Helper function for doAllQuotes()
1555 * @param string $text
1559 public function doQuotes( $text ) {
1560 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1561 $countarr = count( $arr );
1562 if ( $countarr == 1 ) {
1566 // First, do some preliminary work. This may shift some apostrophes from
1567 // being mark-up to being text. It also counts the number of occurrences
1568 // of bold and italics mark-ups.
1571 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1572 $thislen = strlen( $arr[$i] );
1573 // If there are ever four apostrophes, assume the first is supposed to
1574 // be text, and the remaining three constitute mark-up for bold text.
1575 // (bug 13227: ''''foo'''' turns into ' ''' foo ' ''')
1576 if ( $thislen == 4 ) {
1577 $arr[$i - 1] .= "'";
1580 } elseif ( $thislen > 5 ) {
1581 // If there are more than 5 apostrophes in a row, assume they're all
1582 // text except for the last 5.
1583 // (bug 13227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1584 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1588 // Count the number of occurrences of bold and italics mark-ups.
1589 if ( $thislen == 2 ) {
1591 } elseif ( $thislen == 3 ) {
1593 } elseif ( $thislen == 5 ) {
1599 // If there is an odd number of both bold and italics, it is likely
1600 // that one of the bold ones was meant to be an apostrophe followed
1601 // by italics. Which one we cannot know for certain, but it is more
1602 // likely to be one that has a single-letter word before it.
1603 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1604 $firstsingleletterword = -1;
1605 $firstmultiletterword = -1;
1607 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1608 if ( strlen( $arr[$i] ) == 3 ) {
1609 $x1 = substr( $arr[$i - 1], -1 );
1610 $x2 = substr( $arr[$i - 1], -2, 1 );
1611 if ( $x1 === ' ' ) {
1612 if ( $firstspace == -1 ) {
1615 } elseif ( $x2 === ' ' ) {
1616 if ( $firstsingleletterword == -1 ) {
1617 $firstsingleletterword = $i;
1618 // if $firstsingleletterword is set, we don't
1619 // look at the other options, so we can bail early.
1623 if ( $firstmultiletterword == -1 ) {
1624 $firstmultiletterword = $i;
1630 // If there is a single-letter word, use it!
1631 if ( $firstsingleletterword > -1 ) {
1632 $arr[$firstsingleletterword] = "''";
1633 $arr[$firstsingleletterword - 1] .= "'";
1634 } elseif ( $firstmultiletterword > -1 ) {
1635 // If not, but there's a multi-letter word, use that one.
1636 $arr[$firstmultiletterword] = "''";
1637 $arr[$firstmultiletterword - 1] .= "'";
1638 } elseif ( $firstspace > -1 ) {
1639 // ... otherwise use the first one that has neither.
1640 // (notice that it is possible for all three to be -1 if, for example,
1641 // there is only one pentuple-apostrophe in the line)
1642 $arr[$firstspace] = "''";
1643 $arr[$firstspace - 1] .= "'";
1647 // Now let's actually convert our apostrophic mush to HTML!
1652 foreach ( $arr as $r ) {
1653 if ( ( $i %
2 ) == 0 ) {
1654 if ( $state === 'both' ) {
1660 $thislen = strlen( $r );
1661 if ( $thislen == 2 ) {
1662 if ( $state === 'i' ) {
1665 } elseif ( $state === 'bi' ) {
1668 } elseif ( $state === 'ib' ) {
1669 $output .= '</b></i><b>';
1671 } elseif ( $state === 'both' ) {
1672 $output .= '<b><i>' . $buffer . '</i>';
1674 } else { // $state can be 'b' or ''
1678 } elseif ( $thislen == 3 ) {
1679 if ( $state === 'b' ) {
1682 } elseif ( $state === 'bi' ) {
1683 $output .= '</i></b><i>';
1685 } elseif ( $state === 'ib' ) {
1688 } elseif ( $state === 'both' ) {
1689 $output .= '<i><b>' . $buffer . '</b>';
1691 } else { // $state can be 'i' or ''
1695 } elseif ( $thislen == 5 ) {
1696 if ( $state === 'b' ) {
1697 $output .= '</b><i>';
1699 } elseif ( $state === 'i' ) {
1700 $output .= '</i><b>';
1702 } elseif ( $state === 'bi' ) {
1703 $output .= '</i></b>';
1705 } elseif ( $state === 'ib' ) {
1706 $output .= '</b></i>';
1708 } elseif ( $state === 'both' ) {
1709 $output .= '<i><b>' . $buffer . '</b></i>';
1711 } else { // ($state == '')
1719 // Now close all remaining tags. Notice that the order is important.
1720 if ( $state === 'b' ||
$state === 'ib' ) {
1723 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1726 if ( $state === 'bi' ) {
1729 // There might be lonely ''''', so make sure we have a buffer
1730 if ( $state === 'both' && $buffer ) {
1731 $output .= '<b><i>' . $buffer . '</i></b>';
1737 * Replace external links (REL)
1739 * Note: this is all very hackish and the order of execution matters a lot.
1740 * Make sure to run tests/parserTests.php if you change this code.
1744 * @param string $text
1746 * @throws MWException
1749 public function replaceExternalLinks( $text ) {
1750 wfProfileIn( __METHOD__
);
1752 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1753 if ( $bits === false ) {
1754 wfProfileOut( __METHOD__
);
1755 throw new MWException( "PCRE needs to be compiled with "
1756 . "--enable-unicode-properties in order for MediaWiki to function" );
1758 $s = array_shift( $bits );
1761 while ( $i < count( $bits ) ) {
1764 $text = $bits[$i++
];
1765 $trail = $bits[$i++
];
1767 # The characters '<' and '>' (which were escaped by
1768 # removeHTMLtags()) should not be included in
1769 # URLs, per RFC 2396.
1771 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1772 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1773 $url = substr( $url, 0, $m2[0][1] );
1776 # If the link text is an image URL, replace it with an <img> tag
1777 # This happened by accident in the original parser, but some people used it extensively
1778 $img = $this->maybeMakeExternalImage( $text );
1779 if ( $img !== false ) {
1785 # Set linktype for CSS - if URL==text, link is essentially free
1786 $linktype = ( $text === $url ) ?
'free' : 'text';
1788 # No link text, e.g. [http://domain.tld/some.link]
1789 if ( $text == '' ) {
1791 $langObj = $this->getTargetLanguage();
1792 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1793 $linktype = 'autonumber';
1795 # Have link text, e.g. [http://domain.tld/some.link text]s
1797 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1800 $text = $this->getConverterLanguage()->markNoConversion( $text );
1802 $url = Sanitizer
::cleanUrl( $url );
1804 # Use the encoded URL
1805 # This means that users can paste URLs directly into the text
1806 # Funny characters like ö aren't valid in URLs anyway
1807 # This was changed in August 2004
1808 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1809 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1811 # Register link in the output object.
1812 # Replace unnecessary URL escape codes with the referenced character
1813 # This prevents spammers from hiding links from the filters
1814 $pasteurized = self
::normalizeLinkUrl( $url );
1815 $this->mOutput
->addExternalLink( $pasteurized );
1818 wfProfileOut( __METHOD__
);
1823 * Get the rel attribute for a particular external link.
1826 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1827 * nofollow if appropriate
1828 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1829 * @return string|null Rel attribute for $url
1831 public static function getExternalLinkRel( $url = false, $title = null ) {
1832 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1833 $ns = $title ?
$title->getNamespace() : false;
1834 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1835 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1843 * Get an associative array of additional HTML attributes appropriate for a
1844 * particular external link. This currently may include rel => nofollow
1845 * (depending on configuration, namespace, and the URL's domain) and/or a
1846 * target attribute (depending on configuration).
1848 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1849 * nofollow if appropriate
1850 * @return array Associative array of HTML attributes
1852 public function getExternalLinkAttribs( $url = false ) {
1854 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1856 if ( $this->mOptions
->getExternalLinkTarget() ) {
1857 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1863 * Replace unusual escape codes in a URL with their equivalent characters
1865 * @deprecated since 1.24, use normalizeLinkUrl
1866 * @param string $url
1869 public static function replaceUnusualEscapes( $url ) {
1870 wfDeprecated( __METHOD__
, '1.24' );
1871 return self
::normalizeLinkUrl( $url );
1875 * Replace unusual escape codes in a URL with their equivalent characters
1877 * This generally follows the syntax defined in RFC 3986, with special
1878 * consideration for HTTP query strings.
1880 * @param string $url
1883 public static function normalizeLinkUrl( $url ) {
1884 # First, make sure unsafe characters are encoded
1885 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
1887 return rawurlencode( $m[0] );
1893 $end = strlen( $url );
1895 # Fragment part - 'fragment'
1896 $start = strpos( $url, '#' );
1897 if ( $start !== false && $start < $end ) {
1898 $ret = self
::normalizeUrlComponent(
1899 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
1903 # Query part - 'query' minus &=+;
1904 $start = strpos( $url, '?' );
1905 if ( $start !== false && $start < $end ) {
1906 $ret = self
::normalizeUrlComponent(
1907 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
1911 # Scheme and path part - 'pchar'
1912 # (we assume no userinfo or encoded colons in the host)
1913 $ret = self
::normalizeUrlComponent(
1914 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
1919 private static function normalizeUrlComponent( $component, $unsafe ) {
1920 $callback = function ( $matches ) use ( $unsafe ) {
1921 $char = urldecode( $matches[0] );
1922 $ord = ord( $char );
1923 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
1927 # Leave it escaped, but use uppercase for a-f
1928 return strtoupper( $matches[0] );
1931 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
1935 * make an image if it's allowed, either through the global
1936 * option, through the exception, or through the on-wiki whitelist
1938 * @param string $url
1942 private function maybeMakeExternalImage( $url ) {
1943 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1944 $imagesexception = !empty( $imagesfrom );
1946 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1947 if ( $imagesexception && is_array( $imagesfrom ) ) {
1948 $imagematch = false;
1949 foreach ( $imagesfrom as $match ) {
1950 if ( strpos( $url, $match ) === 0 ) {
1955 } elseif ( $imagesexception ) {
1956 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1958 $imagematch = false;
1961 if ( $this->mOptions
->getAllowExternalImages()
1962 ||
( $imagesexception && $imagematch )
1964 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1966 $text = Linker
::makeExternalImage( $url );
1969 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1970 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
1972 $whitelist = explode(
1974 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
1977 foreach ( $whitelist as $entry ) {
1978 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1979 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1982 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1983 # Image matches a whitelist entry
1984 $text = Linker
::makeExternalImage( $url );
1993 * Process [[ ]] wikilinks
1997 * @return string Processed text
2001 public function replaceInternalLinks( $s ) {
2002 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
2007 * Process [[ ]] wikilinks (RIL)
2009 * @throws MWException
2010 * @return LinkHolderArray
2014 public function replaceInternalLinks2( &$s ) {
2015 global $wgExtraInterlanguageLinkPrefixes;
2016 wfProfileIn( __METHOD__
);
2018 wfProfileIn( __METHOD__
. '-setup' );
2019 static $tc = false, $e1, $e1_img;
2020 # the % is needed to support urlencoded titles as well
2022 $tc = Title
::legalChars() . '#%';
2023 # Match a link having the form [[namespace:link|alternate]]trail
2024 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2025 # Match cases where there is no "]]", which might still be images
2026 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2029 $holders = new LinkHolderArray( $this );
2031 # split the entire text string on occurrences of [[
2032 $a = StringUtils
::explode( '[[', ' ' . $s );
2033 # get the first element (all text up to first [[), and remove the space we added
2036 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2037 $s = substr( $s, 1 );
2039 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2041 if ( $useLinkPrefixExtension ) {
2042 # Match the end of a line for a word that's not followed by whitespace,
2043 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2045 $charset = $wgContLang->linkPrefixCharset();
2046 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2049 if ( is_null( $this->mTitle
) ) {
2050 wfProfileOut( __METHOD__
. '-setup' );
2051 wfProfileOut( __METHOD__
);
2052 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
2054 $nottalk = !$this->mTitle
->isTalkPage();
2056 if ( $useLinkPrefixExtension ) {
2058 if ( preg_match( $e2, $s, $m ) ) {
2059 $first_prefix = $m[2];
2061 $first_prefix = false;
2067 $useSubpages = $this->areSubpagesAllowed();
2068 wfProfileOut( __METHOD__
. '-setup' );
2070 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
2071 # Loop for each link
2072 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2073 // @codingStandardsIgnoreStart
2075 # Check for excessive memory usage
2076 if ( $holders->isBig() ) {
2078 # Do the existence check, replace the link holders and clear the array
2079 $holders->replace( $s );
2083 if ( $useLinkPrefixExtension ) {
2084 wfProfileIn( __METHOD__
. '-prefixhandling' );
2085 if ( preg_match( $e2, $s, $m ) ) {
2092 if ( $first_prefix ) {
2093 $prefix = $first_prefix;
2094 $first_prefix = false;
2096 wfProfileOut( __METHOD__
. '-prefixhandling' );
2099 $might_be_img = false;
2101 wfProfileIn( __METHOD__
. "-e1" );
2102 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2104 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2105 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2106 # the real problem is with the $e1 regex
2109 # Still some problems for cases where the ] is meant to be outside punctuation,
2110 # and no image is in sight. See bug 2095.
2113 && substr( $m[3], 0, 1 ) === ']'
2114 && strpos( $text, '[' ) !== false
2116 $text .= ']'; # so that replaceExternalLinks($text) works later
2117 $m[3] = substr( $m[3], 1 );
2119 # fix up urlencoded title texts
2120 if ( strpos( $m[1], '%' ) !== false ) {
2121 # Should anchors '#' also be rejected?
2122 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) );
2125 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2126 # Invalid, but might be an image with a link in its caption
2127 $might_be_img = true;
2129 if ( strpos( $m[1], '%' ) !== false ) {
2130 $m[1] = rawurldecode( $m[1] );
2133 } else { # Invalid form; output directly
2134 $s .= $prefix . '[[' . $line;
2135 wfProfileOut( __METHOD__
. "-e1" );
2138 wfProfileOut( __METHOD__
. "-e1" );
2139 wfProfileIn( __METHOD__
. "-misc" );
2143 # Don't allow internal links to pages containing
2144 # PROTO: where PROTO is a valid URL protocol; these
2145 # should be external links.
2146 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2147 $s .= $prefix . '[[' . $line;
2148 wfProfileOut( __METHOD__
. "-misc" );
2152 # Make subpage if necessary
2153 if ( $useSubpages ) {
2154 $link = $this->maybeDoSubpageLink( $origLink, $text );
2159 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2161 # Strip off leading ':'
2162 $link = substr( $link, 1 );
2165 wfProfileOut( __METHOD__
. "-misc" );
2166 wfProfileIn( __METHOD__
. "-title" );
2167 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
2168 if ( $nt === null ) {
2169 $s .= $prefix . '[[' . $line;
2170 wfProfileOut( __METHOD__
. "-title" );
2174 $ns = $nt->getNamespace();
2175 $iw = $nt->getInterwiki();
2176 wfProfileOut( __METHOD__
. "-title" );
2178 if ( $might_be_img ) { # if this is actually an invalid link
2179 wfProfileIn( __METHOD__
. "-might_be_img" );
2180 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2183 # look at the next 'line' to see if we can close it there
2185 $next_line = $a->current();
2186 if ( $next_line === false ||
$next_line === null ) {
2189 $m = explode( ']]', $next_line, 3 );
2190 if ( count( $m ) == 3 ) {
2191 # the first ]] closes the inner link, the second the image
2193 $text .= "[[{$m[0]}]]{$m[1]}";
2196 } elseif ( count( $m ) == 2 ) {
2197 # if there's exactly one ]] that's fine, we'll keep looking
2198 $text .= "[[{$m[0]}]]{$m[1]}";
2200 # if $next_line is invalid too, we need look no further
2201 $text .= '[[' . $next_line;
2206 # we couldn't find the end of this imageLink, so output it raw
2207 # but don't ignore what might be perfectly normal links in the text we've examined
2208 $holders->merge( $this->replaceInternalLinks2( $text ) );
2209 $s .= "{$prefix}[[$link|$text";
2210 # note: no $trail, because without an end, there *is* no trail
2211 wfProfileOut( __METHOD__
. "-might_be_img" );
2214 } else { # it's not an image, so output it raw
2215 $s .= "{$prefix}[[$link|$text";
2216 # note: no $trail, because without an end, there *is* no trail
2217 wfProfileOut( __METHOD__
. "-might_be_img" );
2220 wfProfileOut( __METHOD__
. "-might_be_img" );
2223 $wasblank = ( $text == '' );
2227 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
2228 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2229 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2230 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2231 $text = $this->doQuotes( $text );
2234 # Link not escaped by : , create the various objects
2235 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2237 wfProfileIn( __METHOD__
. "-interwiki" );
2239 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2240 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2241 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2244 # Bug 24502: filter duplicates
2245 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2246 $this->mLangLinkLanguages
[$iw] = true;
2247 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2250 $s = rtrim( $s . $prefix );
2251 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2252 wfProfileOut( __METHOD__
. "-interwiki" );
2255 wfProfileOut( __METHOD__
. "-interwiki" );
2257 if ( $ns == NS_FILE
) {
2258 wfProfileIn( __METHOD__
. "-image" );
2259 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2261 # if no parameters were passed, $text
2262 # becomes something like "File:Foo.png",
2263 # which we don't want to pass on to the
2267 # recursively parse links inside the image caption
2268 # actually, this will parse them in any other parameters, too,
2269 # but it might be hard to fix that, and it doesn't matter ATM
2270 $text = $this->replaceExternalLinks( $text );
2271 $holders->merge( $this->replaceInternalLinks2( $text ) );
2273 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2274 $s .= $prefix . $this->armorLinks(
2275 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2277 $s .= $prefix . $trail;
2279 wfProfileOut( __METHOD__
. "-image" );
2283 if ( $ns == NS_CATEGORY
) {
2284 wfProfileIn( __METHOD__
. "-category" );
2285 $s = rtrim( $s . "\n" ); # bug 87
2288 $sortkey = $this->getDefaultSort();
2292 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2293 $sortkey = str_replace( "\n", '', $sortkey );
2294 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2295 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2298 * Strip the whitespace Category links produce, see bug 87
2300 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2302 wfProfileOut( __METHOD__
. "-category" );
2307 # Self-link checking. For some languages, variants of the title are checked in
2308 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2309 # for linking to a different variant.
2310 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2311 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2315 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2316 # @todo FIXME: Should do batch file existence checks, see comment below
2317 if ( $ns == NS_MEDIA
) {
2318 wfProfileIn( __METHOD__
. "-media" );
2319 # Give extensions a chance to select the file revision for us
2322 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2323 array( $this, $nt, &$options, &$descQuery ) );
2324 # Fetch and register the file (file title may be different via hooks)
2325 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2326 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2327 $s .= $prefix . $this->armorLinks(
2328 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2329 wfProfileOut( __METHOD__
. "-media" );
2333 wfProfileIn( __METHOD__
. "-always_known" );
2334 # Some titles, such as valid special pages or files in foreign repos, should
2335 # be shown as bluelinks even though they're not included in the page table
2337 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2338 # batch file existence checks for NS_FILE and NS_MEDIA
2339 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2340 $this->mOutput
->addLink( $nt );
2341 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2343 # Links will be added to the output link list after checking
2344 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2346 wfProfileOut( __METHOD__
. "-always_known" );
2348 wfProfileOut( __METHOD__
);
2353 * Render a forced-blue link inline; protect against double expansion of
2354 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2355 * Since this little disaster has to split off the trail text to avoid
2356 * breaking URLs in the following text without breaking trails on the
2357 * wiki links, it's been made into a horrible function.
2360 * @param string $text
2361 * @param array|string $query
2362 * @param string $trail
2363 * @param string $prefix
2364 * @return string HTML-wikitext mix oh yuck
2366 public function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2367 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2369 if ( is_string( $query ) ) {
2370 $query = wfCgiToArray( $query );
2372 if ( $text == '' ) {
2373 $text = htmlspecialchars( $nt->getPrefixedText() );
2376 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2378 return $this->armorLinks( $link ) . $trail;
2382 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2383 * going to go through further parsing steps before inline URL expansion.
2385 * Not needed quite as much as it used to be since free links are a bit
2386 * more sensible these days. But bracketed links are still an issue.
2388 * @param string $text More-or-less HTML
2389 * @return string Less-or-more HTML with NOPARSE bits
2391 public function armorLinks( $text ) {
2392 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2393 "{$this->mUniqPrefix}NOPARSE$1", $text );
2397 * Return true if subpage links should be expanded on this page.
2400 public function areSubpagesAllowed() {
2401 # Some namespaces don't allow subpages
2402 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2406 * Handle link to subpage if necessary
2408 * @param string $target The source of the link
2409 * @param string &$text The link text, modified as necessary
2410 * @return string The full name of the link
2413 public function maybeDoSubpageLink( $target, &$text ) {
2414 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2418 * Used by doBlockLevels()
2423 public function closeParagraph() {
2425 if ( $this->mLastSection
!= '' ) {
2426 $result = '</' . $this->mLastSection
. ">\n";
2428 $this->mInPre
= false;
2429 $this->mLastSection
= '';
2434 * getCommon() returns the length of the longest common substring
2435 * of both arguments, starting at the beginning of both.
2438 * @param string $st1
2439 * @param string $st2
2443 public function getCommon( $st1, $st2 ) {
2444 $fl = strlen( $st1 );
2445 $shorter = strlen( $st2 );
2446 if ( $fl < $shorter ) {
2450 for ( $i = 0; $i < $shorter; ++
$i ) {
2451 if ( $st1[$i] != $st2[$i] ) {
2459 * These next three functions open, continue, and close the list
2460 * element appropriate to the prefix character passed into them.
2463 * @param string $char
2467 public function openList( $char ) {
2468 $result = $this->closeParagraph();
2470 if ( '*' === $char ) {
2471 $result .= "<ul><li>";
2472 } elseif ( '#' === $char ) {
2473 $result .= "<ol><li>";
2474 } elseif ( ':' === $char ) {
2475 $result .= "<dl><dd>";
2476 } elseif ( ';' === $char ) {
2477 $result .= "<dl><dt>";
2478 $this->mDTopen
= true;
2480 $result = '<!-- ERR 1 -->';
2488 * @param string $char
2493 public function nextItem( $char ) {
2494 if ( '*' === $char ||
'#' === $char ) {
2495 return "</li>\n<li>";
2496 } elseif ( ':' === $char ||
';' === $char ) {
2498 if ( $this->mDTopen
) {
2501 if ( ';' === $char ) {
2502 $this->mDTopen
= true;
2503 return $close . '<dt>';
2505 $this->mDTopen
= false;
2506 return $close . '<dd>';
2509 return '<!-- ERR 2 -->';
2514 * @param string $char
2519 public function closeList( $char ) {
2520 if ( '*' === $char ) {
2521 $text = "</li></ul>";
2522 } elseif ( '#' === $char ) {
2523 $text = "</li></ol>";
2524 } elseif ( ':' === $char ) {
2525 if ( $this->mDTopen
) {
2526 $this->mDTopen
= false;
2527 $text = "</dt></dl>";
2529 $text = "</dd></dl>";
2532 return '<!-- ERR 3 -->';
2539 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2541 * @param string $text
2542 * @param bool $linestart Whether or not this is at the start of a line.
2544 * @return string The lists rendered as HTML
2546 public function doBlockLevels( $text, $linestart ) {
2547 wfProfileIn( __METHOD__
);
2549 # Parsing through the text line by line. The main thing
2550 # happening here is handling of block-level elements p, pre,
2551 # and making lists from lines starting with * # : etc.
2553 $textLines = StringUtils
::explode( "\n", $text );
2555 $lastPrefix = $output = '';
2556 $this->mDTopen
= $inBlockElem = false;
2558 $paragraphStack = false;
2559 $inBlockquote = false;
2561 foreach ( $textLines as $oLine ) {
2563 if ( !$linestart ) {
2573 $lastPrefixLength = strlen( $lastPrefix );
2574 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2575 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2576 # If not in a <pre> element, scan for and figure out what prefixes are there.
2577 if ( !$this->mInPre
) {
2578 # Multiple prefixes may abut each other for nested lists.
2579 $prefixLength = strspn( $oLine, '*#:;' );
2580 $prefix = substr( $oLine, 0, $prefixLength );
2583 # ; and : are both from definition-lists, so they're equivalent
2584 # for the purposes of determining whether or not we need to open/close
2586 $prefix2 = str_replace( ';', ':', $prefix );
2587 $t = substr( $oLine, $prefixLength );
2588 $this->mInPre
= (bool)$preOpenMatch;
2590 # Don't interpret any other prefixes in preformatted text
2592 $prefix = $prefix2 = '';
2597 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2598 # Same as the last item, so no need to deal with nesting or opening stuff
2599 $output .= $this->nextItem( substr( $prefix, -1 ) );
2600 $paragraphStack = false;
2602 if ( substr( $prefix, -1 ) === ';' ) {
2603 # The one nasty exception: definition lists work like this:
2604 # ; title : definition text
2605 # So we check for : in the remainder text to split up the
2606 # title and definition, without b0rking links.
2608 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2610 $output .= $term . $this->nextItem( ':' );
2613 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2614 # We need to open or close prefixes, or both.
2616 # Either open or close a level...
2617 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2618 $paragraphStack = false;
2620 # Close all the prefixes which aren't shared.
2621 while ( $commonPrefixLength < $lastPrefixLength ) {
2622 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2623 --$lastPrefixLength;
2626 # Continue the current prefix if appropriate.
2627 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2628 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2631 # Open prefixes where appropriate.
2632 if ( $lastPrefix && $prefixLength > $commonPrefixLength ) {
2635 while ( $prefixLength > $commonPrefixLength ) {
2636 $char = substr( $prefix, $commonPrefixLength, 1 );
2637 $output .= $this->openList( $char );
2639 if ( ';' === $char ) {
2640 # @todo FIXME: This is dupe of code above
2641 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2643 $output .= $term . $this->nextItem( ':' );
2646 ++
$commonPrefixLength;
2648 if ( !$prefixLength && $lastPrefix ) {
2651 $lastPrefix = $prefix2;
2654 # If we have no prefixes, go to paragraph mode.
2655 if ( 0 == $prefixLength ) {
2656 wfProfileIn( __METHOD__
. "-paragraph" );
2657 # No prefix (not in list)--go to paragraph mode
2658 # XXX: use a stack for nestable elements like span, table and div
2659 $openmatch = preg_match(
2660 '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|'
2661 . '<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS',
2664 $closematch = preg_match(
2665 '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'
2666 . '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|<\\/mw:|'
2667 . $this->mUniqPrefix
2668 . '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS',
2672 if ( $openmatch ||
$closematch ) {
2673 $paragraphStack = false;
2674 # @todo bug 5718: paragraph closed
2675 $output .= $this->closeParagraph();
2676 if ( $preOpenMatch && !$preCloseMatch ) {
2677 $this->mInPre
= true;
2680 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t, $bqMatch, PREG_OFFSET_CAPTURE
, $bqOffset ) ) {
2681 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
2682 $bqOffset = $bqMatch[0][1] +
strlen( $bqMatch[0][0] );
2684 $inBlockElem = !$closematch;
2685 } elseif ( !$inBlockElem && !$this->mInPre
) {
2686 if ( ' ' == substr( $t, 0, 1 )
2687 && ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' )
2691 if ( $this->mLastSection
!== 'pre' ) {
2692 $paragraphStack = false;
2693 $output .= $this->closeParagraph() . '<pre>';
2694 $this->mLastSection
= 'pre';
2696 $t = substr( $t, 1 );
2699 if ( trim( $t ) === '' ) {
2700 if ( $paragraphStack ) {
2701 $output .= $paragraphStack . '<br />';
2702 $paragraphStack = false;
2703 $this->mLastSection
= 'p';
2705 if ( $this->mLastSection
!== 'p' ) {
2706 $output .= $this->closeParagraph();
2707 $this->mLastSection
= '';
2708 $paragraphStack = '<p>';
2710 $paragraphStack = '</p><p>';
2714 if ( $paragraphStack ) {
2715 $output .= $paragraphStack;
2716 $paragraphStack = false;
2717 $this->mLastSection
= 'p';
2718 } elseif ( $this->mLastSection
!== 'p' ) {
2719 $output .= $this->closeParagraph() . '<p>';
2720 $this->mLastSection
= 'p';
2725 wfProfileOut( __METHOD__
. "-paragraph" );
2727 # somewhere above we forget to get out of pre block (bug 785)
2728 if ( $preCloseMatch && $this->mInPre
) {
2729 $this->mInPre
= false;
2731 if ( $paragraphStack === false ) {
2733 if ( $prefixLength === 0 ) {
2738 while ( $prefixLength ) {
2739 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2741 if ( !$prefixLength ) {
2745 if ( $this->mLastSection
!= '' ) {
2746 $output .= '</' . $this->mLastSection
. '>';
2747 $this->mLastSection
= '';
2750 wfProfileOut( __METHOD__
);
2755 * Split up a string on ':', ignoring any occurrences inside tags
2756 * to prevent illegal overlapping.
2758 * @param string $str The string to split
2759 * @param string &$before Set to everything before the ':'
2760 * @param string &$after Set to everything after the ':'
2761 * @throws MWException
2762 * @return string The position of the ':', or false if none found
2764 public function findColonNoLinks( $str, &$before, &$after ) {
2765 wfProfileIn( __METHOD__
);
2767 $pos = strpos( $str, ':' );
2768 if ( $pos === false ) {
2770 wfProfileOut( __METHOD__
);
2774 $lt = strpos( $str, '<' );
2775 if ( $lt === false ||
$lt > $pos ) {
2776 # Easy; no tag nesting to worry about
2777 $before = substr( $str, 0, $pos );
2778 $after = substr( $str, $pos +
1 );
2779 wfProfileOut( __METHOD__
);
2783 # Ugly state machine to walk through avoiding tags.
2784 $state = self
::COLON_STATE_TEXT
;
2786 $len = strlen( $str );
2787 for ( $i = 0; $i < $len; $i++
) {
2791 # (Using the number is a performance hack for common cases)
2792 case 0: # self::COLON_STATE_TEXT:
2795 # Could be either a <start> tag or an </end> tag
2796 $state = self
::COLON_STATE_TAGSTART
;
2799 if ( $stack == 0 ) {
2801 $before = substr( $str, 0, $i );
2802 $after = substr( $str, $i +
1 );
2803 wfProfileOut( __METHOD__
);
2806 # Embedded in a tag; don't break it.
2809 # Skip ahead looking for something interesting
2810 $colon = strpos( $str, ':', $i );
2811 if ( $colon === false ) {
2812 # Nothing else interesting
2813 wfProfileOut( __METHOD__
);
2816 $lt = strpos( $str, '<', $i );
2817 if ( $stack === 0 ) {
2818 if ( $lt === false ||
$colon < $lt ) {
2820 $before = substr( $str, 0, $colon );
2821 $after = substr( $str, $colon +
1 );
2822 wfProfileOut( __METHOD__
);
2826 if ( $lt === false ) {
2827 # Nothing else interesting to find; abort!
2828 # We're nested, but there's no close tags left. Abort!
2831 # Skip ahead to next tag start
2833 $state = self
::COLON_STATE_TAGSTART
;
2836 case 1: # self::COLON_STATE_TAG:
2841 $state = self
::COLON_STATE_TEXT
;
2844 # Slash may be followed by >?
2845 $state = self
::COLON_STATE_TAGSLASH
;
2851 case 2: # self::COLON_STATE_TAGSTART:
2854 $state = self
::COLON_STATE_CLOSETAG
;
2857 $state = self
::COLON_STATE_COMMENT
;
2860 # Illegal early close? This shouldn't happen D:
2861 $state = self
::COLON_STATE_TEXT
;
2864 $state = self
::COLON_STATE_TAG
;
2867 case 3: # self::COLON_STATE_CLOSETAG:
2872 wfDebug( __METHOD__
. ": Invalid input; too many close tags\n" );
2873 wfProfileOut( __METHOD__
);
2876 $state = self
::COLON_STATE_TEXT
;
2879 case self
::COLON_STATE_TAGSLASH
:
2881 # Yes, a self-closed tag <blah/>
2882 $state = self
::COLON_STATE_TEXT
;
2884 # Probably we're jumping the gun, and this is an attribute
2885 $state = self
::COLON_STATE_TAG
;
2888 case 5: # self::COLON_STATE_COMMENT:
2890 $state = self
::COLON_STATE_COMMENTDASH
;
2893 case self
::COLON_STATE_COMMENTDASH
:
2895 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2897 $state = self
::COLON_STATE_COMMENT
;
2900 case self
::COLON_STATE_COMMENTDASHDASH
:
2902 $state = self
::COLON_STATE_TEXT
;
2904 $state = self
::COLON_STATE_COMMENT
;
2908 wfProfileOut( __METHOD__
);
2909 throw new MWException( "State machine error in " . __METHOD__
);
2913 wfDebug( __METHOD__
. ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2914 wfProfileOut( __METHOD__
);
2917 wfProfileOut( __METHOD__
);
2922 * Return value of a magic variable (like PAGENAME)
2927 * @param bool|PPFrame $frame
2929 * @throws MWException
2932 public function getVariableValue( $index, $frame = false ) {
2933 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2934 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2936 if ( is_null( $this->mTitle
) ) {
2937 // If no title set, bad things are going to happen
2938 // later. Title should always be set since this
2939 // should only be called in the middle of a parse
2940 // operation (but the unit-tests do funky stuff)
2941 throw new MWException( __METHOD__
. ' Should only be '
2942 . ' called while parsing (no title set)' );
2946 * Some of these require message or data lookups and can be
2947 * expensive to check many times.
2949 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2950 if ( isset( $this->mVarCache
[$index] ) ) {
2951 return $this->mVarCache
[$index];
2955 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2956 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2958 $pageLang = $this->getFunctionLang();
2964 case 'currentmonth':
2965 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ) );
2967 case 'currentmonth1':
2968 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2970 case 'currentmonthname':
2971 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2973 case 'currentmonthnamegen':
2974 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2976 case 'currentmonthabbrev':
2977 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2980 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ) );
2983 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ) );
2986 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ) );
2989 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2991 case 'localmonthname':
2992 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2994 case 'localmonthnamegen':
2995 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2997 case 'localmonthabbrev':
2998 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
3001 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ) );
3004 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ) );
3007 $value = wfEscapeWikiText( $this->mTitle
->getText() );
3010 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
3012 case 'fullpagename':
3013 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
3015 case 'fullpagenamee':
3016 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
3019 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
3021 case 'subpagenamee':
3022 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
3024 case 'rootpagename':
3025 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
3027 case 'rootpagenamee':
3028 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
3031 $this->mTitle
->getRootText()
3034 case 'basepagename':
3035 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
3037 case 'basepagenamee':
3038 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
3041 $this->mTitle
->getBaseText()
3044 case 'talkpagename':
3045 if ( $this->mTitle
->canTalk() ) {
3046 $talkPage = $this->mTitle
->getTalkPage();
3047 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
3052 case 'talkpagenamee':
3053 if ( $this->mTitle
->canTalk() ) {
3054 $talkPage = $this->mTitle
->getTalkPage();
3055 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
3060 case 'subjectpagename':
3061 $subjPage = $this->mTitle
->getSubjectPage();
3062 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
3064 case 'subjectpagenamee':
3065 $subjPage = $this->mTitle
->getSubjectPage();
3066 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
3068 case 'pageid': // requested in bug 23427
3069 $pageid = $this->getTitle()->getArticleID();
3070 if ( $pageid == 0 ) {
3071 # 0 means the page doesn't exist in the database,
3072 # which means the user is previewing a new page.
3073 # The vary-revision flag must be set, because the magic word
3074 # will have a different value once the page is saved.
3075 $this->mOutput
->setFlag( 'vary-revision' );
3076 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
3078 $value = $pageid ?
$pageid : null;
3081 # Let the edit saving system know we should parse the page
3082 # *after* a revision ID has been assigned.
3083 $this->mOutput
->setFlag( 'vary-revision' );
3084 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
3085 $value = $this->mRevisionId
;
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__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
3092 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
3094 case 'revisionday2':
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__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
3099 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
3101 case 'revisionmonth':
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__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
3106 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
3108 case 'revisionmonth1':
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__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
3113 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
3115 case 'revisionyear':
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__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
3120 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
3122 case 'revisiontimestamp':
3123 # Let the edit saving system know we should parse the page
3124 # *after* a revision ID has been assigned. This is for null edits.
3125 $this->mOutput
->setFlag( 'vary-revision' );
3126 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
3127 $value = $this->getRevisionTimestamp();
3129 case 'revisionuser':
3130 # Let the edit saving system know we should parse the page
3131 # *after* a revision ID has been assigned. This is for null edits.
3132 $this->mOutput
->setFlag( 'vary-revision' );
3133 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
3134 $value = $this->getRevisionUser();
3136 case 'revisionsize':
3137 # Let the edit saving system know we should parse the page
3138 # *after* a revision ID has been assigned. This is for null edits.
3139 $this->mOutput
->setFlag( 'vary-revision' );
3140 wfDebug( __METHOD__
. ": {{REVISIONSIZE}} used, setting vary-revision...\n" );
3141 $value = $this->getRevisionSize();
3144 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3147 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3149 case 'namespacenumber':
3150 $value = $this->mTitle
->getNamespace();
3153 $value = $this->mTitle
->canTalk()
3154 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
3158 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
3160 case 'subjectspace':
3161 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
3163 case 'subjectspacee':
3164 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
3166 case 'currentdayname':
3167 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
3170 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
3173 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
3176 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
3179 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3180 # int to remove the padding
3181 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
3184 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
3186 case 'localdayname':
3187 $value = $pageLang->getWeekdayName(
3188 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
3192 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
3195 $value = $pageLang->time(
3196 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
3202 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
3205 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3206 # int to remove the padding
3207 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
3210 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
3212 case 'numberofarticles':
3213 $value = $pageLang->formatNum( SiteStats
::articles() );
3215 case 'numberoffiles':
3216 $value = $pageLang->formatNum( SiteStats
::images() );
3218 case 'numberofusers':
3219 $value = $pageLang->formatNum( SiteStats
::users() );
3221 case 'numberofactiveusers':
3222 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
3224 case 'numberofpages':
3225 $value = $pageLang->formatNum( SiteStats
::pages() );
3227 case 'numberofadmins':
3228 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
3230 case 'numberofedits':
3231 $value = $pageLang->formatNum( SiteStats
::edits() );
3233 case 'currenttimestamp':
3234 $value = wfTimestamp( TS_MW
, $ts );
3236 case 'localtimestamp':
3237 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
3239 case 'currentversion':
3240 $value = SpecialVersion
::getVersion();
3243 return $wgArticlePath;
3249 return $wgServerName;
3251 return $wgScriptPath;
3253 return $wgStylePath;
3254 case 'directionmark':
3255 return $pageLang->getDirMark();
3256 case 'contentlanguage':
3257 global $wgLanguageCode;
3258 return $wgLanguageCode;
3259 case 'cascadingsources':
3260 $value = CoreParserFunctions
::cascadingsources( $this );
3265 'ParserGetVariableValueSwitch',
3266 array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame )
3273 $this->mVarCache
[$index] = $value;
3280 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3284 public function initialiseVariables() {
3285 wfProfileIn( __METHOD__
);
3286 $variableIDs = MagicWord
::getVariableIDs();
3287 $substIDs = MagicWord
::getSubstIDs();
3289 $this->mVariables
= new MagicWordArray( $variableIDs );
3290 $this->mSubstWords
= new MagicWordArray( $substIDs );
3291 wfProfileOut( __METHOD__
);
3295 * Preprocess some wikitext and return the document tree.
3296 * This is the ghost of replace_variables().
3298 * @param string $text The text to parse
3299 * @param int $flags Bitwise combination of:
3300 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
3301 * included. Default is to assume a direct page view.
3303 * The generated DOM tree must depend only on the input text and the flags.
3304 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3306 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3307 * change in the DOM tree for a given text, must be passed through the section identifier
3308 * in the section edit link and thus back to extractSections().
3310 * The output of this function is currently only cached in process memory, but a persistent
3311 * cache may be implemented at a later date which takes further advantage of these strict
3312 * dependency requirements.
3316 public function preprocessToDom( $text, $flags = 0 ) {
3317 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3322 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3328 public static function splitWhitespace( $s ) {
3329 $ltrimmed = ltrim( $s );
3330 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3331 $trimmed = rtrim( $ltrimmed );
3332 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3334 $w2 = substr( $ltrimmed, -$diff );
3338 return array( $w1, $trimmed, $w2 );
3342 * Replace magic variables, templates, and template arguments
3343 * with the appropriate text. Templates are substituted recursively,
3344 * taking care to avoid infinite loops.
3346 * Note that the substitution depends on value of $mOutputType:
3347 * self::OT_WIKI: only {{subst:}} templates
3348 * self::OT_PREPROCESS: templates but not extension tags
3349 * self::OT_HTML: all templates and extension tags
3351 * @param string $text The text to transform
3352 * @param bool|PPFrame $frame Object describing the arguments passed to the
3353 * template. Arguments may also be provided as an associative array, as
3354 * was the usual case before MW1.12. Providing arguments this way may be
3355 * useful for extensions wishing to perform variable replacement
3357 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3358 * double-brace expansion.
3361 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3362 # Is there any text? Also, Prevent too big inclusions!
3363 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3366 wfProfileIn( __METHOD__
);
3368 if ( $frame === false ) {
3369 $frame = $this->getPreprocessor()->newFrame();
3370 } elseif ( !( $frame instanceof PPFrame
) ) {
3371 wfDebug( __METHOD__
. " called using plain parameters instead of "
3372 . "a PPFrame instance. Creating custom frame.\n" );
3373 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3376 $dom = $this->preprocessToDom( $text );
3377 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3378 $text = $frame->expand( $dom, $flags );
3380 wfProfileOut( __METHOD__
);
3385 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3387 * @param array $args
3391 public static function createAssocArgs( $args ) {
3392 $assocArgs = array();
3394 foreach ( $args as $arg ) {
3395 $eqpos = strpos( $arg, '=' );
3396 if ( $eqpos === false ) {
3397 $assocArgs[$index++
] = $arg;
3399 $name = trim( substr( $arg, 0, $eqpos ) );
3400 $value = trim( substr( $arg, $eqpos +
1 ) );
3401 if ( $value === false ) {
3404 if ( $name !== false ) {
3405 $assocArgs[$name] = $value;
3414 * Warn the user when a parser limitation is reached
3415 * Will warn at most once the user per limitation type
3417 * @param string $limitationType Should be one of:
3418 * 'expensive-parserfunction' (corresponding messages:
3419 * 'expensive-parserfunction-warning',
3420 * 'expensive-parserfunction-category')
3421 * 'post-expand-template-argument' (corresponding messages:
3422 * 'post-expand-template-argument-warning',
3423 * 'post-expand-template-argument-category')
3424 * 'post-expand-template-inclusion' (corresponding messages:
3425 * 'post-expand-template-inclusion-warning',
3426 * 'post-expand-template-inclusion-category')
3427 * 'node-count-exceeded' (corresponding messages:
3428 * 'node-count-exceeded-warning',
3429 * 'node-count-exceeded-category')
3430 * 'expansion-depth-exceeded' (corresponding messages:
3431 * 'expansion-depth-exceeded-warning',
3432 * 'expansion-depth-exceeded-category')
3433 * @param string|int|null $current Current value
3434 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3435 * exceeded, provide the values (optional)
3437 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3438 # does no harm if $current and $max are present but are unnecessary for the message
3439 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3440 ->inLanguage( $this->mOptions
->getUserLangObj() )->text();
3441 $this->mOutput
->addWarning( $warning );
3442 $this->addTrackingCategory( "$limitationType-category" );
3446 * Return the text of a template, after recursively
3447 * replacing any variables or templates within the template.
3449 * @param array $piece The parts of the template
3450 * $piece['title']: the title, i.e. the part before the |
3451 * $piece['parts']: the parameter array
3452 * $piece['lineStart']: whether the brace was at the start of a line
3453 * @param PPFrame $frame The current frame, contains template arguments
3455 * @return string The text of the template
3457 public function braceSubstitution( $piece, $frame ) {
3458 wfProfileIn( __METHOD__
);
3459 wfProfileIn( __METHOD__
. '-setup' );
3463 // $text has been filled
3465 // wiki markup in $text should be escaped
3467 // $text is HTML, armour it against wikitext transformation
3469 // Force interwiki transclusion to be done in raw mode not rendered
3470 $forceRawInterwiki = false;
3471 // $text is a DOM node needing expansion in a child frame
3472 $isChildObj = false;
3473 // $text is a DOM node needing expansion in the current frame
3474 $isLocalObj = false;
3476 # Title object, where $text came from
3479 # $part1 is the bit before the first |, and must contain only title characters.
3480 # Various prefixes will be stripped from it later.
3481 $titleWithSpaces = $frame->expand( $piece['title'] );
3482 $part1 = trim( $titleWithSpaces );
3485 # Original title text preserved for various purposes
3486 $originalTitle = $part1;
3488 # $args is a list of argument nodes, starting from index 0, not including $part1
3489 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3490 # below won't work b/c this $args isn't an object
3491 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3492 wfProfileOut( __METHOD__
. '-setup' );
3494 $profileSection = null; // profile templates
3497 wfProfileIn( __METHOD__
. '-modifiers' );
3500 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3502 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3503 # Decide whether to expand template or keep wikitext as-is.
3504 if ( $this->ot
['wiki'] ) {
3505 if ( $substMatch === false ) {
3506 $literal = true; # literal when in PST with no prefix
3508 $literal = false; # expand when in PST with subst: or safesubst:
3511 if ( $substMatch == 'subst' ) {
3512 $literal = true; # literal when not in PST with plain subst:
3514 $literal = false; # expand when not in PST with safesubst: or no prefix
3518 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3525 if ( !$found && $args->getLength() == 0 ) {
3526 $id = $this->mVariables
->matchStartToEnd( $part1 );
3527 if ( $id !== false ) {
3528 $text = $this->getVariableValue( $id, $frame );
3529 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3530 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3536 # MSG, MSGNW and RAW
3539 $mwMsgnw = MagicWord
::get( 'msgnw' );
3540 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3543 # Remove obsolete MSG:
3544 $mwMsg = MagicWord
::get( 'msg' );
3545 $mwMsg->matchStartAndRemove( $part1 );
3549 $mwRaw = MagicWord
::get( 'raw' );
3550 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3551 $forceRawInterwiki = true;
3554 wfProfileOut( __METHOD__
. '-modifiers' );
3558 wfProfileIn( __METHOD__
. '-pfunc' );
3560 $colonPos = strpos( $part1, ':' );
3561 if ( $colonPos !== false ) {
3562 $func = substr( $part1, 0, $colonPos );
3563 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3564 for ( $i = 0; $i < $args->getLength(); $i++
) {
3565 $funcArgs[] = $args->item( $i );
3568 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3569 } catch ( Exception
$ex ) {
3570 wfProfileOut( __METHOD__
. '-pfunc' );
3571 wfProfileOut( __METHOD__
);
3575 # The interface for parser functions allows for extracting
3576 # flags into the local scope. Extract any forwarded flags
3580 wfProfileOut( __METHOD__
. '-pfunc' );
3583 # Finish mangling title and then check for loops.
3584 # Set $title to a Title object and $titleText to the PDBK
3587 # Split the title into page and subpage
3589 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3590 if ( $part1 !== $relative ) {
3592 $ns = $this->mTitle
->getNamespace();
3594 $title = Title
::newFromText( $part1, $ns );
3596 $titleText = $title->getPrefixedText();
3597 # Check for language variants if the template is not found
3598 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3599 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3601 # Do recursion depth check
3602 $limit = $this->mOptions
->getMaxTemplateDepth();
3603 if ( $frame->depth
>= $limit ) {
3605 $text = '<span class="error">'
3606 . wfMessage( 'parser-template-recursion-depth-warning' )
3607 ->numParams( $limit )->inContentLanguage()->text()
3613 # Load from database
3614 if ( !$found && $title ) {
3615 $profileSection = $this->mProfiler
->scopedProfileIn( $title->getPrefixedDBkey() );
3616 wfProfileIn( __METHOD__
. '-loadtpl' );
3617 if ( !$title->isExternal() ) {
3618 if ( $title->isSpecialPage()
3619 && $this->mOptions
->getAllowSpecialInclusion()
3620 && $this->ot
['html']
3622 // Pass the template arguments as URL parameters.
3623 // "uselang" will have no effect since the Language object
3624 // is forced to the one defined in ParserOptions.
3625 $pageArgs = array();
3626 $argsLength = $args->getLength();
3627 for ( $i = 0; $i < $argsLength; $i++
) {
3628 $bits = $args->item( $i )->splitArg();
3629 if ( strval( $bits['index'] ) === '' ) {
3630 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3631 $value = trim( $frame->expand( $bits['value'] ) );
3632 $pageArgs[$name] = $value;
3636 // Create a new context to execute the special page
3637 $context = new RequestContext
;
3638 $context->setTitle( $title );
3639 $context->setRequest( new FauxRequest( $pageArgs ) );
3640 $context->setUser( $this->getUser() );
3641 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3642 $ret = SpecialPageFactory
::capturePath( $title, $context );
3644 $text = $context->getOutput()->getHTML();
3645 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3648 $this->disableCache();
3650 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3651 $found = false; # access denied
3652 wfDebug( __METHOD__
. ": template inclusion denied for " .
3653 $title->getPrefixedDBkey() . "\n" );
3655 list( $text, $title ) = $this->getTemplateDom( $title );
3656 if ( $text !== false ) {
3662 # If the title is valid but undisplayable, make a link to it
3663 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3664 $text = "[[:$titleText]]";
3667 } elseif ( $title->isTrans() ) {
3668 # Interwiki transclusion
3669 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3670 $text = $this->interwikiTransclude( $title, 'render' );
3673 $text = $this->interwikiTransclude( $title, 'raw' );
3674 # Preprocess it like a template
3675 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3681 # Do infinite loop check
3682 # This has to be done after redirect resolution to avoid infinite loops via redirects
3683 if ( !$frame->loopCheck( $title ) ) {
3685 $text = '<span class="error">'
3686 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3688 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3690 wfProfileOut( __METHOD__
. '-loadtpl' );
3693 # If we haven't found text to substitute by now, we're done
3694 # Recover the source wikitext and return it
3696 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3697 if ( $profileSection ) {
3698 $this->mProfiler
->scopedProfileOut( $profileSection );
3700 wfProfileOut( __METHOD__
);
3701 return array( 'object' => $text );
3704 # Expand DOM-style return values in a child frame
3705 if ( $isChildObj ) {
3706 # Clean up argument array
3707 $newFrame = $frame->newChild( $args, $title );
3710 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3711 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3712 # Expansion is eligible for the empty-frame cache
3713 $text = $newFrame->cachedExpand( $titleText, $text );
3715 # Uncached expansion
3716 $text = $newFrame->expand( $text );
3719 if ( $isLocalObj && $nowiki ) {
3720 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3721 $isLocalObj = false;
3724 if ( $profileSection ) {
3725 $this->mProfiler
->scopedProfileOut( $profileSection );
3728 # Replace raw HTML by a placeholder
3730 $text = $this->insertStripItem( $text );
3731 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3732 # Escape nowiki-style return values
3733 $text = wfEscapeWikiText( $text );
3734 } elseif ( is_string( $text )
3735 && !$piece['lineStart']
3736 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3738 # Bug 529: if the template begins with a table or block-level
3739 # element, it should be treated as beginning a new line.
3740 # This behavior is somewhat controversial.
3741 $text = "\n" . $text;
3744 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3745 # Error, oversize inclusion
3746 if ( $titleText !== false ) {
3747 # Make a working, properly escaped link if possible (bug 23588)
3748 $text = "[[:$titleText]]";
3750 # This will probably not be a working link, but at least it may
3751 # provide some hint of where the problem is
3752 preg_replace( '/^:/', '', $originalTitle );
3753 $text = "[[:$originalTitle]]";
3755 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3756 . 'post-expand include size too large -->' );
3757 $this->limitationWarn( 'post-expand-template-inclusion' );
3760 if ( $isLocalObj ) {
3761 $ret = array( 'object' => $text );
3763 $ret = array( 'text' => $text );
3766 wfProfileOut( __METHOD__
);
3771 * Call a parser function and return an array with text and flags.
3773 * The returned array will always contain a boolean 'found', indicating
3774 * whether the parser function was found or not. It may also contain the
3776 * text: string|object, resulting wikitext or PP DOM object
3777 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3778 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3779 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3780 * nowiki: bool, wiki markup in $text should be escaped
3783 * @param PPFrame $frame The current frame, contains template arguments
3784 * @param string $function Function name
3785 * @param array $args Arguments to the function
3786 * @throws MWException
3789 public function callParserFunction( $frame, $function, array $args = array() ) {
3792 wfProfileIn( __METHOD__
);
3794 # Case sensitive functions
3795 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3796 $function = $this->mFunctionSynonyms
[1][$function];
3798 # Case insensitive functions
3799 $function = $wgContLang->lc( $function );
3800 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3801 $function = $this->mFunctionSynonyms
[0][$function];
3803 wfProfileOut( __METHOD__
);
3804 return array( 'found' => false );
3808 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3809 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3811 # Workaround for PHP bug 35229 and similar
3812 if ( !is_callable( $callback ) ) {
3813 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3814 wfProfileOut( __METHOD__
);
3815 throw new MWException( "Tag hook for $function is not callable\n" );
3818 $allArgs = array( &$this );
3819 if ( $flags & SFH_OBJECT_ARGS
) {
3820 # Convert arguments to PPNodes and collect for appending to $allArgs
3821 $funcArgs = array();
3822 foreach ( $args as $k => $v ) {
3823 if ( $v instanceof PPNode ||
$k === 0 ) {
3826 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( array( $k => $v ) )->item( 0 );
3830 # Add a frame parameter, and pass the arguments as an array
3831 $allArgs[] = $frame;
3832 $allArgs[] = $funcArgs;
3834 # Convert arguments to plain text and append to $allArgs
3835 foreach ( $args as $k => $v ) {
3836 if ( $v instanceof PPNode
) {
3837 $allArgs[] = trim( $frame->expand( $v ) );
3838 } elseif ( is_int( $k ) && $k >= 0 ) {
3839 $allArgs[] = trim( $v );
3841 $allArgs[] = trim( "$k=$v" );
3846 $result = call_user_func_array( $callback, $allArgs );
3848 # The interface for function hooks allows them to return a wikitext
3849 # string or an array containing the string and any flags. This mungs
3850 # things around to match what this method should return.
3851 if ( !is_array( $result ) ) {
3857 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3858 $result['text'] = $result[0];
3860 unset( $result[0] );
3867 $preprocessFlags = 0;
3868 if ( isset( $result['noparse'] ) ) {
3869 $noparse = $result['noparse'];
3871 if ( isset( $result['preprocessFlags'] ) ) {
3872 $preprocessFlags = $result['preprocessFlags'];
3876 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3877 $result['isChildObj'] = true;
3879 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3880 wfProfileOut( __METHOD__
);
3886 * Get the semi-parsed DOM representation of a template with a given title,
3887 * and its redirect destination title. Cached.
3889 * @param Title $title
3893 public function getTemplateDom( $title ) {
3894 $cacheTitle = $title;
3895 $titleText = $title->getPrefixedDBkey();
3897 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3898 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3899 $title = Title
::makeTitle( $ns, $dbk );
3900 $titleText = $title->getPrefixedDBkey();
3902 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3903 return array( $this->mTplDomCache
[$titleText], $title );
3906 # Cache miss, go to the database
3907 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3909 if ( $text === false ) {
3910 $this->mTplDomCache
[$titleText] = false;
3911 return array( false, $title );
3914 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3915 $this->mTplDomCache
[$titleText] = $dom;
3917 if ( !$title->equals( $cacheTitle ) ) {
3918 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3919 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3922 return array( $dom, $title );
3926 * Fetch the current revision of a given title. Note that the revision
3927 * (and even the title) may not exist in the database, so everything
3928 * contributing to the output of the parser should use this method
3929 * where possible, rather than getting the revisions themselves. This
3930 * method also caches its results, so using it benefits performance.
3933 * @param Title $title
3936 public function fetchCurrentRevisionOfTitle( $title ) {
3937 $cacheKey = $title->getPrefixedDBkey();
3938 if ( !$this->currentRevisionCache
) {
3939 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3941 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3942 $this->currentRevisionCache
->set( $cacheKey,
3943 // Defaults to Parser::statelessFetchRevision()
3944 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3947 return $this->currentRevisionCache
->get( $cacheKey );
3951 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3952 * without passing them on to it.
3955 * @param Title $title
3956 * @param Parser|bool $parser
3959 public static function statelessFetchRevision( $title, $parser = false ) {
3960 return Revision
::newFromTitle( $title );
3964 * Fetch the unparsed text of a template and register a reference to it.
3965 * @param Title $title
3966 * @return array ( string or false, Title )
3968 public function fetchTemplateAndTitle( $title ) {
3969 // Defaults to Parser::statelessFetchTemplate()
3970 $templateCb = $this->mOptions
->getTemplateCallback();
3971 $stuff = call_user_func( $templateCb, $title, $this );
3972 $text = $stuff['text'];
3973 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3974 if ( isset( $stuff['deps'] ) ) {
3975 foreach ( $stuff['deps'] as $dep ) {
3976 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3977 if ( $dep['title']->equals( $this->getTitle() ) ) {
3978 // If we transclude ourselves, the final result
3979 // will change based on the new version of the page
3980 $this->mOutput
->setFlag( 'vary-revision' );
3984 return array( $text, $finalTitle );
3988 * Fetch the unparsed text of a template and register a reference to it.
3989 * @param Title $title
3990 * @return string|bool
3992 public function fetchTemplate( $title ) {
3993 $rv = $this->fetchTemplateAndTitle( $title );
3998 * Static function to get a template
3999 * Can be overridden via ParserOptions::setTemplateCallback().
4001 * @param Title $title
4002 * @param bool|Parser $parser
4006 public static function statelessFetchTemplate( $title, $parser = false ) {
4007 $text = $skip = false;
4008 $finalTitle = $title;
4011 # Loop to fetch the article, with up to 1 redirect
4012 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
4013 # Give extensions a chance to select the revision instead
4014 $id = false; # Assume current
4015 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
4016 array( $parser, $title, &$skip, &$id ) );
4022 'page_id' => $title->getArticleID(),
4029 $rev = Revision
::newFromId( $id );
4030 } elseif ( $parser ) {
4031 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
4033 $rev = Revision
::newFromTitle( $title );
4035 $rev_id = $rev ?
$rev->getId() : 0;
4036 # If there is no current revision, there is no page
4037 if ( $id === false && !$rev ) {
4038 $linkCache = LinkCache
::singleton();
4039 $linkCache->addBadLinkObj( $title );
4044 'page_id' => $title->getArticleID(),
4045 'rev_id' => $rev_id );
4046 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
4047 # We fetched a rev from a different title; register it too...
4049 'title' => $rev->getTitle(),
4050 'page_id' => $rev->getPage(),
4051 'rev_id' => $rev_id );
4055 $content = $rev->getContent();
4056 $text = $content ?
$content->getWikitextForTransclusion() : null;
4058 if ( $text === false ||
$text === null ) {
4062 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
4064 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
4065 if ( !$message->exists() ) {
4069 $content = $message->content();
4070 $text = $message->plain();
4078 $finalTitle = $title;
4079 $title = $content->getRedirectTarget();
4083 'finalTitle' => $finalTitle,
4088 * Fetch a file and its title and register a reference to it.
4089 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4090 * @param Title $title
4091 * @param array $options Array of options to RepoGroup::findFile
4094 public function fetchFile( $title, $options = array() ) {
4095 $res = $this->fetchFileAndTitle( $title, $options );
4100 * Fetch a file and its title and register a reference to it.
4101 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4102 * @param Title $title
4103 * @param array $options Array of options to RepoGroup::findFile
4104 * @return array ( File or false, Title of file )
4106 public function fetchFileAndTitle( $title, $options = array() ) {
4107 $file = $this->fetchFileNoRegister( $title, $options );
4109 $time = $file ?
$file->getTimestamp() : false;
4110 $sha1 = $file ?
$file->getSha1() : false;
4111 # Register the file as a dependency...
4112 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4113 if ( $file && !$title->equals( $file->getTitle() ) ) {
4114 # Update fetched file title
4115 $title = $file->getTitle();
4116 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4118 return array( $file, $title );
4122 * Helper function for fetchFileAndTitle.
4124 * Also useful if you need to fetch a file but not use it yet,
4125 * for example to get the file's handler.
4127 * @param Title $title
4128 * @param array $options Array of options to RepoGroup::findFile
4131 protected function fetchFileNoRegister( $title, $options = array() ) {
4132 if ( isset( $options['broken'] ) ) {
4133 $file = false; // broken thumbnail forced by hook
4134 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
4135 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
4136 } else { // get by (name,timestamp)
4137 $file = wfFindFile( $title, $options );
4143 * Transclude an interwiki link.
4145 * @param Title $title
4146 * @param string $action
4150 public function interwikiTransclude( $title, $action ) {
4151 global $wgEnableScaryTranscluding;
4153 if ( !$wgEnableScaryTranscluding ) {
4154 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
4157 $url = $title->getFullURL( array( 'action' => $action ) );
4159 if ( strlen( $url ) > 255 ) {
4160 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
4162 return $this->fetchScaryTemplateMaybeFromCache( $url );
4166 * @param string $url
4167 * @return mixed|string
4169 public function fetchScaryTemplateMaybeFromCache( $url ) {
4170 global $wgTranscludeCacheExpiry;
4171 $dbr = wfGetDB( DB_SLAVE
);
4172 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
4173 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
4174 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
4176 return $obj->tc_contents
;
4179 $req = MWHttpRequest
::factory( $url );
4180 $status = $req->execute(); // Status object
4181 if ( $status->isOK() ) {
4182 $text = $req->getContent();
4183 } elseif ( $req->getStatus() != 200 ) {
4184 // Though we failed to fetch the content, this status is useless.
4185 return wfMessage( 'scarytranscludefailed-httpstatus' )
4186 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
4188 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
4191 $dbw = wfGetDB( DB_MASTER
);
4192 $dbw->replace( 'transcache', array( 'tc_url' ), array(
4194 'tc_time' => $dbw->timestamp( time() ),
4195 'tc_contents' => $text
4201 * Triple brace replacement -- used for template arguments
4204 * @param array $piece
4205 * @param PPFrame $frame
4209 public function argSubstitution( $piece, $frame ) {
4210 wfProfileIn( __METHOD__
);
4213 $parts = $piece['parts'];
4214 $nameWithSpaces = $frame->expand( $piece['title'] );
4215 $argName = trim( $nameWithSpaces );
4217 $text = $frame->getArgument( $argName );
4218 if ( $text === false && $parts->getLength() > 0
4219 && ( $this->ot
['html']
4221 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
4224 # No match in frame, use the supplied default
4225 $object = $parts->item( 0 )->getChildren();
4227 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
4228 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
4229 $this->limitationWarn( 'post-expand-template-argument' );
4232 if ( $text === false && $object === false ) {
4234 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
4236 if ( $error !== false ) {
4239 if ( $object !== false ) {
4240 $ret = array( 'object' => $object );
4242 $ret = array( 'text' => $text );
4245 wfProfileOut( __METHOD__
);
4250 * Return the text to be used for a given extension tag.
4251 * This is the ghost of strip().
4253 * @param array $params Associative array of parameters:
4254 * name PPNode for the tag name
4255 * attr PPNode for unparsed text where tag attributes are thought to be
4256 * attributes Optional associative array of parsed attributes
4257 * inner Contents of extension element
4258 * noClose Original text did not have a close tag
4259 * @param PPFrame $frame
4261 * @throws MWException
4264 public function extensionSubstitution( $params, $frame ) {
4265 $name = $frame->expand( $params['name'] );
4266 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
4267 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
4268 $marker = "{$this->mUniqPrefix}-$name-"
4269 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
4271 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
4272 ( $this->ot
['html'] ||
$this->ot
['pre'] );
4273 if ( $isFunctionTag ) {
4274 $markerType = 'none';
4276 $markerType = 'general';
4278 if ( $this->ot
['html'] ||
$isFunctionTag ) {
4279 $name = strtolower( $name );
4280 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
4281 if ( isset( $params['attributes'] ) ) {
4282 $attributes = $attributes +
$params['attributes'];
4285 if ( isset( $this->mTagHooks
[$name] ) ) {
4286 # Workaround for PHP bug 35229 and similar
4287 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
4288 throw new MWException( "Tag hook for $name is not callable\n" );
4290 $output = call_user_func_array( $this->mTagHooks
[$name],
4291 array( $content, $attributes, $this, $frame ) );
4292 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
4293 list( $callback, ) = $this->mFunctionTagHooks
[$name];
4294 if ( !is_callable( $callback ) ) {
4295 throw new MWException( "Tag hook for $name is not callable\n" );
4298 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
4300 $output = '<span class="error">Invalid tag extension name: ' .
4301 htmlspecialchars( $name ) . '</span>';
4304 if ( is_array( $output ) ) {
4305 # Extract flags to local scope (to override $markerType)
4307 $output = $flags[0];
4312 if ( is_null( $attrText ) ) {
4315 if ( isset( $params['attributes'] ) ) {
4316 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4317 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4318 htmlspecialchars( $attrValue ) . '"';
4321 if ( $content === null ) {
4322 $output = "<$name$attrText/>";
4324 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4325 $output = "<$name$attrText>$content$close";
4329 if ( $markerType === 'none' ) {
4331 } elseif ( $markerType === 'nowiki' ) {
4332 $this->mStripState
->addNoWiki( $marker, $output );
4333 } elseif ( $markerType === 'general' ) {
4334 $this->mStripState
->addGeneral( $marker, $output );
4336 throw new MWException( __METHOD__
. ': invalid marker type' );
4342 * Increment an include size counter
4344 * @param string $type The type of expansion
4345 * @param int $size The size of the text
4346 * @return bool False if this inclusion would take it over the maximum, true otherwise
4348 public function incrementIncludeSize( $type, $size ) {
4349 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4352 $this->mIncludeSizes
[$type] +
= $size;
4358 * Increment the expensive function count
4360 * @return bool False if the limit has been exceeded
4362 public function incrementExpensiveFunctionCount() {
4363 $this->mExpensiveFunctionCount++
;
4364 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4368 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4369 * Fills $this->mDoubleUnderscores, returns the modified text
4371 * @param string $text
4375 public function doDoubleUnderscore( $text ) {
4376 wfProfileIn( __METHOD__
);
4378 # The position of __TOC__ needs to be recorded
4379 $mw = MagicWord
::get( 'toc' );
4380 if ( $mw->match( $text ) ) {
4381 $this->mShowToc
= true;
4382 $this->mForceTocPosition
= true;
4384 # Set a placeholder. At the end we'll fill it in with the TOC.
4385 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4387 # Only keep the first one.
4388 $text = $mw->replace( '', $text );
4391 # Now match and remove the rest of them
4392 $mwa = MagicWord
::getDoubleUnderscoreArray();
4393 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4395 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4396 $this->mOutput
->mNoGallery
= true;
4398 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4399 $this->mShowToc
= false;
4401 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4402 && $this->mTitle
->getNamespace() == NS_CATEGORY
4404 $this->addTrackingCategory( 'hidden-category-category' );
4406 # (bug 8068) Allow control over whether robots index a page.
4408 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4409 # is not desirable, the last one on the page should win.
4410 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4411 $this->mOutput
->setIndexPolicy( 'noindex' );
4412 $this->addTrackingCategory( 'noindex-category' );
4414 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4415 $this->mOutput
->setIndexPolicy( 'index' );
4416 $this->addTrackingCategory( 'index-category' );
4419 # Cache all double underscores in the database
4420 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4421 $this->mOutput
->setProperty( $key, '' );
4424 wfProfileOut( __METHOD__
);
4429 * @see ParserOutput::addTrackingCategory()
4430 * @param string $msg Message key
4431 * @return bool Whether the addition was successful
4433 public function addTrackingCategory( $msg ) {
4434 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4438 * This function accomplishes several tasks:
4439 * 1) Auto-number headings if that option is enabled
4440 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4441 * 3) Add a Table of contents on the top for users who have enabled the option
4442 * 4) Auto-anchor headings
4444 * It loops through all headlines, collects the necessary data, then splits up the
4445 * string and re-inserts the newly formatted headlines.
4447 * @param string $text
4448 * @param string $origText Original, untouched wikitext
4449 * @param bool $isMain
4450 * @return mixed|string
4453 public function formatHeadings( $text, $origText, $isMain = true ) {
4454 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4456 # Inhibit editsection links if requested in the page
4457 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4458 $maybeShowEditLink = $showEditLink = false;
4460 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4461 $showEditLink = $this->mOptions
->getEditSection();
4463 if ( $showEditLink ) {
4464 $this->mOutput
->setEditSectionTokens( true );
4467 # Get all headlines for numbering them and adding funky stuff like [edit]
4468 # links - this is for later, but we need the number of headlines right now
4470 $numMatches = preg_match_all(
4471 '/<H(?P<level>[1-6])(?P<attrib>.*?' . '>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i',
4476 # if there are fewer than 4 headlines in the article, do not show TOC
4477 # unless it's been explicitly enabled.
4478 $enoughToc = $this->mShowToc
&&
4479 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4481 # Allow user to stipulate that a page should have a "new section"
4482 # link added via __NEWSECTIONLINK__
4483 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4484 $this->mOutput
->setNewSection( true );
4487 # Allow user to remove the "new section"
4488 # link via __NONEWSECTIONLINK__
4489 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4490 $this->mOutput
->hideNewSection( true );
4493 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4494 # override above conditions and always show TOC above first header
4495 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4496 $this->mShowToc
= true;
4504 # Ugh .. the TOC should have neat indentation levels which can be
4505 # passed to the skin functions. These are determined here
4509 $sublevelCount = array();
4510 $levelCount = array();
4515 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4516 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4517 $oldType = $this->mOutputType
;
4518 $this->setOutputType( self
::OT_WIKI
);
4519 $frame = $this->getPreprocessor()->newFrame();
4520 $root = $this->preprocessToDom( $origText );
4521 $node = $root->getFirstChild();
4526 foreach ( $matches[3] as $headline ) {
4527 $isTemplate = false;
4529 $sectionIndex = false;
4531 $markerMatches = array();
4532 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4533 $serial = $markerMatches[1];
4534 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4535 $isTemplate = ( $titleText != $baseTitleText );
4536 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4540 $prevlevel = $level;
4542 $level = $matches[1][$headlineCount];
4544 if ( $level > $prevlevel ) {
4545 # Increase TOC level
4547 $sublevelCount[$toclevel] = 0;
4548 if ( $toclevel < $wgMaxTocLevel ) {
4549 $prevtoclevel = $toclevel;
4550 $toc .= Linker
::tocIndent();
4553 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4554 # Decrease TOC level, find level to jump to
4556 for ( $i = $toclevel; $i > 0; $i-- ) {
4557 if ( $levelCount[$i] == $level ) {
4558 # Found last matching level
4561 } elseif ( $levelCount[$i] < $level ) {
4562 # Found first matching level below current level
4570 if ( $toclevel < $wgMaxTocLevel ) {
4571 if ( $prevtoclevel < $wgMaxTocLevel ) {
4572 # Unindent only if the previous toc level was shown :p
4573 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4574 $prevtoclevel = $toclevel;
4576 $toc .= Linker
::tocLineEnd();
4580 # No change in level, end TOC line
4581 if ( $toclevel < $wgMaxTocLevel ) {
4582 $toc .= Linker
::tocLineEnd();
4586 $levelCount[$toclevel] = $level;
4588 # count number of headlines for each level
4589 $sublevelCount[$toclevel]++
;
4591 for ( $i = 1; $i <= $toclevel; $i++
) {
4592 if ( !empty( $sublevelCount[$i] ) ) {
4596 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4601 # The safe header is a version of the header text safe to use for links
4603 # Remove link placeholders by the link text.
4604 # <!--LINK number-->
4606 # link text with suffix
4607 # Do this before unstrip since link text can contain strip markers
4608 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4610 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4611 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4613 # Strip out HTML (first regex removes any tag not allowed)
4615 # * <sup> and <sub> (bug 8393)
4618 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4620 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4621 # to allow setting directionality in toc items.
4622 $tocline = preg_replace(
4624 '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?' . '>#',
4625 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?' . '>#'
4627 array( '', '<$1>' ),
4630 $tocline = trim( $tocline );
4632 # For the anchor, strip out HTML-y stuff period
4633 $safeHeadline = preg_replace( '/<.*?' . '>/', '', $safeHeadline );
4634 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4636 # Save headline for section edit hint before it's escaped
4637 $headlineHint = $safeHeadline;
4639 if ( $wgExperimentalHtmlIds ) {
4640 # For reverse compatibility, provide an id that's
4641 # HTML4-compatible, like we used to.
4643 # It may be worth noting, academically, that it's possible for
4644 # the legacy anchor to conflict with a non-legacy headline
4645 # anchor on the page. In this case likely the "correct" thing
4646 # would be to either drop the legacy anchors or make sure
4647 # they're numbered first. However, this would require people
4648 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4649 # manually, so let's not bother worrying about it.
4650 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4651 array( 'noninitial', 'legacy' ) );
4652 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4654 if ( $legacyHeadline == $safeHeadline ) {
4655 # No reason to have both (in fact, we can't)
4656 $legacyHeadline = false;
4659 $legacyHeadline = false;
4660 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4664 # HTML names must be case-insensitively unique (bug 10721).
4665 # This does not apply to Unicode characters per
4666 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4667 # @todo FIXME: We may be changing them depending on the current locale.
4668 $arrayKey = strtolower( $safeHeadline );
4669 if ( $legacyHeadline === false ) {
4670 $legacyArrayKey = false;
4672 $legacyArrayKey = strtolower( $legacyHeadline );
4675 # count how many in assoc. array so we can track dupes in anchors
4676 if ( isset( $refers[$arrayKey] ) ) {
4677 $refers[$arrayKey]++
;
4679 $refers[$arrayKey] = 1;
4681 if ( isset( $refers[$legacyArrayKey] ) ) {
4682 $refers[$legacyArrayKey]++
;
4684 $refers[$legacyArrayKey] = 1;
4687 # Don't number the heading if it is the only one (looks silly)
4688 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4689 # the two are different if the line contains a link
4690 $headline = Html
::element(
4692 array( 'class' => 'mw-headline-number' ),
4694 ) . ' ' . $headline;
4697 # Create the anchor for linking from the TOC to the section
4698 $anchor = $safeHeadline;
4699 $legacyAnchor = $legacyHeadline;
4700 if ( $refers[$arrayKey] > 1 ) {
4701 $anchor .= '_' . $refers[$arrayKey];
4703 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4704 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4706 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4707 $toc .= Linker
::tocLine( $anchor, $tocline,
4708 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4711 # Add the section to the section tree
4712 # Find the DOM node for this header
4713 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4714 while ( $node && !$noOffset ) {
4715 if ( $node->getName() === 'h' ) {
4716 $bits = $node->splitHeading();
4717 if ( $bits['i'] == $sectionIndex ) {
4721 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4722 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4723 $node = $node->getNextSibling();
4726 'toclevel' => $toclevel,
4729 'number' => $numbering,
4730 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4731 'fromtitle' => $titleText,
4732 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4733 'anchor' => $anchor,
4736 # give headline the correct <h#> tag
4737 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4738 // Output edit section links as markers with styles that can be customized by skins
4739 if ( $isTemplate ) {
4740 # Put a T flag in the section identifier, to indicate to extractSections()
4741 # that sections inside <includeonly> should be counted.
4742 $editsectionPage = $titleText;
4743 $editsectionSection = "T-$sectionIndex";
4744 $editsectionContent = null;
4746 $editsectionPage = $this->mTitle
->getPrefixedText();
4747 $editsectionSection = $sectionIndex;
4748 $editsectionContent = $headlineHint;
4750 // We use a bit of pesudo-xml for editsection markers. The
4751 // language converter is run later on. Using a UNIQ style marker
4752 // leads to the converter screwing up the tokens when it
4753 // converts stuff. And trying to insert strip tags fails too. At
4754 // this point all real inputted tags have already been escaped,
4755 // so we don't have to worry about a user trying to input one of
4756 // these markers directly. We use a page and section attribute
4757 // to stop the language converter from converting these
4758 // important bits of data, but put the headline hint inside a
4759 // content block because the language converter is supposed to
4760 // be able to convert that piece of data.
4761 // Gets replaced with html in ParserOutput::getText
4762 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4763 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4764 if ( $editsectionContent !== null ) {
4765 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4772 $head[$headlineCount] = Linker
::makeHeadline( $level,
4773 $matches['attrib'][$headlineCount], $anchor, $headline,
4774 $editlink, $legacyAnchor );
4779 $this->setOutputType( $oldType );
4781 # Never ever show TOC if no headers
4782 if ( $numVisible < 1 ) {
4787 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4788 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4790 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4791 $this->mOutput
->setTOCHTML( $toc );
4792 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4793 $this->mOutput
->addModules( 'mediawiki.toc' );
4797 $this->mOutput
->setSections( $tocraw );
4800 # split up and insert constructed headlines
4801 $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text );
4804 // build an array of document sections
4805 $sections = array();
4806 foreach ( $blocks as $block ) {
4807 // $head is zero-based, sections aren't.
4808 if ( empty( $head[$i - 1] ) ) {
4809 $sections[$i] = $block;
4811 $sections[$i] = $head[$i - 1] . $block;
4815 * Send a hook, one per section.
4816 * The idea here is to be able to make section-level DIVs, but to do so in a
4817 * lower-impact, more correct way than r50769
4820 * $section : the section number
4821 * &$sectionContent : ref to the content of the section
4822 * $showEditLinks : boolean describing whether this section has an edit link
4824 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4829 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4830 // append the TOC at the beginning
4831 // Top anchor now in skin
4832 $sections[0] = $sections[0] . $toc . "\n";
4835 $full .= join( '', $sections );
4837 if ( $this->mForceTocPosition
) {
4838 return str_replace( '<!--MWTOC-->', $toc, $full );
4845 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4846 * conversion, substituting signatures, {{subst:}} templates, etc.
4848 * @param string $text The text to transform
4849 * @param Title $title The Title object for the current article
4850 * @param User $user The User object describing the current user
4851 * @param ParserOptions $options Parsing options
4852 * @param bool $clearState Whether to clear the parser state first
4853 * @return string The altered wiki markup
4855 public function preSaveTransform( $text, Title
$title, User
$user,
4856 ParserOptions
$options, $clearState = true
4858 if ( $clearState ) {
4859 $magicScopeVariable = $this->lock();
4861 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4862 $this->setUser( $user );
4867 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4868 if ( $options->getPreSaveTransform() ) {
4869 $text = $this->pstPass2( $text, $user );
4871 $text = $this->mStripState
->unstripBoth( $text );
4873 $this->setUser( null ); #Reset
4879 * Pre-save transform helper function
4881 * @param string $text
4886 private function pstPass2( $text, $user ) {
4889 # Note: This is the timestamp saved as hardcoded wikitext to
4890 # the database, we use $wgContLang here in order to give
4891 # everyone the same signature and use the default one rather
4892 # than the one selected in each user's preferences.
4893 # (see also bug 12815)
4894 $ts = $this->mOptions
->getTimestamp();
4895 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4896 $ts = $timestamp->format( 'YmdHis' );
4897 $tzMsg = $timestamp->format( 'T' ); # might vary on DST changeover!
4899 # Allow translation of timezones through wiki. format() can return
4900 # whatever crap the system uses, localised or not, so we cannot
4901 # ship premade translations.
4902 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4903 $msg = wfMessage( $key )->inContentLanguage();
4904 if ( $msg->exists() ) {
4905 $tzMsg = $msg->text();
4908 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4910 # Variable replacement
4911 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4912 $text = $this->replaceVariables( $text );
4914 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4915 # which may corrupt this parser instance via its wfMessage()->text() call-
4918 $sigText = $this->getUserSig( $user );
4919 $text = strtr( $text, array(
4921 '~~~~' => "$sigText $d",
4925 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4926 $tc = '[' . Title
::legalChars() . ']';
4927 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4929 // [[ns:page (context)|]]
4930 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4931 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4932 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4933 // [[ns:page (context), context|]] (using either single or double-width comma)
4934 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4935 // [[|page]] (reverse pipe trick: add context from page title)
4936 $p2 = "/\[\[\\|($tc+)]]/";
4938 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4939 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4940 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4941 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4943 $t = $this->mTitle
->getText();
4945 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4946 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4947 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4948 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4950 # if there's no context, don't bother duplicating the title
4951 $text = preg_replace( $p2, '[[\\1]]', $text );
4954 # Trim trailing whitespace
4955 $text = rtrim( $text );
4961 * Fetch the user's signature text, if any, and normalize to
4962 * validated, ready-to-insert wikitext.
4963 * If you have pre-fetched the nickname or the fancySig option, you can
4964 * specify them here to save a database query.
4965 * Do not reuse this parser instance after calling getUserSig(),
4966 * as it may have changed if it's the $wgParser.
4969 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4970 * @param bool|null $fancySig whether the nicknname is the complete signature
4971 * or null to use default value
4974 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4975 global $wgMaxSigChars;
4977 $username = $user->getName();
4979 # If not given, retrieve from the user object.
4980 if ( $nickname === false ) {
4981 $nickname = $user->getOption( 'nickname' );
4984 if ( is_null( $fancySig ) ) {
4985 $fancySig = $user->getBoolOption( 'fancysig' );
4988 $nickname = $nickname == null ?
$username : $nickname;
4990 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4991 $nickname = $username;
4992 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4993 } elseif ( $fancySig !== false ) {
4994 # Sig. might contain markup; validate this
4995 if ( $this->validateSig( $nickname ) !== false ) {
4996 # Validated; clean up (if needed) and return it
4997 return $this->cleanSig( $nickname, true );
4999 # Failed to validate; fall back to the default
5000 $nickname = $username;
5001 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
5005 # Make sure nickname doesnt get a sig in a sig
5006 $nickname = self
::cleanSigInSig( $nickname );
5008 # If we're still here, make it a link to the user page
5009 $userText = wfEscapeWikiText( $username );
5010 $nickText = wfEscapeWikiText( $nickname );
5011 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
5013 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
5014 ->title( $this->getTitle() )->text();
5018 * Check that the user's signature contains no bad XML
5020 * @param string $text
5021 * @return string|bool An expanded string, or false if invalid.
5023 public function validateSig( $text ) {
5024 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
5028 * Clean up signature text
5030 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
5031 * 2) Substitute all transclusions
5033 * @param string $text
5034 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
5035 * @return string Signature text
5037 public function cleanSig( $text, $parsing = false ) {
5040 $magicScopeVariable = $this->lock();
5041 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
5044 # Option to disable this feature
5045 if ( !$this->mOptions
->getCleanSignatures() ) {
5049 # @todo FIXME: Regex doesn't respect extension tags or nowiki
5050 # => Move this logic to braceSubstitution()
5051 $substWord = MagicWord
::get( 'subst' );
5052 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
5053 $substText = '{{' . $substWord->getSynonym( 0 );
5055 $text = preg_replace( $substRegex, $substText, $text );
5056 $text = self
::cleanSigInSig( $text );
5057 $dom = $this->preprocessToDom( $text );
5058 $frame = $this->getPreprocessor()->newFrame();
5059 $text = $frame->expand( $dom );
5062 $text = $this->mStripState
->unstripBoth( $text );
5069 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
5071 * @param string $text
5072 * @return string Signature text with /~{3,5}/ removed
5074 public static function cleanSigInSig( $text ) {
5075 $text = preg_replace( '/~{3,5}/', '', $text );
5080 * Set up some variables which are usually set up in parse()
5081 * so that an external function can call some class members with confidence
5083 * @param Title|null $title
5084 * @param ParserOptions $options
5085 * @param int $outputType
5086 * @param bool $clearState
5088 public function startExternalParse( Title
$title = null, ParserOptions
$options,
5089 $outputType, $clearState = true
5091 $this->startParse( $title, $options, $outputType, $clearState );
5095 * @param Title|null $title
5096 * @param ParserOptions $options
5097 * @param int $outputType
5098 * @param bool $clearState
5100 private function startParse( Title
$title = null, ParserOptions
$options,
5101 $outputType, $clearState = true
5103 $this->setTitle( $title );
5104 $this->mOptions
= $options;
5105 $this->setOutputType( $outputType );
5106 if ( $clearState ) {
5107 $this->clearState();
5112 * Wrapper for preprocess()
5114 * @param string $text The text to preprocess
5115 * @param ParserOptions $options Options
5116 * @param Title|null $title Title object or null to use $wgTitle
5119 public function transformMsg( $text, $options, $title = null ) {
5120 static $executing = false;
5122 # Guard against infinite recursion
5128 wfProfileIn( __METHOD__
);
5134 $text = $this->preprocess( $text, $title, $options );
5137 wfProfileOut( __METHOD__
);
5142 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
5143 * The callback should have the following form:
5144 * function myParserHook( $text, $params, $parser, $frame ) { ... }
5146 * Transform and return $text. Use $parser for any required context, e.g. use
5147 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
5149 * Hooks may return extended information by returning an array, of which the
5150 * first numbered element (index 0) must be the return string, and all other
5151 * entries are extracted into local variables within an internal function
5152 * in the Parser class.
5154 * This interface (introduced r61913) appears to be undocumented, but
5155 * 'markerName' is used by some core tag hooks to override which strip
5156 * array their results are placed in. **Use great caution if attempting
5157 * this interface, as it is not documented and injudicious use could smash
5158 * private variables.**
5160 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5161 * @param callable $callback The callback function (and object) to use for the tag
5162 * @throws MWException
5163 * @return callable|null The old value of the mTagHooks array associated with the hook
5165 public function setHook( $tag, $callback ) {
5166 $tag = strtolower( $tag );
5167 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5168 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
5170 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
5171 $this->mTagHooks
[$tag] = $callback;
5172 if ( !in_array( $tag, $this->mStripList
) ) {
5173 $this->mStripList
[] = $tag;
5180 * As setHook(), but letting the contents be parsed.
5182 * Transparent tag hooks are like regular XML-style tag hooks, except they
5183 * operate late in the transformation sequence, on HTML instead of wikitext.
5185 * This is probably obsoleted by things dealing with parser frames?
5186 * The only extension currently using it is geoserver.
5189 * @todo better document or deprecate this
5191 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5192 * @param callable $callback The callback function (and object) to use for the tag
5193 * @throws MWException
5194 * @return callable|null The old value of the mTagHooks array associated with the hook
5196 public function setTransparentTagHook( $tag, $callback ) {
5197 $tag = strtolower( $tag );
5198 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5199 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
5201 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
5202 $this->mTransparentTagHooks
[$tag] = $callback;
5208 * Remove all tag hooks
5210 public function clearTagHooks() {
5211 $this->mTagHooks
= array();
5212 $this->mFunctionTagHooks
= array();
5213 $this->mStripList
= $this->mDefaultStripList
;
5217 * Create a function, e.g. {{sum:1|2|3}}
5218 * The callback function should have the form:
5219 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
5221 * Or with SFH_OBJECT_ARGS:
5222 * function myParserFunction( $parser, $frame, $args ) { ... }
5224 * The callback may either return the text result of the function, or an array with the text
5225 * in element 0, and a number of flags in the other elements. The names of the flags are
5226 * specified in the keys. Valid flags are:
5227 * found The text returned is valid, stop processing the template. This
5229 * nowiki Wiki markup in the return value should be escaped
5230 * isHTML The returned text is HTML, armour it against wikitext transformation
5232 * @param string $id The magic word ID
5233 * @param callable $callback The callback function (and object) to use
5234 * @param int $flags A combination of the following flags:
5235 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
5237 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
5238 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
5239 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
5240 * the arguments, and to control the way they are expanded.
5242 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
5243 * arguments, for instance:
5244 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
5246 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
5247 * future versions. Please call $frame->expand() on it anyway so that your code keeps
5248 * working if/when this is changed.
5250 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
5253 * Please read the documentation in includes/parser/Preprocessor.php for more information
5254 * about the methods available in PPFrame and PPNode.
5256 * @throws MWException
5257 * @return string|callable The old callback function for this name, if any
5259 public function setFunctionHook( $id, $callback, $flags = 0 ) {
5262 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
5263 $this->mFunctionHooks
[$id] = array( $callback, $flags );
5265 # Add to function cache
5266 $mw = MagicWord
::get( $id );
5268 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
5271 $synonyms = $mw->getSynonyms();
5272 $sensitive = intval( $mw->isCaseSensitive() );
5274 foreach ( $synonyms as $syn ) {
5276 if ( !$sensitive ) {
5277 $syn = $wgContLang->lc( $syn );
5280 if ( !( $flags & SFH_NO_HASH
) ) {
5283 # Remove trailing colon
5284 if ( substr( $syn, -1, 1 ) === ':' ) {
5285 $syn = substr( $syn, 0, -1 );
5287 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
5293 * Get all registered function hook identifiers
5297 public function getFunctionHooks() {
5298 return array_keys( $this->mFunctionHooks
);
5302 * Create a tag function, e.g. "<test>some stuff</test>".
5303 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5304 * Unlike parser functions, their content is not preprocessed.
5305 * @param string $tag
5306 * @param callable $callback
5308 * @throws MWException
5311 public function setFunctionTagHook( $tag, $callback, $flags ) {
5312 $tag = strtolower( $tag );
5313 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5314 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5316 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
5317 $this->mFunctionTagHooks
[$tag] : null;
5318 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
5320 if ( !in_array( $tag, $this->mStripList
) ) {
5321 $this->mStripList
[] = $tag;
5328 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
5329 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5330 * Placeholders created in Skin::makeLinkObj()
5332 * @param string $text
5333 * @param int $options
5335 public function replaceLinkHolders( &$text, $options = 0 ) {
5336 $this->mLinkHolders
->replace( $text );
5340 * Replace "<!--LINK-->" link placeholders with plain text of links
5341 * (not HTML-formatted).
5343 * @param string $text
5346 public function replaceLinkHoldersText( $text ) {
5347 return $this->mLinkHolders
->replaceText( $text );
5351 * Renders an image gallery from a text with one line per image.
5352 * text labels may be given by using |-style alternative text. E.g.
5353 * Image:one.jpg|The number "1"
5354 * Image:tree.jpg|A tree
5355 * given as text will return the HTML of a gallery with two images,
5356 * labeled 'The number "1"' and
5359 * @param string $text
5360 * @param array $params
5361 * @return string HTML
5363 public function renderImageGallery( $text, $params ) {
5364 wfProfileIn( __METHOD__
);
5367 if ( isset( $params['mode'] ) ) {
5368 $mode = $params['mode'];
5372 $ig = ImageGalleryBase
::factory( $mode );
5373 } catch ( MWException
$e ) {
5374 // If invalid type set, fallback to default.
5375 $ig = ImageGalleryBase
::factory( false );
5378 $ig->setContextTitle( $this->mTitle
);
5379 $ig->setShowBytes( false );
5380 $ig->setShowFilename( false );
5381 $ig->setParser( $this );
5382 $ig->setHideBadImages();
5383 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
5385 if ( isset( $params['showfilename'] ) ) {
5386 $ig->setShowFilename( true );
5388 $ig->setShowFilename( false );
5390 if ( isset( $params['caption'] ) ) {
5391 $caption = $params['caption'];
5392 $caption = htmlspecialchars( $caption );
5393 $caption = $this->replaceInternalLinks( $caption );
5394 $ig->setCaptionHtml( $caption );
5396 if ( isset( $params['perrow'] ) ) {
5397 $ig->setPerRow( $params['perrow'] );
5399 if ( isset( $params['widths'] ) ) {
5400 $ig->setWidths( $params['widths'] );
5402 if ( isset( $params['heights'] ) ) {
5403 $ig->setHeights( $params['heights'] );
5405 $ig->setAdditionalOptions( $params );
5407 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5409 $lines = StringUtils
::explode( "\n", $text );
5410 foreach ( $lines as $line ) {
5411 # match lines like these:
5412 # Image:someimage.jpg|This is some image
5414 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5416 if ( count( $matches ) == 0 ) {
5420 if ( strpos( $matches[0], '%' ) !== false ) {
5421 $matches[1] = rawurldecode( $matches[1] );
5423 $title = Title
::newFromText( $matches[1], NS_FILE
);
5424 if ( is_null( $title ) ) {
5425 # Bogus title. Ignore these so we don't bomb out later.
5429 # We need to get what handler the file uses, to figure out parameters.
5430 # Note, a hook can overide the file name, and chose an entirely different
5431 # file (which potentially could be of a different type and have different handler).
5434 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5435 array( $this, $title, &$options, &$descQuery ) );
5436 # Don't register it now, as ImageGallery does that later.
5437 $file = $this->fetchFileNoRegister( $title, $options );
5438 $handler = $file ?
$file->getHandler() : false;
5440 wfProfileIn( __METHOD__
. '-getMagicWord' );
5442 'img_alt' => 'gallery-internal-alt',
5443 'img_link' => 'gallery-internal-link',
5446 $paramMap = $paramMap +
$handler->getParamMap();
5447 // We don't want people to specify per-image widths.
5448 // Additionally the width parameter would need special casing anyhow.
5449 unset( $paramMap['img_width'] );
5452 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5453 wfProfileOut( __METHOD__
. '-getMagicWord' );
5458 $handlerOptions = array();
5459 if ( isset( $matches[3] ) ) {
5460 // look for an |alt= definition while trying not to break existing
5461 // captions with multiple pipes (|) in it, until a more sensible grammar
5462 // is defined for images in galleries
5464 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5465 // splitting on '|' is a bit odd, and different from makeImage.
5466 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5467 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
5469 foreach ( $parameterMatches as $parameterMatch ) {
5470 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5472 $paramName = $paramMap[$magicName];
5474 switch ( $paramName ) {
5475 case 'gallery-internal-alt':
5476 $alt = $this->stripAltText( $match, false );
5478 case 'gallery-internal-link':
5479 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5480 $chars = self
::EXT_LINK_URL_CLASS
;
5481 $prots = $this->mUrlProtocols
;
5482 //check to see if link matches an absolute url, if not then it must be a wiki link.
5483 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5486 $localLinkTitle = Title
::newFromText( $linkValue );
5487 if ( $localLinkTitle !== null ) {
5488 $link = $localLinkTitle->getLinkURL();
5493 // Must be a handler specific parameter.
5494 if ( $handler->validateParam( $paramName, $match ) ) {
5495 $handlerOptions[$paramName] = $match;
5497 // Guess not. Append it to the caption.
5498 wfDebug( "$parameterMatch failed parameter validation\n" );
5499 $label .= '|' . $parameterMatch;
5504 // concatenate all other pipes
5505 $label .= '|' . $parameterMatch;
5508 // remove the first pipe
5509 $label = substr( $label, 1 );
5512 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5514 $html = $ig->toHTML();
5515 wfRunHooks( 'AfterParserFetchFileAndTitle', array( $this, $ig, &$html ) );
5516 wfProfileOut( __METHOD__
);
5521 * @param string $handler
5524 public function getImageParams( $handler ) {
5526 $handlerClass = get_class( $handler );
5530 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5531 # Initialise static lists
5532 static $internalParamNames = array(
5533 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5534 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5535 'bottom', 'text-bottom' ),
5536 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5537 'upright', 'border', 'link', 'alt', 'class' ),
5539 static $internalParamMap;
5540 if ( !$internalParamMap ) {
5541 $internalParamMap = array();
5542 foreach ( $internalParamNames as $type => $names ) {
5543 foreach ( $names as $name ) {
5544 $magicName = str_replace( '-', '_', "img_$name" );
5545 $internalParamMap[$magicName] = array( $type, $name );
5550 # Add handler params
5551 $paramMap = $internalParamMap;
5553 $handlerParamMap = $handler->getParamMap();
5554 foreach ( $handlerParamMap as $magic => $paramName ) {
5555 $paramMap[$magic] = array( 'handler', $paramName );
5558 $this->mImageParams
[$handlerClass] = $paramMap;
5559 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5561 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5565 * Parse image options text and use it to make an image
5567 * @param Title $title
5568 * @param string $options
5569 * @param LinkHolderArray|bool $holders
5570 * @return string HTML
5572 public function makeImage( $title, $options, $holders = false ) {
5573 # Check if the options text is of the form "options|alt text"
5575 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5576 # * left no resizing, just left align. label is used for alt= only
5577 # * right same, but right aligned
5578 # * none same, but not aligned
5579 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5580 # * center center the image
5581 # * frame Keep original image size, no magnify-button.
5582 # * framed Same as "frame"
5583 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5584 # * upright reduce width for upright images, rounded to full __0 px
5585 # * border draw a 1px border around the image
5586 # * alt Text for HTML alt attribute (defaults to empty)
5587 # * class Set a class for img node
5588 # * link Set the target of the image link. Can be external, interwiki, or local
5589 # vertical-align values (no % or length right now):
5599 $parts = StringUtils
::explode( "|", $options );
5601 # Give extensions a chance to select the file revision for us
5604 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5605 array( $this, $title, &$options, &$descQuery ) );
5606 # Fetch and register the file (file title may be different via hooks)
5607 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5610 $handler = $file ?
$file->getHandler() : false;
5612 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5615 $this->addTrackingCategory( 'broken-file-category' );
5618 # Process the input parameters
5620 $params = array( 'frame' => array(), 'handler' => array(),
5621 'horizAlign' => array(), 'vertAlign' => array() );
5622 $seenformat = false;
5623 foreach ( $parts as $part ) {
5624 $part = trim( $part );
5625 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5627 if ( isset( $paramMap[$magicName] ) ) {
5628 list( $type, $paramName ) = $paramMap[$magicName];
5630 # Special case; width and height come in one variable together
5631 if ( $type === 'handler' && $paramName === 'width' ) {
5632 $parsedWidthParam = $this->parseWidthParam( $value );
5633 if ( isset( $parsedWidthParam['width'] ) ) {
5634 $width = $parsedWidthParam['width'];
5635 if ( $handler->validateParam( 'width', $width ) ) {
5636 $params[$type]['width'] = $width;
5640 if ( isset( $parsedWidthParam['height'] ) ) {
5641 $height = $parsedWidthParam['height'];
5642 if ( $handler->validateParam( 'height', $height ) ) {
5643 $params[$type]['height'] = $height;
5647 # else no validation -- bug 13436
5649 if ( $type === 'handler' ) {
5650 # Validate handler parameter
5651 $validated = $handler->validateParam( $paramName, $value );
5653 # Validate internal parameters
5654 switch ( $paramName ) {
5658 # @todo FIXME: Possibly check validity here for
5659 # manualthumb? downstream behavior seems odd with
5660 # missing manual thumbs.
5662 $value = $this->stripAltText( $value, $holders );
5665 $chars = self
::EXT_LINK_URL_CLASS
;
5666 $prots = $this->mUrlProtocols
;
5667 if ( $value === '' ) {
5668 $paramName = 'no-link';
5671 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5672 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5673 $paramName = 'link-url';
5674 $this->mOutput
->addExternalLink( $value );
5675 if ( $this->mOptions
->getExternalLinkTarget() ) {
5676 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5681 $linkTitle = Title
::newFromText( $value );
5683 $paramName = 'link-title';
5684 $value = $linkTitle;
5685 $this->mOutput
->addLink( $linkTitle );
5693 // use first appearing option, discard others.
5694 $validated = ! $seenformat;
5698 # Most other things appear to be empty or numeric...
5699 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5704 $params[$type][$paramName] = $value;
5708 if ( !$validated ) {
5713 # Process alignment parameters
5714 if ( $params['horizAlign'] ) {
5715 $params['frame']['align'] = key( $params['horizAlign'] );
5717 if ( $params['vertAlign'] ) {
5718 $params['frame']['valign'] = key( $params['vertAlign'] );
5721 $params['frame']['caption'] = $caption;
5723 # Will the image be presented in a frame, with the caption below?
5724 $imageIsFramed = isset( $params['frame']['frame'] )
5725 ||
isset( $params['frame']['framed'] )
5726 ||
isset( $params['frame']['thumbnail'] )
5727 ||
isset( $params['frame']['manualthumb'] );
5729 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5730 # came to also set the caption, ordinary text after the image -- which
5731 # makes no sense, because that just repeats the text multiple times in
5732 # screen readers. It *also* came to set the title attribute.
5734 # Now that we have an alt attribute, we should not set the alt text to
5735 # equal the caption: that's worse than useless, it just repeats the
5736 # text. This is the framed/thumbnail case. If there's no caption, we
5737 # use the unnamed parameter for alt text as well, just for the time be-
5738 # ing, if the unnamed param is set and the alt param is not.
5740 # For the future, we need to figure out if we want to tweak this more,
5741 # e.g., introducing a title= parameter for the title; ignoring the un-
5742 # named parameter entirely for images without a caption; adding an ex-
5743 # plicit caption= parameter and preserving the old magic unnamed para-
5745 if ( $imageIsFramed ) { # Framed image
5746 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5747 # No caption or alt text, add the filename as the alt text so
5748 # that screen readers at least get some description of the image
5749 $params['frame']['alt'] = $title->getText();
5751 # Do not set $params['frame']['title'] because tooltips don't make sense
5753 } else { # Inline image
5754 if ( !isset( $params['frame']['alt'] ) ) {
5755 # No alt text, use the "caption" for the alt text
5756 if ( $caption !== '' ) {
5757 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5759 # No caption, fall back to using the filename for the
5761 $params['frame']['alt'] = $title->getText();
5764 # Use the "caption" for the tooltip text
5765 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5768 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5770 # Linker does the rest
5771 $time = isset( $options['time'] ) ?
$options['time'] : false;
5772 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5773 $time, $descQuery, $this->mOptions
->getThumbSize() );
5775 # Give the handler a chance to modify the parser object
5777 $handler->parserTransformHook( $this, $file );
5784 * @param string $caption
5785 * @param LinkHolderArray|bool $holders
5786 * @return mixed|string
5788 protected function stripAltText( $caption, $holders ) {
5789 # Strip bad stuff out of the title (tooltip). We can't just use
5790 # replaceLinkHoldersText() here, because if this function is called
5791 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5793 $tooltip = $holders->replaceText( $caption );
5795 $tooltip = $this->replaceLinkHoldersText( $caption );
5798 # make sure there are no placeholders in thumbnail attributes
5799 # that are later expanded to html- so expand them now and
5801 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5802 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5808 * Set a flag in the output object indicating that the content is dynamic and
5809 * shouldn't be cached.
5811 public function disableCache() {
5812 wfDebug( "Parser output marked as uncacheable.\n" );
5813 if ( !$this->mOutput
) {
5814 throw new MWException( __METHOD__
.
5815 " can only be called when actually parsing something" );
5817 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5818 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5822 * Callback from the Sanitizer for expanding items found in HTML attribute
5823 * values, so they can be safely tested and escaped.
5825 * @param string $text
5826 * @param bool|PPFrame $frame
5829 public function attributeStripCallback( &$text, $frame = false ) {
5830 $text = $this->replaceVariables( $text, $frame );
5831 $text = $this->mStripState
->unstripBoth( $text );
5840 public function getTags() {
5842 array_keys( $this->mTransparentTagHooks
),
5843 array_keys( $this->mTagHooks
),
5844 array_keys( $this->mFunctionTagHooks
)
5849 * Replace transparent tags in $text with the values given by the callbacks.
5851 * Transparent tag hooks are like regular XML-style tag hooks, except they
5852 * operate late in the transformation sequence, on HTML instead of wikitext.
5854 * @param string $text
5858 public function replaceTransparentTags( $text ) {
5860 $elements = array_keys( $this->mTransparentTagHooks
);
5861 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5862 $replacements = array();
5864 foreach ( $matches as $marker => $data ) {
5865 list( $element, $content, $params, $tag ) = $data;
5866 $tagName = strtolower( $element );
5867 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5868 $output = call_user_func_array(
5869 $this->mTransparentTagHooks
[$tagName],
5870 array( $content, $params, $this )
5875 $replacements[$marker] = $output;
5877 return strtr( $text, $replacements );
5881 * Break wikitext input into sections, and either pull or replace
5882 * some particular section's text.
5884 * External callers should use the getSection and replaceSection methods.
5886 * @param string $text Page wikitext
5887 * @param string|number $sectionId A section identifier string of the form:
5888 * "<flag1> - <flag2> - ... - <section number>"
5890 * Currently the only recognised flag is "T", which means the target section number
5891 * was derived during a template inclusion parse, in other words this is a template
5892 * section edit link. If no flags are given, it was an ordinary section edit link.
5893 * This flag is required to avoid a section numbering mismatch when a section is
5894 * enclosed by "<includeonly>" (bug 6563).
5896 * The section number 0 pulls the text before the first heading; other numbers will
5897 * pull the given section along with its lower-level subsections. If the section is
5898 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5900 * Section 0 is always considered to exist, even if it only contains the empty
5901 * string. If $text is the empty string and section 0 is replaced, $newText is
5904 * @param string $mode One of "get" or "replace"
5905 * @param string $newText Replacement text for section data.
5906 * @return string For "get", the extracted section text.
5907 * for "replace", the whole page with the section replaced.
5909 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5910 global $wgTitle; # not generally used but removes an ugly failure mode
5912 $magicScopeVariable = $this->lock();
5913 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5915 $frame = $this->getPreprocessor()->newFrame();
5917 # Process section extraction flags
5919 $sectionParts = explode( '-', $sectionId );
5920 $sectionIndex = array_pop( $sectionParts );
5921 foreach ( $sectionParts as $part ) {
5922 if ( $part === 'T' ) {
5923 $flags |
= self
::PTD_FOR_INCLUSION
;
5927 # Check for empty input
5928 if ( strval( $text ) === '' ) {
5929 # Only sections 0 and T-0 exist in an empty document
5930 if ( $sectionIndex == 0 ) {
5931 if ( $mode === 'get' ) {
5937 if ( $mode === 'get' ) {
5945 # Preprocess the text
5946 $root = $this->preprocessToDom( $text, $flags );
5948 # <h> nodes indicate section breaks
5949 # They can only occur at the top level, so we can find them by iterating the root's children
5950 $node = $root->getFirstChild();
5952 # Find the target section
5953 if ( $sectionIndex == 0 ) {
5954 # Section zero doesn't nest, level=big
5955 $targetLevel = 1000;
5958 if ( $node->getName() === 'h' ) {
5959 $bits = $node->splitHeading();
5960 if ( $bits['i'] == $sectionIndex ) {
5961 $targetLevel = $bits['level'];
5965 if ( $mode === 'replace' ) {
5966 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5968 $node = $node->getNextSibling();
5974 if ( $mode === 'get' ) {
5981 # Find the end of the section, including nested sections
5983 if ( $node->getName() === 'h' ) {
5984 $bits = $node->splitHeading();
5985 $curLevel = $bits['level'];
5986 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5990 if ( $mode === 'get' ) {
5991 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5993 $node = $node->getNextSibling();
5996 # Write out the remainder (in replace mode only)
5997 if ( $mode === 'replace' ) {
5998 # Output the replacement text
5999 # Add two newlines on -- trailing whitespace in $newText is conventionally
6000 # stripped by the editor, so we need both newlines to restore the paragraph gap
6001 # Only add trailing whitespace if there is newText
6002 if ( $newText != "" ) {
6003 $outText .= $newText . "\n\n";
6007 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
6008 $node = $node->getNextSibling();
6012 if ( is_string( $outText ) ) {
6013 # Re-insert stripped tags
6014 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
6021 * This function returns the text of a section, specified by a number ($section).
6022 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
6023 * the first section before any such heading (section 0).
6025 * If a section contains subsections, these are also returned.
6027 * @param string $text Text to look in
6028 * @param string|number $sectionId Section identifier as a number or string
6029 * (e.g. 0, 1 or 'T-1').
6030 * @param string $defaultText Default to return if section is not found
6032 * @return string Text of the requested section
6034 public function getSection( $text, $sectionId, $defaultText = '' ) {
6035 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
6039 * This function returns $oldtext after the content of the section
6040 * specified by $section has been replaced with $text. If the target
6041 * section does not exist, $oldtext is returned unchanged.
6043 * @param string $oldText Former text of the article
6044 * @param string|number $sectionId Section identifier as a number or string
6045 * (e.g. 0, 1 or 'T-1').
6046 * @param string $newText Replacing text
6048 * @return string Modified text
6050 public function replaceSection( $oldText, $sectionId, $newText ) {
6051 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
6055 * Get the ID of the revision we are parsing
6059 public function getRevisionId() {
6060 return $this->mRevisionId
;
6064 * Get the revision object for $this->mRevisionId
6066 * @return Revision|null Either a Revision object or null
6067 * @since 1.23 (public since 1.23)
6069 public function getRevisionObject() {
6070 if ( !is_null( $this->mRevisionObject
) ) {
6071 return $this->mRevisionObject
;
6073 if ( is_null( $this->mRevisionId
) ) {
6077 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
6078 return $this->mRevisionObject
;
6082 * Get the timestamp associated with the current revision, adjusted for
6083 * the default server-local timestamp
6086 public function getRevisionTimestamp() {
6087 if ( is_null( $this->mRevisionTimestamp
) ) {
6088 wfProfileIn( __METHOD__
);
6092 $revObject = $this->getRevisionObject();
6093 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
6095 # The cryptic '' timezone parameter tells to use the site-default
6096 # timezone offset instead of the user settings.
6098 # Since this value will be saved into the parser cache, served
6099 # to other users, and potentially even used inside links and such,
6100 # it needs to be consistent for all visitors.
6101 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
6103 wfProfileOut( __METHOD__
);
6105 return $this->mRevisionTimestamp
;
6109 * Get the name of the user that edited the last revision
6111 * @return string User name
6113 public function getRevisionUser() {
6114 if ( is_null( $this->mRevisionUser
) ) {
6115 $revObject = $this->getRevisionObject();
6117 # if this template is subst: the revision id will be blank,
6118 # so just use the current user's name
6120 $this->mRevisionUser
= $revObject->getUserText();
6121 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6122 $this->mRevisionUser
= $this->getUser()->getName();
6125 return $this->mRevisionUser
;
6129 * Get the size of the revision
6131 * @return int|null Revision size
6133 public function getRevisionSize() {
6134 if ( is_null( $this->mRevisionSize
) ) {
6135 $revObject = $this->getRevisionObject();
6137 # if this variable is subst: the revision id will be blank,
6138 # so just use the parser input size, because the own substituation
6139 # will change the size.
6141 $this->mRevisionSize
= $revObject->getSize();
6142 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6143 $this->mRevisionSize
= $this->mInputSize
;
6146 return $this->mRevisionSize
;
6150 * Mutator for $mDefaultSort
6152 * @param string $sort New value
6154 public function setDefaultSort( $sort ) {
6155 $this->mDefaultSort
= $sort;
6156 $this->mOutput
->setProperty( 'defaultsort', $sort );
6160 * Accessor for $mDefaultSort
6161 * Will use the empty string if none is set.
6163 * This value is treated as a prefix, so the
6164 * empty string is equivalent to sorting by
6169 public function getDefaultSort() {
6170 if ( $this->mDefaultSort
!== false ) {
6171 return $this->mDefaultSort
;
6178 * Accessor for $mDefaultSort
6179 * Unlike getDefaultSort(), will return false if none is set
6181 * @return string|bool
6183 public function getCustomDefaultSort() {
6184 return $this->mDefaultSort
;
6188 * Try to guess the section anchor name based on a wikitext fragment
6189 * presumably extracted from a heading, for example "Header" from
6192 * @param string $text
6196 public function guessSectionNameFromWikiText( $text ) {
6197 # Strip out wikitext links(they break the anchor)
6198 $text = $this->stripSectionName( $text );
6199 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6200 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
6204 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6205 * instead. For use in redirects, since IE6 interprets Redirect: headers
6206 * as something other than UTF-8 (apparently?), resulting in breakage.
6208 * @param string $text The section name
6209 * @return string An anchor
6211 public function guessLegacySectionNameFromWikiText( $text ) {
6212 # Strip out wikitext links(they break the anchor)
6213 $text = $this->stripSectionName( $text );
6214 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6215 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
6219 * Strips a text string of wikitext for use in a section anchor
6221 * Accepts a text string and then removes all wikitext from the
6222 * string and leaves only the resultant text (i.e. the result of
6223 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6224 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6225 * to create valid section anchors by mimicing the output of the
6226 * parser when headings are parsed.
6228 * @param string $text Text string to be stripped of wikitext
6229 * for use in a Section anchor
6230 * @return string Filtered text string
6232 public function stripSectionName( $text ) {
6233 # Strip internal link markup
6234 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6235 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6237 # Strip external link markup
6238 # @todo FIXME: Not tolerant to blank link text
6239 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6240 # on how many empty links there are on the page - need to figure that out.
6241 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6243 # Parse wikitext quotes (italics & bold)
6244 $text = $this->doQuotes( $text );
6247 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
6252 * strip/replaceVariables/unstrip for preprocessor regression testing
6254 * @param string $text
6255 * @param Title $title
6256 * @param ParserOptions $options
6257 * @param int $outputType
6261 public function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
6262 $magicScopeVariable = $this->lock();
6263 $this->startParse( $title, $options, $outputType, true );
6265 $text = $this->replaceVariables( $text );
6266 $text = $this->mStripState
->unstripBoth( $text );
6267 $text = Sanitizer
::removeHTMLtags( $text );
6272 * @param string $text
6273 * @param Title $title
6274 * @param ParserOptions $options
6277 public function testPst( $text, Title
$title, ParserOptions
$options ) {
6278 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6282 * @param string $text
6283 * @param Title $title
6284 * @param ParserOptions $options
6287 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
6288 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
6292 * Call a callback function on all regions of the given text that are not
6293 * inside strip markers, and replace those regions with the return value
6294 * of the callback. For example, with input:
6298 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6299 * two strings will be replaced with the value returned by the callback in
6303 * @param callable $callback
6307 public function markerSkipCallback( $s, $callback ) {
6310 while ( $i < strlen( $s ) ) {
6311 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
6312 if ( $markerStart === false ) {
6313 $out .= call_user_func( $callback, substr( $s, $i ) );
6316 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6317 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6318 if ( $markerEnd === false ) {
6319 $out .= substr( $s, $markerStart );
6322 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6323 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6332 * Remove any strip markers found in the given text.
6334 * @param string $text Input string
6337 public function killMarkers( $text ) {
6338 return $this->mStripState
->killMarkers( $text );
6342 * Save the parser state required to convert the given half-parsed text to
6343 * HTML. "Half-parsed" in this context means the output of
6344 * recursiveTagParse() or internalParse(). This output has strip markers
6345 * from replaceVariables (extensionSubstitution() etc.), and link
6346 * placeholders from replaceLinkHolders().
6348 * Returns an array which can be serialized and stored persistently. This
6349 * array can later be loaded into another parser instance with
6350 * unserializeHalfParsedText(). The text can then be safely incorporated into
6351 * the return value of a parser hook.
6353 * @param string $text
6357 public function serializeHalfParsedText( $text ) {
6358 wfProfileIn( __METHOD__
);
6361 'version' => self
::HALF_PARSED_VERSION
,
6362 'stripState' => $this->mStripState
->getSubState( $text ),
6363 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6365 wfProfileOut( __METHOD__
);
6370 * Load the parser state given in the $data array, which is assumed to
6371 * have been generated by serializeHalfParsedText(). The text contents is
6372 * extracted from the array, and its markers are transformed into markers
6373 * appropriate for the current Parser instance. This transformed text is
6374 * returned, and can be safely included in the return value of a parser
6377 * If the $data array has been stored persistently, the caller should first
6378 * check whether it is still valid, by calling isValidHalfParsedText().
6380 * @param array $data Serialized data
6381 * @throws MWException
6384 public function unserializeHalfParsedText( $data ) {
6385 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6386 throw new MWException( __METHOD__
. ': invalid version' );
6389 # First, extract the strip state.
6390 $texts = array( $data['text'] );
6391 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6393 # Now renumber links
6394 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6396 # Should be good to go.
6401 * Returns true if the given array, presumed to be generated by
6402 * serializeHalfParsedText(), is compatible with the current version of the
6405 * @param array $data
6409 public function isValidHalfParsedText( $data ) {
6410 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6414 * Parsed a width param of imagelink like 300px or 200x300px
6416 * @param string $value
6421 public function parseWidthParam( $value ) {
6422 $parsedWidthParam = array();
6423 if ( $value === '' ) {
6424 return $parsedWidthParam;
6427 # (bug 13500) In both cases (width/height and width only),
6428 # permit trailing "px" for backward compatibility.
6429 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6430 $width = intval( $m[1] );
6431 $height = intval( $m[2] );
6432 $parsedWidthParam['width'] = $width;
6433 $parsedWidthParam['height'] = $height;
6434 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6435 $width = intval( $value );
6436 $parsedWidthParam['width'] = $width;
6438 return $parsedWidthParam;
6442 * Lock the current instance of the parser.
6444 * This is meant to stop someone from calling the parser
6445 * recursively and messing up all the strip state.
6447 * @throws MWException If parser is in a parse
6448 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6450 protected function lock() {
6451 if ( $this->mInParse
) {
6452 throw new MWException( "Parser state cleared while parsing. "
6453 . "Did you call Parser::parse recursively?" );
6455 $this->mInParse
= true;
6458 $recursiveCheck = new ScopedCallback( function() use ( $that ) {
6459 $that->mInParse
= false;
6462 return $recursiveCheck;
6466 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6468 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6469 * or if there is more than one <p/> tag in the input HTML.
6471 * @param string $html
6475 public static function stripOuterParagraph( $html ) {
6477 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6478 if ( strpos( $m[1], '</p>' ) === false ) {
6487 * Return this parser if it is not doing anything, otherwise
6488 * get a fresh parser. You can use this method by doing
6489 * $myParser = $wgParser->getFreshParser(), or more simply
6490 * $wgParser->getFreshParser()->parse( ... );
6491 * if you're unsure if $wgParser is safe to use.
6494 * @return Parser A parser object that is not parsing anything
6496 public function getFreshParser() {
6497 global $wgParserConf;
6498 if ( $this->mInParse
) {
6499 return new $wgParserConf['class']( $wgParserConf );