3 * PHP parser that converts wiki markup to HTML.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * @defgroup Parser Parser
29 * PHP Parser - Processes wiki markup (which uses a more user-friendly
30 * syntax, such as "[[link]]" for making links), and provides a one-way
31 * transformation of that wiki markup it into (X)HTML output / markup
32 * (which in turn the browser understands, and can display).
34 * There are seven main entry points into the Parser class:
37 * produces HTML output
38 * - Parser::preSaveTransform()
39 * produces altered wiki markup
40 * - Parser::preprocess()
41 * removes HTML comments and expands templates
42 * - Parser::cleanSig() and Parser::cleanSigInSig()
43 * cleans a signature before saving it to preferences
44 * - Parser::getSection()
45 * return the content of a section from an article for section editing
46 * - Parser::replaceSection()
47 * replaces a section by number inside an article
48 * - Parser::getPreloadText()
49 * removes <noinclude> sections and <includeonly> tags
54 * @warning $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
57 * $wgNamespacesWithSubpages
59 * @par Settings only within ParserOptions:
60 * $wgAllowExternalImages
61 * $wgAllowSpecialInclusion
69 * Update this version number when the ParserOutput format
70 * changes in an incompatible way, so the parser cache
71 * can automatically discard old data.
73 const VERSION
= '1.6.4';
76 * Update this version number when the output of serialiseHalfParsedText()
77 * changes in an incompatible way
79 const HALF_PARSED_VERSION
= 2;
81 # Flags for Parser::setFunctionHook
82 const SFH_NO_HASH
= 1;
83 const SFH_OBJECT_ARGS
= 2;
85 # Constants needed for external link processing
86 # Everything except bracket, space, or control characters
87 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
88 # as well as U+3000 is IDEOGRAPHIC SPACE for bug 19052
89 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}]';
90 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F\p{Zs}]+)
91 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
93 # State constants for the definition list colon extraction
94 const COLON_STATE_TEXT
= 0;
95 const COLON_STATE_TAG
= 1;
96 const COLON_STATE_TAGSTART
= 2;
97 const COLON_STATE_CLOSETAG
= 3;
98 const COLON_STATE_TAGSLASH
= 4;
99 const COLON_STATE_COMMENT
= 5;
100 const COLON_STATE_COMMENTDASH
= 6;
101 const COLON_STATE_COMMENTDASHDASH
= 7;
103 # Flags for preprocessToDom
104 const PTD_FOR_INCLUSION
= 1;
106 # Allowed values for $this->mOutputType
107 # Parameter to startExternalParse().
108 const OT_HTML
= 1; # like parse()
109 const OT_WIKI
= 2; # like preSaveTransform()
110 const OT_PREPROCESS
= 3; # like preprocess()
112 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
114 # Marker Suffix needs to be accessible staticly.
115 const MARKER_SUFFIX
= "-QINU\x7f";
117 # Markers used for wrapping the table of contents
118 const TOC_START
= '<mw:toc>';
119 const TOC_END
= '</mw:toc>';
122 public $mTagHooks = array();
123 public $mTransparentTagHooks = array();
124 public $mFunctionHooks = array();
125 public $mFunctionSynonyms = array( 0 => array(), 1 => array() );
126 public $mFunctionTagHooks = array();
127 public $mStripList = array();
128 public $mDefaultStripList = array();
129 public $mVarCache = array();
130 public $mImageParams = array();
131 public $mImageParamsMagicArray = array();
132 public $mMarkerIndex = 0;
133 public $mFirstCall = true;
135 # Initialised by initialiseVariables()
138 * @var MagicWordArray
143 * @var MagicWordArray
146 public $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
148 # Cleared with clearState():
153 public $mAutonumber, $mDTopen;
160 public $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
162 * @var LinkHolderArray
164 public $mLinkHolders;
167 public $mIncludeSizes, $mPPNodeCount, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
168 public $mDefaultSort;
169 public $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
170 public $mExpensiveFunctionCount; # number of expensive parser function calls
171 public $mShowToc, $mForceTocPosition;
176 public $mUser; # User object; only used when doing pre-save transform
179 # These are variables reset at least once per parse regardless of $clearState
189 public $mTitle; # Title context, used for self-link rendering and similar things
190 public $mOutputType; # Output type, one of the OT_xxx constants
191 public $ot; # Shortcut alias, see setOutputType()
192 public $mRevisionObject; # The revision object of the specified revision ID
193 public $mRevisionId; # ID to display in {{REVISIONID}} tags
194 public $mRevisionTimestamp; # The timestamp of the specified revision ID
195 public $mRevisionUser; # User to display in {{REVISIONUSER}} tag
196 public $mRevisionSize; # Size to display in {{REVISIONSIZE}} variable
197 public $mRevIdForTs; # The revision ID which was used to fetch the timestamp
198 public $mInputSize = false; # For {{PAGESIZE}} on current page.
206 * @var array Array with the language name of each language link (i.e. the
207 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
208 * duplicate language links to the ParserOutput.
210 public $mLangLinkLanguages;
213 * @var MapCacheLRU|null
216 * A cache of the current revisions of titles. Keys are $title->getPrefixedDbKey()
218 public $currentRevisionCache;
221 * @var bool Recursive call protection.
222 * This variable should be treated as if it were private.
224 public $mInParse = false;
226 /** @var SectionProfiler */
227 protected $mProfiler;
232 public function __construct( $conf = array() ) {
233 $this->mConf
= $conf;
234 $this->mUrlProtocols
= wfUrlProtocols();
235 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
236 self
::EXT_LINK_URL_CLASS
. '+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
237 if ( isset( $conf['preprocessorClass'] ) ) {
238 $this->mPreprocessorClass
= $conf['preprocessorClass'];
239 } elseif ( defined( 'HPHP_VERSION' ) ) {
240 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
241 $this->mPreprocessorClass
= 'Preprocessor_Hash';
242 } elseif ( extension_loaded( 'domxml' ) ) {
243 # PECL extension that conflicts with the core DOM extension (bug 13770)
244 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
245 $this->mPreprocessorClass
= 'Preprocessor_Hash';
246 } elseif ( extension_loaded( 'dom' ) ) {
247 $this->mPreprocessorClass
= 'Preprocessor_DOM';
249 $this->mPreprocessorClass
= 'Preprocessor_Hash';
251 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
255 * Reduce memory usage to reduce the impact of circular references
257 public function __destruct() {
258 if ( isset( $this->mLinkHolders
) ) {
259 unset( $this->mLinkHolders
);
261 foreach ( $this as $name => $value ) {
262 unset( $this->$name );
267 * Allow extensions to clean up when the parser is cloned
269 public function __clone() {
270 $this->mInParse
= false;
272 // Bug 56226: When you create a reference "to" an object field, that
273 // makes the object field itself be a reference too (until the other
274 // reference goes out of scope). When cloning, any field that's a
275 // reference is copied as a reference in the new object. Both of these
276 // are defined PHP5 behaviors, as inconvenient as it is for us when old
277 // hooks from PHP4 days are passing fields by reference.
278 foreach ( array( 'mStripState', 'mVarCache' ) as $k ) {
279 // Make a non-reference copy of the field, then rebind the field to
280 // reference the new copy.
286 Hooks
::run( 'ParserCloned', array( $this ) );
290 * Do various kinds of initialisation on the first call of the parser
292 public function firstCallInit() {
293 if ( !$this->mFirstCall
) {
296 $this->mFirstCall
= false;
298 wfProfileIn( __METHOD__
);
300 CoreParserFunctions
::register( $this );
301 CoreTagHooks
::register( $this );
302 $this->initialiseVariables();
304 Hooks
::run( 'ParserFirstCallInit', array( &$this ) );
305 wfProfileOut( __METHOD__
);
313 public function clearState() {
314 wfProfileIn( __METHOD__
);
315 if ( $this->mFirstCall
) {
316 $this->firstCallInit();
318 $this->mOutput
= new ParserOutput
;
319 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
320 $this->mAutonumber
= 0;
321 $this->mLastSection
= '';
322 $this->mDTopen
= false;
323 $this->mIncludeCount
= array();
324 $this->mArgStack
= false;
325 $this->mInPre
= false;
326 $this->mLinkHolders
= new LinkHolderArray( $this );
328 $this->mRevisionObject
= $this->mRevisionTimestamp
=
329 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
330 $this->mVarCache
= array();
332 $this->mLangLinkLanguages
= array();
333 $this->currentRevisionCache
= null;
336 * Prefix for temporary replacement strings for the multipass parser.
337 * \x07 should never appear in input as it's disallowed in XML.
338 * Using it at the front also gives us a little extra robustness
339 * since it shouldn't match when butted up against identifier-like
342 * Must not consist of all title characters, or else it will change
343 * the behavior of <nowiki> in a link.
345 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
346 $this->mStripState
= new StripState( $this->mUniqPrefix
);
348 # Clear these on every parse, bug 4549
349 $this->mTplRedirCache
= $this->mTplDomCache
= array();
351 $this->mShowToc
= true;
352 $this->mForceTocPosition
= false;
353 $this->mIncludeSizes
= array(
357 $this->mPPNodeCount
= 0;
358 $this->mGeneratedPPNodeCount
= 0;
359 $this->mHighestExpansionDepth
= 0;
360 $this->mDefaultSort
= false;
361 $this->mHeadings
= array();
362 $this->mDoubleUnderscores
= array();
363 $this->mExpensiveFunctionCount
= 0;
366 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
367 $this->mPreprocessor
= null;
370 $this->mProfiler
= new SectionProfiler();
372 Hooks
::run( 'ParserClearState', array( &$this ) );
373 wfProfileOut( __METHOD__
);
377 * Convert wikitext to HTML
378 * Do not call this function recursively.
380 * @param string $text Text we want to parse
381 * @param Title $title
382 * @param ParserOptions $options
383 * @param bool $linestart
384 * @param bool $clearState
385 * @param int $revid Number to pass in {{REVISIONID}}
386 * @return ParserOutput A ParserOutput
388 public function parse( $text, Title
$title, ParserOptions
$options,
389 $linestart = true, $clearState = true, $revid = null
392 * First pass--just handle <nowiki> sections, pass the rest off
393 * to internalParse() which does all the real work.
396 global $wgShowHostnames;
397 $fname = __METHOD__
. '-' . wfGetCaller();
398 wfProfileIn( __METHOD__
);
399 wfProfileIn( $fname );
402 $magicScopeVariable = $this->lock();
405 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
407 $this->currentRevisionCache
= null;
408 $this->mInputSize
= strlen( $text );
409 if ( $this->mOptions
->getEnableLimitReport() ) {
410 $this->mOutput
->resetParseStartTime();
413 # Remove the strip marker tag prefix from the input, if present.
415 $text = str_replace( $this->mUniqPrefix
, '', $text );
418 $oldRevisionId = $this->mRevisionId
;
419 $oldRevisionObject = $this->mRevisionObject
;
420 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
421 $oldRevisionUser = $this->mRevisionUser
;
422 $oldRevisionSize = $this->mRevisionSize
;
423 if ( $revid !== null ) {
424 $this->mRevisionId
= $revid;
425 $this->mRevisionObject
= null;
426 $this->mRevisionTimestamp
= null;
427 $this->mRevisionUser
= null;
428 $this->mRevisionSize
= null;
431 Hooks
::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
433 Hooks
::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
434 $text = $this->internalParse( $text );
435 Hooks
::run( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
437 $text = $this->internalParseHalfParsed( $text, true, $linestart );
440 * A converted title will be provided in the output object if title and
441 * content conversion are enabled, the article text does not contain
442 * a conversion-suppressing double-underscore tag, and no
443 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
444 * automatic link conversion.
446 if ( !( $options->getDisableTitleConversion()
447 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
448 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
449 ||
$this->mOutput
->getDisplayTitle() !== false )
451 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
452 if ( $convruletitle ) {
453 $this->mOutput
->setTitleText( $convruletitle );
455 $titleText = $this->getConverterLanguage()->convertTitle( $title );
456 $this->mOutput
->setTitleText( $titleText );
460 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
461 $this->limitationWarn( 'expensive-parserfunction',
462 $this->mExpensiveFunctionCount
,
463 $this->mOptions
->getExpensiveParserFunctionLimit()
467 # Information on include size limits, for the benefit of users who try to skirt them
468 if ( $this->mOptions
->getEnableLimitReport() ) {
469 $max = $this->mOptions
->getMaxIncludeSize();
471 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
472 if ( $cpuTime !== null ) {
473 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
474 sprintf( "%.3f", $cpuTime )
478 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
479 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
480 sprintf( "%.3f", $wallTime )
483 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
484 array( $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() )
486 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
487 array( $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() )
489 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
490 array( $this->mIncludeSizes
['post-expand'], $max )
492 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
493 array( $this->mIncludeSizes
['arg'], $max )
495 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
496 array( $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() )
498 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
499 array( $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() )
501 Hooks
::run( 'ParserLimitReportPrepare', array( $this, $this->mOutput
) );
503 $limitReport = "NewPP limit report\n";
504 if ( $wgShowHostnames ) {
505 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
507 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
508 if ( Hooks
::run( 'ParserLimitReportFormat',
509 array( $key, &$value, &$limitReport, false, false )
511 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
512 $valueMsg = wfMessage( array( "$key-value-text", "$key-value" ) )
513 ->inLanguage( 'en' )->useDatabase( false );
514 if ( !$valueMsg->exists() ) {
515 $valueMsg = new RawMessage( '$1' );
517 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
518 $valueMsg->params( $value );
519 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
523 // Since we're not really outputting HTML, decode the entities and
524 // then re-encode the things that need hiding inside HTML comments.
525 $limitReport = htmlspecialchars_decode( $limitReport );
526 Hooks
::run( 'ParserLimitReport', array( $this, &$limitReport ) );
528 // Sanitize for comment. Note '‐' in the replacement is U+2010,
529 // which looks much like the problematic '-'.
530 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&' ), $limitReport );
531 $text .= "\n<!-- \n$limitReport-->\n";
533 // Add on template profiling data
534 $dataByFunc = $this->mProfiler
->getFunctionStats();
535 uasort( $dataByFunc, function ( $a, $b ) {
536 return $a['real'] < $b['real']; // descending order
538 $profileReport = "Transclusion expansion time report (%,ms,calls,template)\n";
539 foreach ( array_slice( $dataByFunc, 0, 10 ) as $item ) {
540 $profileReport .= sprintf( "%6.2f%% %8.3f %6d - %s\n",
541 $item['%real'], $item['real'], $item['calls'],
542 htmlspecialchars( $item['name'] ) );
544 $text .= "\n<!-- \n$profileReport-->\n";
546 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
547 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
548 $this->mTitle
->getPrefixedDBkey() );
551 $this->mOutput
->setText( $text );
553 $this->mRevisionId
= $oldRevisionId;
554 $this->mRevisionObject
= $oldRevisionObject;
555 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
556 $this->mRevisionUser
= $oldRevisionUser;
557 $this->mRevisionSize
= $oldRevisionSize;
558 $this->mInputSize
= false;
559 $this->currentRevisionCache
= null;
560 wfProfileOut( $fname );
561 wfProfileOut( __METHOD__
);
563 return $this->mOutput
;
567 * Half-parse wikitext to half-parsed HTML. This recursive parser entry point
568 * can be called from an extension tag hook.
570 * The output of this function IS NOT SAFE PARSED HTML; it is "half-parsed"
571 * instead, which means that lists and links have not been fully parsed yet,
572 * and strip markers are still present.
574 * Use recursiveTagParseFully() to fully parse wikitext to output-safe HTML.
576 * Use this function if you're a parser tag hook and you want to parse
577 * wikitext before or after applying additional transformations, and you
578 * intend to *return the result as hook output*, which will cause it to go
579 * through the rest of parsing process automatically.
581 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
582 * $text are not expanded
584 * @param string $text Text extension wants to have parsed
585 * @param bool|PPFrame $frame The frame to use for expanding any template variables
586 * @return string UNSAFE half-parsed HTML
588 public function recursiveTagParse( $text, $frame = false ) {
589 wfProfileIn( __METHOD__
);
590 Hooks
::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
591 Hooks
::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
592 $text = $this->internalParse( $text, false, $frame );
593 wfProfileOut( __METHOD__
);
598 * Fully parse wikitext to fully parsed HTML. This recursive parser entry
599 * point can be called from an extension tag hook.
601 * The output of this function is fully-parsed HTML that is safe for output.
602 * If you're a parser tag hook, you might want to use recursiveTagParse()
605 * If $frame is not provided, then template variables (e.g., {{{1}}}) within
606 * $text are not expanded
610 * @param string $text Text extension wants to have parsed
611 * @param bool|PPFrame $frame The frame to use for expanding any template variables
612 * @return string Fully parsed HTML
614 public function recursiveTagParseFully( $text, $frame = false ) {
615 wfProfileIn( __METHOD__
);
616 $text = $this->recursiveTagParse( $text, $frame );
617 $text = $this->internalParseHalfParsed( $text, false );
618 wfProfileOut( __METHOD__
);
623 * Expand templates and variables in the text, producing valid, static wikitext.
624 * Also removes comments.
625 * Do not call this function recursively.
626 * @param string $text
627 * @param Title $title
628 * @param ParserOptions $options
629 * @param int|null $revid
630 * @param bool|PPFrame $frame
631 * @return mixed|string
633 public function preprocess( $text, Title
$title = null, ParserOptions
$options, $revid = null, $frame = false ) {
634 wfProfileIn( __METHOD__
);
635 $magicScopeVariable = $this->lock();
636 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
637 if ( $revid !== null ) {
638 $this->mRevisionId
= $revid;
640 Hooks
::run( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
641 Hooks
::run( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
642 $text = $this->replaceVariables( $text, $frame );
643 $text = $this->mStripState
->unstripBoth( $text );
644 wfProfileOut( __METHOD__
);
649 * Recursive parser entry point that can be called from an extension tag
652 * @param string $text Text to be expanded
653 * @param bool|PPFrame $frame The frame to use for expanding any template variables
657 public function recursivePreprocess( $text, $frame = false ) {
658 wfProfileIn( __METHOD__
);
659 $text = $this->replaceVariables( $text, $frame );
660 $text = $this->mStripState
->unstripBoth( $text );
661 wfProfileOut( __METHOD__
);
666 * Process the wikitext for the "?preload=" feature. (bug 5210)
668 * "<noinclude>", "<includeonly>" etc. are parsed as for template
669 * transclusion, comments, templates, arguments, tags hooks and parser
670 * functions are untouched.
672 * @param string $text
673 * @param Title $title
674 * @param ParserOptions $options
675 * @param array $params
678 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = array() ) {
679 $msg = new RawMessage( $text );
680 $text = $msg->params( $params )->plain();
682 # Parser (re)initialisation
683 $magicScopeVariable = $this->lock();
684 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
686 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
687 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
688 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
689 $text = $this->mStripState
->unstripBoth( $text );
694 * Get a random string
698 public static function getRandomString() {
699 return wfRandomString( 16 );
703 * Set the current user.
704 * Should only be used when doing pre-save transform.
706 * @param User|null $user User object or null (to reset)
708 public function setUser( $user ) {
709 $this->mUser
= $user;
713 * Accessor for mUniqPrefix.
717 public function uniqPrefix() {
718 if ( !isset( $this->mUniqPrefix
) ) {
719 # @todo FIXME: This is probably *horribly wrong*
720 # LanguageConverter seems to want $wgParser's uniqPrefix, however
721 # if this is called for a parser cache hit, the parser may not
722 # have ever been initialized in the first place.
723 # Not really sure what the heck is supposed to be going on here.
725 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
727 return $this->mUniqPrefix
;
731 * Set the context title
735 public function setTitle( $t ) {
737 $t = Title
::newFromText( 'NO TITLE' );
740 if ( $t->hasFragment() ) {
741 # Strip the fragment to avoid various odd effects
742 $this->mTitle
= clone $t;
743 $this->mTitle
->setFragment( '' );
750 * Accessor for the Title object
754 public function getTitle() {
755 return $this->mTitle
;
759 * Accessor/mutator for the Title object
761 * @param Title $x Title object or null to just get the current one
764 public function Title( $x = null ) {
765 return wfSetVar( $this->mTitle
, $x );
769 * Set the output type
771 * @param int $ot New value
773 public function setOutputType( $ot ) {
774 $this->mOutputType
= $ot;
777 'html' => $ot == self
::OT_HTML
,
778 'wiki' => $ot == self
::OT_WIKI
,
779 'pre' => $ot == self
::OT_PREPROCESS
,
780 'plain' => $ot == self
::OT_PLAIN
,
785 * Accessor/mutator for the output type
787 * @param int|null $x New value or null to just get the current one
790 public function OutputType( $x = null ) {
791 return wfSetVar( $this->mOutputType
, $x );
795 * Get the ParserOutput object
797 * @return ParserOutput
799 public function getOutput() {
800 return $this->mOutput
;
804 * Get the ParserOptions object
806 * @return ParserOptions
808 public function getOptions() {
809 return $this->mOptions
;
813 * Accessor/mutator for the ParserOptions object
815 * @param ParserOptions $x New value or null to just get the current one
816 * @return ParserOptions Current ParserOptions object
818 public function Options( $x = null ) {
819 return wfSetVar( $this->mOptions
, $x );
825 public function nextLinkID() {
826 return $this->mLinkID++
;
832 public function setLinkID( $id ) {
833 $this->mLinkID
= $id;
837 * Get a language object for use in parser functions such as {{FORMATNUM:}}
840 public function getFunctionLang() {
841 return $this->getTargetLanguage();
845 * Get the target language for the content being parsed. This is usually the
846 * language that the content is in.
850 * @throws MWException
853 public function getTargetLanguage() {
854 $target = $this->mOptions
->getTargetLanguage();
856 if ( $target !== null ) {
858 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
859 return $this->mOptions
->getUserLangObj();
860 } elseif ( is_null( $this->mTitle
) ) {
861 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
864 return $this->mTitle
->getPageLanguage();
868 * Get the language object for language conversion
869 * @return Language|null
871 public function getConverterLanguage() {
872 return $this->getTargetLanguage();
876 * Get a User object either from $this->mUser, if set, or from the
877 * ParserOptions object otherwise
881 public function getUser() {
882 if ( !is_null( $this->mUser
) ) {
885 return $this->mOptions
->getUser();
889 * Get a preprocessor object
891 * @return Preprocessor
893 public function getPreprocessor() {
894 if ( !isset( $this->mPreprocessor
) ) {
895 $class = $this->mPreprocessorClass
;
896 $this->mPreprocessor
= new $class( $this );
898 return $this->mPreprocessor
;
902 * Replaces all occurrences of HTML-style comments and the given tags
903 * in the text with a random marker and returns the next text. The output
904 * parameter $matches will be an associative array filled with data in
908 * 'UNIQ-xxxxx' => array(
911 * array( 'param' => 'x' ),
912 * '<element param="x">tag content</element>' ) )
915 * @param array $elements List of element names. Comments are always extracted.
916 * @param string $text Source text string.
917 * @param array $matches Out parameter, Array: extracted tags
918 * @param string $uniq_prefix
919 * @return string Stripped text
921 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
926 $taglist = implode( '|', $elements );
927 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
929 while ( $text != '' ) {
930 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
932 if ( count( $p ) < 5 ) {
935 if ( count( $p ) > 5 ) {
949 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
950 $stripped .= $marker;
952 if ( $close === '/>' ) {
953 # Empty element tag, <tag />
958 if ( $element === '!--' ) {
961 $end = "/(<\\/$element\\s*>)/i";
963 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
965 if ( count( $q ) < 3 ) {
966 # No end tag -- let it run out to the end of the text.
975 $matches[$marker] = array( $element,
977 Sanitizer
::decodeTagAttributes( $attributes ),
978 "<$element$attributes$close$content$tail" );
984 * Get a list of strippable XML-like elements
988 public function getStripList() {
989 return $this->mStripList
;
993 * Add an item to the strip state
994 * Returns the unique tag which must be inserted into the stripped text
995 * The tag will be replaced with the original text in unstrip()
997 * @param string $text
1001 public function insertStripItem( $text ) {
1002 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
1003 $this->mMarkerIndex++
;
1004 $this->mStripState
->addGeneral( $rnd, $text );
1009 * parse the wiki syntax used to render tables
1012 * @param string $text
1015 public function doTableStuff( $text ) {
1016 wfProfileIn( __METHOD__
);
1018 $lines = StringUtils
::explode( "\n", $text );
1020 $td_history = array(); # Is currently a td tag open?
1021 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
1022 $tr_history = array(); # Is currently a tr tag open?
1023 $tr_attributes = array(); # history of tr attributes
1024 $has_opened_tr = array(); # Did this table open a <tr> element?
1025 $indent_level = 0; # indent level of the table
1027 foreach ( $lines as $outLine ) {
1028 $line = trim( $outLine );
1030 if ( $line === '' ) { # empty line, go to next line
1031 $out .= $outLine . "\n";
1035 $first_character = $line[0];
1038 if ( preg_match( '/^(:*)\{\|(.*)$/', $line, $matches ) ) {
1039 # First check if we are starting a new table
1040 $indent_level = strlen( $matches[1] );
1042 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1043 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1045 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1046 array_push( $td_history, false );
1047 array_push( $last_tag_history, '' );
1048 array_push( $tr_history, false );
1049 array_push( $tr_attributes, '' );
1050 array_push( $has_opened_tr, false );
1051 } elseif ( count( $td_history ) == 0 ) {
1052 # Don't do any of the following
1053 $out .= $outLine . "\n";
1055 } elseif ( substr( $line, 0, 2 ) === '|}' ) {
1056 # We are ending a table
1057 $line = '</table>' . substr( $line, 2 );
1058 $last_tag = array_pop( $last_tag_history );
1060 if ( !array_pop( $has_opened_tr ) ) {
1061 $line = "<tr><td></td></tr>{$line}";
1064 if ( array_pop( $tr_history ) ) {
1065 $line = "</tr>{$line}";
1068 if ( array_pop( $td_history ) ) {
1069 $line = "</{$last_tag}>{$line}";
1071 array_pop( $tr_attributes );
1072 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
1073 } elseif ( substr( $line, 0, 2 ) === '|-' ) {
1074 # Now we have a table row
1075 $line = preg_replace( '#^\|-+#', '', $line );
1077 # Whats after the tag is now only attributes
1078 $attributes = $this->mStripState
->unstripBoth( $line );
1079 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1080 array_pop( $tr_attributes );
1081 array_push( $tr_attributes, $attributes );
1084 $last_tag = array_pop( $last_tag_history );
1085 array_pop( $has_opened_tr );
1086 array_push( $has_opened_tr, true );
1088 if ( array_pop( $tr_history ) ) {
1092 if ( array_pop( $td_history ) ) {
1093 $line = "</{$last_tag}>{$line}";
1097 array_push( $tr_history, false );
1098 array_push( $td_history, false );
1099 array_push( $last_tag_history, '' );
1100 } elseif ( $first_character === '|'
1101 ||
$first_character === '!'
1102 ||
substr( $line, 0, 2 ) === '|+'
1104 # This might be cell elements, td, th or captions
1105 if ( substr( $line, 0, 2 ) === '|+' ) {
1106 $first_character = '+';
1107 $line = substr( $line, 1 );
1110 $line = substr( $line, 1 );
1112 if ( $first_character === '!' ) {
1113 $line = str_replace( '!!', '||', $line );
1116 # Split up multiple cells on the same line.
1117 # FIXME : This can result in improper nesting of tags processed
1118 # by earlier parser steps, but should avoid splitting up eg
1119 # attribute values containing literal "||".
1120 $cells = StringUtils
::explodeMarkup( '||', $line );
1124 # Loop through each table cell
1125 foreach ( $cells as $cell ) {
1127 if ( $first_character !== '+' ) {
1128 $tr_after = array_pop( $tr_attributes );
1129 if ( !array_pop( $tr_history ) ) {
1130 $previous = "<tr{$tr_after}>\n";
1132 array_push( $tr_history, true );
1133 array_push( $tr_attributes, '' );
1134 array_pop( $has_opened_tr );
1135 array_push( $has_opened_tr, true );
1138 $last_tag = array_pop( $last_tag_history );
1140 if ( array_pop( $td_history ) ) {
1141 $previous = "</{$last_tag}>\n{$previous}";
1144 if ( $first_character === '|' ) {
1146 } elseif ( $first_character === '!' ) {
1148 } elseif ( $first_character === '+' ) {
1149 $last_tag = 'caption';
1154 array_push( $last_tag_history, $last_tag );
1156 # A cell could contain both parameters and data
1157 $cell_data = explode( '|', $cell, 2 );
1159 # Bug 553: Note that a '|' inside an invalid link should not
1160 # be mistaken as delimiting cell parameters
1161 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1162 $cell = "{$previous}<{$last_tag}>{$cell}";
1163 } elseif ( count( $cell_data ) == 1 ) {
1164 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1166 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1167 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1168 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1172 array_push( $td_history, true );
1175 $out .= $outLine . "\n";
1178 # Closing open td, tr && table
1179 while ( count( $td_history ) > 0 ) {
1180 if ( array_pop( $td_history ) ) {
1183 if ( array_pop( $tr_history ) ) {
1186 if ( !array_pop( $has_opened_tr ) ) {
1187 $out .= "<tr><td></td></tr>\n";
1190 $out .= "</table>\n";
1193 # Remove trailing line-ending (b/c)
1194 if ( substr( $out, -1 ) === "\n" ) {
1195 $out = substr( $out, 0, -1 );
1198 # special case: don't return empty table
1199 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1203 wfProfileOut( __METHOD__
);
1209 * Helper function for parse() that transforms wiki markup into half-parsed
1210 * HTML. Only called for $mOutputType == self::OT_HTML.
1214 * @param string $text
1215 * @param bool $isMain
1216 * @param bool $frame
1220 public function internalParse( $text, $isMain = true, $frame = false ) {
1221 wfProfileIn( __METHOD__
);
1225 # Hook to suspend the parser in this state
1226 if ( !Hooks
::run( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1227 wfProfileOut( __METHOD__
);
1231 # if $frame is provided, then use $frame for replacing any variables
1233 # use frame depth to infer how include/noinclude tags should be handled
1234 # depth=0 means this is the top-level document; otherwise it's an included document
1235 if ( !$frame->depth
) {
1238 $flag = Parser
::PTD_FOR_INCLUSION
;
1240 $dom = $this->preprocessToDom( $text, $flag );
1241 $text = $frame->expand( $dom );
1243 # if $frame is not provided, then use old-style replaceVariables
1244 $text = $this->replaceVariables( $text );
1247 Hooks
::run( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1248 $text = Sanitizer
::removeHTMLtags(
1250 array( &$this, 'attributeStripCallback' ),
1252 array_keys( $this->mTransparentTagHooks
)
1254 Hooks
::run( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1256 # Tables need to come after variable replacement for things to work
1257 # properly; putting them before other transformations should keep
1258 # exciting things like link expansions from showing up in surprising
1260 $text = $this->doTableStuff( $text );
1262 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1264 $text = $this->doDoubleUnderscore( $text );
1266 $text = $this->doHeadings( $text );
1267 $text = $this->replaceInternalLinks( $text );
1268 $text = $this->doAllQuotes( $text );
1269 $text = $this->replaceExternalLinks( $text );
1271 # replaceInternalLinks may sometimes leave behind
1272 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1273 $text = str_replace( $this->mUniqPrefix
. 'NOPARSE', '', $text );
1275 $text = $this->doMagicLinks( $text );
1276 $text = $this->formatHeadings( $text, $origText, $isMain );
1278 wfProfileOut( __METHOD__
);
1283 * Helper function for parse() that transforms half-parsed HTML into fully
1286 * @param string $text
1287 * @param bool $isMain
1288 * @param bool $linestart
1291 private function internalParseHalfParsed( $text, $isMain = true, $linestart = true ) {
1292 global $wgUseTidy, $wgAlwaysUseTidy;
1294 $text = $this->mStripState
->unstripGeneral( $text );
1296 # Clean up special characters, only run once, next-to-last before doBlockLevels
1298 # french spaces, last one Guillemet-left
1299 # only if there is something before the space
1300 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
1301 # french spaces, Guillemet-right
1302 '/(\\302\\253) /' => '\\1 ',
1303 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
1305 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
1307 $text = $this->doBlockLevels( $text, $linestart );
1309 $this->replaceLinkHolders( $text );
1312 * The input doesn't get language converted if
1314 * b) Content isn't converted
1315 * c) It's a conversion table
1316 * d) it is an interface message (which is in the user language)
1318 if ( !( $this->mOptions
->getDisableContentConversion()
1319 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
1321 if ( !$this->mOptions
->getInterfaceMessage() ) {
1322 # The position of the convert() call should not be changed. it
1323 # assumes that the links are all replaced and the only thing left
1324 # is the <nowiki> mark.
1325 $text = $this->getConverterLanguage()->convert( $text );
1329 $text = $this->mStripState
->unstripNoWiki( $text );
1332 Hooks
::run( 'ParserBeforeTidy', array( &$this, &$text ) );
1335 $text = $this->replaceTransparentTags( $text );
1336 $text = $this->mStripState
->unstripGeneral( $text );
1338 $text = Sanitizer
::normalizeCharReferences( $text );
1340 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
1341 $text = MWTidy
::tidy( $text );
1343 # attempt to sanitize at least some nesting problems
1344 # (bug #2702 and quite a few others)
1346 # ''Something [http://www.cool.com cool''] -->
1347 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
1348 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
1349 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
1350 # fix up an anchor inside another anchor, only
1351 # at least for a single single nested link (bug 3695)
1352 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
1353 '\\1\\2</a>\\3</a>\\1\\4</a>',
1354 # fix div inside inline elements- doBlockLevels won't wrap a line which
1355 # contains a div, so fix it up here; replace
1356 # div with escaped text
1357 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
1358 '\\1\\3<div\\5>\\6</div>\\8\\9',
1359 # remove empty italic or bold tag pairs, some
1360 # introduced by rules above
1361 '/<([bi])><\/\\1>/' => '',
1364 $text = preg_replace(
1365 array_keys( $tidyregs ),
1366 array_values( $tidyregs ),
1371 Hooks
::run( 'ParserAfterTidy', array( &$this, &$text ) );
1378 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1379 * magic external links.
1384 * @param string $text
1388 public function doMagicLinks( $text ) {
1389 wfProfileIn( __METHOD__
);
1390 $prots = wfUrlProtocolsWithoutProtRel();
1391 $urlChar = self
::EXT_LINK_URL_CLASS
;
1392 $text = preg_replace_callback(
1394 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1395 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1396 (\b(?i:$prots)$urlChar+) | # m[3]: Free external links" . '
1397 \b(?:RFC|PMID)\s+([0-9]+)\b |# m[4]: RFC or PMID, capture number
1398 \bISBN\s+( # m[5]: ISBN, capture number
1399 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1400 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1401 [0-9Xx] # check digit
1403 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1404 wfProfileOut( __METHOD__
);
1409 * @throws MWException
1411 * @return HTML|string
1413 public function magicLinkCallback( $m ) {
1414 if ( isset( $m[1] ) && $m[1] !== '' ) {
1417 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1420 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1421 # Free external link
1422 return $this->makeFreeExternalLink( $m[0] );
1423 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1425 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1428 $cssClass = 'mw-magiclink-rfc';
1430 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1432 $urlmsg = 'pubmedurl';
1433 $cssClass = 'mw-magiclink-pmid';
1436 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1437 substr( $m[0], 0, 20 ) . '"' );
1439 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1440 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass );
1441 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1444 $num = strtr( $isbn, array(
1449 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1450 return '<a href="' .
1451 htmlspecialchars( $titleObj->getLocalURL() ) .
1452 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1459 * Make a free external link, given a user-supplied URL
1461 * @param string $url
1463 * @return string HTML
1466 public function makeFreeExternalLink( $url ) {
1467 wfProfileIn( __METHOD__
);
1471 # The characters '<' and '>' (which were escaped by
1472 # removeHTMLtags()) should not be included in
1473 # URLs, per RFC 2396.
1475 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1476 $trail = substr( $url, $m2[0][1] ) . $trail;
1477 $url = substr( $url, 0, $m2[0][1] );
1480 # Move trailing punctuation to $trail
1482 # If there is no left bracket, then consider right brackets fair game too
1483 if ( strpos( $url, '(' ) === false ) {
1487 $urlRev = strrev( $url );
1488 $numSepChars = strspn( $urlRev, $sep );
1489 # Don't break a trailing HTML entity by moving the ; into $trail
1490 # This is in hot code, so use substr_compare to avoid having to
1491 # create a new string object for the comparison
1492 if ( $numSepChars && substr_compare( $url, ";", -$numSepChars, 1 ) === 0) {
1493 # more optimization: instead of running preg_match with a $
1494 # anchor, which can be slow, do the match on the reversed
1495 # string starting at the desired offset.
1496 # un-reversed regexp is: /&([a-z]+|#x[\da-f]+|#\d+)$/i
1497 if ( preg_match( '/\G([a-z]+|[\da-f]+x#|\d+#)&/i', $urlRev, $m2, 0, $numSepChars ) ) {
1501 if ( $numSepChars ) {
1502 $trail = substr( $url, -$numSepChars ) . $trail;
1503 $url = substr( $url, 0, -$numSepChars );
1506 $url = Sanitizer
::cleanUrl( $url );
1508 # Is this an external image?
1509 $text = $this->maybeMakeExternalImage( $url );
1510 if ( $text === false ) {
1511 # Not an image, make a link
1512 $text = Linker
::makeExternalLink( $url,
1513 $this->getConverterLanguage()->markNoConversion( $url, true ),
1515 $this->getExternalLinkAttribs( $url ) );
1516 # Register it in the output object...
1517 # Replace unnecessary URL escape codes with their equivalent characters
1518 $pasteurized = self
::normalizeLinkUrl( $url );
1519 $this->mOutput
->addExternalLink( $pasteurized );
1521 wfProfileOut( __METHOD__
);
1522 return $text . $trail;
1526 * Parse headers and return html
1530 * @param string $text
1534 public function doHeadings( $text ) {
1535 wfProfileIn( __METHOD__
);
1536 for ( $i = 6; $i >= 1; --$i ) {
1537 $h = str_repeat( '=', $i );
1538 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1540 wfProfileOut( __METHOD__
);
1545 * Replace single quotes with HTML markup
1548 * @param string $text
1550 * @return string The altered text
1552 public function doAllQuotes( $text ) {
1553 wfProfileIn( __METHOD__
);
1555 $lines = StringUtils
::explode( "\n", $text );
1556 foreach ( $lines as $line ) {
1557 $outtext .= $this->doQuotes( $line ) . "\n";
1559 $outtext = substr( $outtext, 0, -1 );
1560 wfProfileOut( __METHOD__
);
1565 * Helper function for doAllQuotes()
1567 * @param string $text
1571 public function doQuotes( $text ) {
1572 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1573 $countarr = count( $arr );
1574 if ( $countarr == 1 ) {
1578 // First, do some preliminary work. This may shift some apostrophes from
1579 // being mark-up to being text. It also counts the number of occurrences
1580 // of bold and italics mark-ups.
1583 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1584 $thislen = strlen( $arr[$i] );
1585 // If there are ever four apostrophes, assume the first is supposed to
1586 // be text, and the remaining three constitute mark-up for bold text.
1587 // (bug 13227: ''''foo'''' turns into ' ''' foo ' ''')
1588 if ( $thislen == 4 ) {
1589 $arr[$i - 1] .= "'";
1592 } elseif ( $thislen > 5 ) {
1593 // If there are more than 5 apostrophes in a row, assume they're all
1594 // text except for the last 5.
1595 // (bug 13227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1596 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1600 // Count the number of occurrences of bold and italics mark-ups.
1601 if ( $thislen == 2 ) {
1603 } elseif ( $thislen == 3 ) {
1605 } elseif ( $thislen == 5 ) {
1611 // If there is an odd number of both bold and italics, it is likely
1612 // that one of the bold ones was meant to be an apostrophe followed
1613 // by italics. Which one we cannot know for certain, but it is more
1614 // likely to be one that has a single-letter word before it.
1615 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1616 $firstsingleletterword = -1;
1617 $firstmultiletterword = -1;
1619 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1620 if ( strlen( $arr[$i] ) == 3 ) {
1621 $x1 = substr( $arr[$i - 1], -1 );
1622 $x2 = substr( $arr[$i - 1], -2, 1 );
1623 if ( $x1 === ' ' ) {
1624 if ( $firstspace == -1 ) {
1627 } elseif ( $x2 === ' ' ) {
1628 if ( $firstsingleletterword == -1 ) {
1629 $firstsingleletterword = $i;
1630 // if $firstsingleletterword is set, we don't
1631 // look at the other options, so we can bail early.
1635 if ( $firstmultiletterword == -1 ) {
1636 $firstmultiletterword = $i;
1642 // If there is a single-letter word, use it!
1643 if ( $firstsingleletterword > -1 ) {
1644 $arr[$firstsingleletterword] = "''";
1645 $arr[$firstsingleletterword - 1] .= "'";
1646 } elseif ( $firstmultiletterword > -1 ) {
1647 // If not, but there's a multi-letter word, use that one.
1648 $arr[$firstmultiletterword] = "''";
1649 $arr[$firstmultiletterword - 1] .= "'";
1650 } elseif ( $firstspace > -1 ) {
1651 // ... otherwise use the first one that has neither.
1652 // (notice that it is possible for all three to be -1 if, for example,
1653 // there is only one pentuple-apostrophe in the line)
1654 $arr[$firstspace] = "''";
1655 $arr[$firstspace - 1] .= "'";
1659 // Now let's actually convert our apostrophic mush to HTML!
1664 foreach ( $arr as $r ) {
1665 if ( ( $i %
2 ) == 0 ) {
1666 if ( $state === 'both' ) {
1672 $thislen = strlen( $r );
1673 if ( $thislen == 2 ) {
1674 if ( $state === 'i' ) {
1677 } elseif ( $state === 'bi' ) {
1680 } elseif ( $state === 'ib' ) {
1681 $output .= '</b></i><b>';
1683 } elseif ( $state === 'both' ) {
1684 $output .= '<b><i>' . $buffer . '</i>';
1686 } else { // $state can be 'b' or ''
1690 } elseif ( $thislen == 3 ) {
1691 if ( $state === 'b' ) {
1694 } elseif ( $state === 'bi' ) {
1695 $output .= '</i></b><i>';
1697 } elseif ( $state === 'ib' ) {
1700 } elseif ( $state === 'both' ) {
1701 $output .= '<i><b>' . $buffer . '</b>';
1703 } else { // $state can be 'i' or ''
1707 } elseif ( $thislen == 5 ) {
1708 if ( $state === 'b' ) {
1709 $output .= '</b><i>';
1711 } elseif ( $state === 'i' ) {
1712 $output .= '</i><b>';
1714 } elseif ( $state === 'bi' ) {
1715 $output .= '</i></b>';
1717 } elseif ( $state === 'ib' ) {
1718 $output .= '</b></i>';
1720 } elseif ( $state === 'both' ) {
1721 $output .= '<i><b>' . $buffer . '</b></i>';
1723 } else { // ($state == '')
1731 // Now close all remaining tags. Notice that the order is important.
1732 if ( $state === 'b' ||
$state === 'ib' ) {
1735 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1738 if ( $state === 'bi' ) {
1741 // There might be lonely ''''', so make sure we have a buffer
1742 if ( $state === 'both' && $buffer ) {
1743 $output .= '<b><i>' . $buffer . '</i></b>';
1749 * Replace external links (REL)
1751 * Note: this is all very hackish and the order of execution matters a lot.
1752 * Make sure to run tests/parserTests.php if you change this code.
1756 * @param string $text
1758 * @throws MWException
1761 public function replaceExternalLinks( $text ) {
1762 wfProfileIn( __METHOD__
);
1764 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1765 if ( $bits === false ) {
1766 wfProfileOut( __METHOD__
);
1767 throw new MWException( "PCRE needs to be compiled with "
1768 . "--enable-unicode-properties in order for MediaWiki to function" );
1770 $s = array_shift( $bits );
1773 while ( $i < count( $bits ) ) {
1776 $text = $bits[$i++
];
1777 $trail = $bits[$i++
];
1779 # The characters '<' and '>' (which were escaped by
1780 # removeHTMLtags()) should not be included in
1781 # URLs, per RFC 2396.
1783 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1784 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1785 $url = substr( $url, 0, $m2[0][1] );
1788 # If the link text is an image URL, replace it with an <img> tag
1789 # This happened by accident in the original parser, but some people used it extensively
1790 $img = $this->maybeMakeExternalImage( $text );
1791 if ( $img !== false ) {
1797 # Set linktype for CSS - if URL==text, link is essentially free
1798 $linktype = ( $text === $url ) ?
'free' : 'text';
1800 # No link text, e.g. [http://domain.tld/some.link]
1801 if ( $text == '' ) {
1803 $langObj = $this->getTargetLanguage();
1804 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1805 $linktype = 'autonumber';
1807 # Have link text, e.g. [http://domain.tld/some.link text]s
1809 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1812 $text = $this->getConverterLanguage()->markNoConversion( $text );
1814 $url = Sanitizer
::cleanUrl( $url );
1816 # Use the encoded URL
1817 # This means that users can paste URLs directly into the text
1818 # Funny characters like ö aren't valid in URLs anyway
1819 # This was changed in August 2004
1820 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1821 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1823 # Register link in the output object.
1824 # Replace unnecessary URL escape codes with the referenced character
1825 # This prevents spammers from hiding links from the filters
1826 $pasteurized = self
::normalizeLinkUrl( $url );
1827 $this->mOutput
->addExternalLink( $pasteurized );
1830 wfProfileOut( __METHOD__
);
1835 * Get the rel attribute for a particular external link.
1838 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1839 * nofollow if appropriate
1840 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1841 * @return string|null Rel attribute for $url
1843 public static function getExternalLinkRel( $url = false, $title = null ) {
1844 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1845 $ns = $title ?
$title->getNamespace() : false;
1846 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1847 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1855 * Get an associative array of additional HTML attributes appropriate for a
1856 * particular external link. This currently may include rel => nofollow
1857 * (depending on configuration, namespace, and the URL's domain) and/or a
1858 * target attribute (depending on configuration).
1860 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1861 * nofollow if appropriate
1862 * @return array Associative array of HTML attributes
1864 public function getExternalLinkAttribs( $url = false ) {
1866 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1868 if ( $this->mOptions
->getExternalLinkTarget() ) {
1869 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1875 * Replace unusual escape codes in a URL with their equivalent characters
1877 * @deprecated since 1.24, use normalizeLinkUrl
1878 * @param string $url
1881 public static function replaceUnusualEscapes( $url ) {
1882 wfDeprecated( __METHOD__
, '1.24' );
1883 return self
::normalizeLinkUrl( $url );
1887 * Replace unusual escape codes in a URL with their equivalent characters
1889 * This generally follows the syntax defined in RFC 3986, with special
1890 * consideration for HTTP query strings.
1892 * @param string $url
1895 public static function normalizeLinkUrl( $url ) {
1896 # First, make sure unsafe characters are encoded
1897 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
1899 return rawurlencode( $m[0] );
1905 $end = strlen( $url );
1907 # Fragment part - 'fragment'
1908 $start = strpos( $url, '#' );
1909 if ( $start !== false && $start < $end ) {
1910 $ret = self
::normalizeUrlComponent(
1911 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
1915 # Query part - 'query' minus &=+;
1916 $start = strpos( $url, '?' );
1917 if ( $start !== false && $start < $end ) {
1918 $ret = self
::normalizeUrlComponent(
1919 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
1923 # Scheme and path part - 'pchar'
1924 # (we assume no userinfo or encoded colons in the host)
1925 $ret = self
::normalizeUrlComponent(
1926 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
1931 private static function normalizeUrlComponent( $component, $unsafe ) {
1932 $callback = function ( $matches ) use ( $unsafe ) {
1933 $char = urldecode( $matches[0] );
1934 $ord = ord( $char );
1935 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
1939 # Leave it escaped, but use uppercase for a-f
1940 return strtoupper( $matches[0] );
1943 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
1947 * make an image if it's allowed, either through the global
1948 * option, through the exception, or through the on-wiki whitelist
1950 * @param string $url
1954 private function maybeMakeExternalImage( $url ) {
1955 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1956 $imagesexception = !empty( $imagesfrom );
1958 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1959 if ( $imagesexception && is_array( $imagesfrom ) ) {
1960 $imagematch = false;
1961 foreach ( $imagesfrom as $match ) {
1962 if ( strpos( $url, $match ) === 0 ) {
1967 } elseif ( $imagesexception ) {
1968 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1970 $imagematch = false;
1973 if ( $this->mOptions
->getAllowExternalImages()
1974 ||
( $imagesexception && $imagematch )
1976 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1978 $text = Linker
::makeExternalImage( $url );
1981 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1982 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
1984 $whitelist = explode(
1986 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
1989 foreach ( $whitelist as $entry ) {
1990 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1991 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1994 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1995 # Image matches a whitelist entry
1996 $text = Linker
::makeExternalImage( $url );
2005 * Process [[ ]] wikilinks
2009 * @return string Processed text
2013 public function replaceInternalLinks( $s ) {
2014 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
2019 * Process [[ ]] wikilinks (RIL)
2021 * @throws MWException
2022 * @return LinkHolderArray
2026 public function replaceInternalLinks2( &$s ) {
2027 global $wgExtraInterlanguageLinkPrefixes;
2028 wfProfileIn( __METHOD__
);
2030 wfProfileIn( __METHOD__
. '-setup' );
2031 static $tc = false, $e1, $e1_img;
2032 # the % is needed to support urlencoded titles as well
2034 $tc = Title
::legalChars() . '#%';
2035 # Match a link having the form [[namespace:link|alternate]]trail
2036 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2037 # Match cases where there is no "]]", which might still be images
2038 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2041 $holders = new LinkHolderArray( $this );
2043 # split the entire text string on occurrences of [[
2044 $a = StringUtils
::explode( '[[', ' ' . $s );
2045 # get the first element (all text up to first [[), and remove the space we added
2048 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2049 $s = substr( $s, 1 );
2051 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2053 if ( $useLinkPrefixExtension ) {
2054 # Match the end of a line for a word that's not followed by whitespace,
2055 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2057 $charset = $wgContLang->linkPrefixCharset();
2058 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2061 if ( is_null( $this->mTitle
) ) {
2062 wfProfileOut( __METHOD__
. '-setup' );
2063 wfProfileOut( __METHOD__
);
2064 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
2066 $nottalk = !$this->mTitle
->isTalkPage();
2068 if ( $useLinkPrefixExtension ) {
2070 if ( preg_match( $e2, $s, $m ) ) {
2071 $first_prefix = $m[2];
2073 $first_prefix = false;
2079 $useSubpages = $this->areSubpagesAllowed();
2080 wfProfileOut( __METHOD__
. '-setup' );
2082 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
2083 # Loop for each link
2084 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2085 // @codingStandardsIgnoreStart
2087 # Check for excessive memory usage
2088 if ( $holders->isBig() ) {
2090 # Do the existence check, replace the link holders and clear the array
2091 $holders->replace( $s );
2095 if ( $useLinkPrefixExtension ) {
2096 wfProfileIn( __METHOD__
. '-prefixhandling' );
2097 if ( preg_match( $e2, $s, $m ) ) {
2104 if ( $first_prefix ) {
2105 $prefix = $first_prefix;
2106 $first_prefix = false;
2108 wfProfileOut( __METHOD__
. '-prefixhandling' );
2111 $might_be_img = false;
2113 wfProfileIn( __METHOD__
. "-e1" );
2114 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2116 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2117 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2118 # the real problem is with the $e1 regex
2121 # Still some problems for cases where the ] is meant to be outside punctuation,
2122 # and no image is in sight. See bug 2095.
2125 && substr( $m[3], 0, 1 ) === ']'
2126 && strpos( $text, '[' ) !== false
2128 $text .= ']'; # so that replaceExternalLinks($text) works later
2129 $m[3] = substr( $m[3], 1 );
2131 # fix up urlencoded title texts
2132 if ( strpos( $m[1], '%' ) !== false ) {
2133 # Should anchors '#' also be rejected?
2134 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) );
2137 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2138 # Invalid, but might be an image with a link in its caption
2139 $might_be_img = true;
2141 if ( strpos( $m[1], '%' ) !== false ) {
2142 $m[1] = rawurldecode( $m[1] );
2145 } else { # Invalid form; output directly
2146 $s .= $prefix . '[[' . $line;
2147 wfProfileOut( __METHOD__
. "-e1" );
2150 wfProfileOut( __METHOD__
. "-e1" );
2151 wfProfileIn( __METHOD__
. "-misc" );
2155 # Don't allow internal links to pages containing
2156 # PROTO: where PROTO is a valid URL protocol; these
2157 # should be external links.
2158 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2159 $s .= $prefix . '[[' . $line;
2160 wfProfileOut( __METHOD__
. "-misc" );
2164 # Make subpage if necessary
2165 if ( $useSubpages ) {
2166 $link = $this->maybeDoSubpageLink( $origLink, $text );
2171 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2173 # Strip off leading ':'
2174 $link = substr( $link, 1 );
2177 wfProfileOut( __METHOD__
. "-misc" );
2178 wfProfileIn( __METHOD__
. "-title" );
2179 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
2180 if ( $nt === null ) {
2181 $s .= $prefix . '[[' . $line;
2182 wfProfileOut( __METHOD__
. "-title" );
2186 $ns = $nt->getNamespace();
2187 $iw = $nt->getInterwiki();
2188 wfProfileOut( __METHOD__
. "-title" );
2190 if ( $might_be_img ) { # if this is actually an invalid link
2191 wfProfileIn( __METHOD__
. "-might_be_img" );
2192 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2195 # look at the next 'line' to see if we can close it there
2197 $next_line = $a->current();
2198 if ( $next_line === false ||
$next_line === null ) {
2201 $m = explode( ']]', $next_line, 3 );
2202 if ( count( $m ) == 3 ) {
2203 # the first ]] closes the inner link, the second the image
2205 $text .= "[[{$m[0]}]]{$m[1]}";
2208 } elseif ( count( $m ) == 2 ) {
2209 # if there's exactly one ]] that's fine, we'll keep looking
2210 $text .= "[[{$m[0]}]]{$m[1]}";
2212 # if $next_line is invalid too, we need look no further
2213 $text .= '[[' . $next_line;
2218 # we couldn't find the end of this imageLink, so output it raw
2219 # but don't ignore what might be perfectly normal links in the text we've examined
2220 $holders->merge( $this->replaceInternalLinks2( $text ) );
2221 $s .= "{$prefix}[[$link|$text";
2222 # note: no $trail, because without an end, there *is* no trail
2223 wfProfileOut( __METHOD__
. "-might_be_img" );
2226 } else { # it's not an image, so output it raw
2227 $s .= "{$prefix}[[$link|$text";
2228 # note: no $trail, because without an end, there *is* no trail
2229 wfProfileOut( __METHOD__
. "-might_be_img" );
2232 wfProfileOut( __METHOD__
. "-might_be_img" );
2235 $wasblank = ( $text == '' );
2239 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
2240 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2241 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2242 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2243 $text = $this->doQuotes( $text );
2246 # Link not escaped by : , create the various objects
2247 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2249 wfProfileIn( __METHOD__
. "-interwiki" );
2251 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2252 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2253 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2256 # Bug 24502: filter duplicates
2257 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2258 $this->mLangLinkLanguages
[$iw] = true;
2259 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2262 $s = rtrim( $s . $prefix );
2263 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2264 wfProfileOut( __METHOD__
. "-interwiki" );
2267 wfProfileOut( __METHOD__
. "-interwiki" );
2269 if ( $ns == NS_FILE
) {
2270 wfProfileIn( __METHOD__
. "-image" );
2271 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2273 # if no parameters were passed, $text
2274 # becomes something like "File:Foo.png",
2275 # which we don't want to pass on to the
2279 # recursively parse links inside the image caption
2280 # actually, this will parse them in any other parameters, too,
2281 # but it might be hard to fix that, and it doesn't matter ATM
2282 $text = $this->replaceExternalLinks( $text );
2283 $holders->merge( $this->replaceInternalLinks2( $text ) );
2285 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2286 $s .= $prefix . $this->armorLinks(
2287 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2289 $s .= $prefix . $trail;
2291 wfProfileOut( __METHOD__
. "-image" );
2295 if ( $ns == NS_CATEGORY
) {
2296 wfProfileIn( __METHOD__
. "-category" );
2297 $s = rtrim( $s . "\n" ); # bug 87
2300 $sortkey = $this->getDefaultSort();
2304 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2305 $sortkey = str_replace( "\n", '', $sortkey );
2306 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2307 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2310 * Strip the whitespace Category links produce, see bug 87
2312 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2314 wfProfileOut( __METHOD__
. "-category" );
2319 # Self-link checking. For some languages, variants of the title are checked in
2320 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2321 # for linking to a different variant.
2322 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2323 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2327 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2328 # @todo FIXME: Should do batch file existence checks, see comment below
2329 if ( $ns == NS_MEDIA
) {
2330 wfProfileIn( __METHOD__
. "-media" );
2331 # Give extensions a chance to select the file revision for us
2334 Hooks
::run( 'BeforeParserFetchFileAndTitle',
2335 array( $this, $nt, &$options, &$descQuery ) );
2336 # Fetch and register the file (file title may be different via hooks)
2337 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2338 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2339 $s .= $prefix . $this->armorLinks(
2340 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2341 wfProfileOut( __METHOD__
. "-media" );
2345 wfProfileIn( __METHOD__
. "-always_known" );
2346 # Some titles, such as valid special pages or files in foreign repos, should
2347 # be shown as bluelinks even though they're not included in the page table
2349 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2350 # batch file existence checks for NS_FILE and NS_MEDIA
2351 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2352 $this->mOutput
->addLink( $nt );
2353 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2355 # Links will be added to the output link list after checking
2356 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2358 wfProfileOut( __METHOD__
. "-always_known" );
2360 wfProfileOut( __METHOD__
);
2365 * Render a forced-blue link inline; protect against double expansion of
2366 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2367 * Since this little disaster has to split off the trail text to avoid
2368 * breaking URLs in the following text without breaking trails on the
2369 * wiki links, it's been made into a horrible function.
2372 * @param string $text
2373 * @param array|string $query
2374 * @param string $trail
2375 * @param string $prefix
2376 * @return string HTML-wikitext mix oh yuck
2378 public function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2379 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2381 if ( is_string( $query ) ) {
2382 $query = wfCgiToArray( $query );
2384 if ( $text == '' ) {
2385 $text = htmlspecialchars( $nt->getPrefixedText() );
2388 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2390 return $this->armorLinks( $link ) . $trail;
2394 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2395 * going to go through further parsing steps before inline URL expansion.
2397 * Not needed quite as much as it used to be since free links are a bit
2398 * more sensible these days. But bracketed links are still an issue.
2400 * @param string $text More-or-less HTML
2401 * @return string Less-or-more HTML with NOPARSE bits
2403 public function armorLinks( $text ) {
2404 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2405 "{$this->mUniqPrefix}NOPARSE$1", $text );
2409 * Return true if subpage links should be expanded on this page.
2412 public function areSubpagesAllowed() {
2413 # Some namespaces don't allow subpages
2414 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2418 * Handle link to subpage if necessary
2420 * @param string $target The source of the link
2421 * @param string &$text The link text, modified as necessary
2422 * @return string The full name of the link
2425 public function maybeDoSubpageLink( $target, &$text ) {
2426 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2430 * Used by doBlockLevels()
2435 public function closeParagraph() {
2437 if ( $this->mLastSection
!= '' ) {
2438 $result = '</' . $this->mLastSection
. ">\n";
2440 $this->mInPre
= false;
2441 $this->mLastSection
= '';
2446 * getCommon() returns the length of the longest common substring
2447 * of both arguments, starting at the beginning of both.
2450 * @param string $st1
2451 * @param string $st2
2455 public function getCommon( $st1, $st2 ) {
2456 $fl = strlen( $st1 );
2457 $shorter = strlen( $st2 );
2458 if ( $fl < $shorter ) {
2462 for ( $i = 0; $i < $shorter; ++
$i ) {
2463 if ( $st1[$i] != $st2[$i] ) {
2471 * These next three functions open, continue, and close the list
2472 * element appropriate to the prefix character passed into them.
2475 * @param string $char
2479 public function openList( $char ) {
2480 $result = $this->closeParagraph();
2482 if ( '*' === $char ) {
2483 $result .= "<ul><li>";
2484 } elseif ( '#' === $char ) {
2485 $result .= "<ol><li>";
2486 } elseif ( ':' === $char ) {
2487 $result .= "<dl><dd>";
2488 } elseif ( ';' === $char ) {
2489 $result .= "<dl><dt>";
2490 $this->mDTopen
= true;
2492 $result = '<!-- ERR 1 -->';
2500 * @param string $char
2505 public function nextItem( $char ) {
2506 if ( '*' === $char ||
'#' === $char ) {
2507 return "</li>\n<li>";
2508 } elseif ( ':' === $char ||
';' === $char ) {
2510 if ( $this->mDTopen
) {
2513 if ( ';' === $char ) {
2514 $this->mDTopen
= true;
2515 return $close . '<dt>';
2517 $this->mDTopen
= false;
2518 return $close . '<dd>';
2521 return '<!-- ERR 2 -->';
2526 * @param string $char
2531 public function closeList( $char ) {
2532 if ( '*' === $char ) {
2533 $text = "</li></ul>";
2534 } elseif ( '#' === $char ) {
2535 $text = "</li></ol>";
2536 } elseif ( ':' === $char ) {
2537 if ( $this->mDTopen
) {
2538 $this->mDTopen
= false;
2539 $text = "</dt></dl>";
2541 $text = "</dd></dl>";
2544 return '<!-- ERR 3 -->';
2551 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2553 * @param string $text
2554 * @param bool $linestart Whether or not this is at the start of a line.
2556 * @return string The lists rendered as HTML
2558 public function doBlockLevels( $text, $linestart ) {
2559 wfProfileIn( __METHOD__
);
2561 # Parsing through the text line by line. The main thing
2562 # happening here is handling of block-level elements p, pre,
2563 # and making lists from lines starting with * # : etc.
2565 $textLines = StringUtils
::explode( "\n", $text );
2567 $lastPrefix = $output = '';
2568 $this->mDTopen
= $inBlockElem = false;
2570 $paragraphStack = false;
2571 $inBlockquote = false;
2573 foreach ( $textLines as $oLine ) {
2575 if ( !$linestart ) {
2585 $lastPrefixLength = strlen( $lastPrefix );
2586 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2587 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2588 # If not in a <pre> element, scan for and figure out what prefixes are there.
2589 if ( !$this->mInPre
) {
2590 # Multiple prefixes may abut each other for nested lists.
2591 $prefixLength = strspn( $oLine, '*#:;' );
2592 $prefix = substr( $oLine, 0, $prefixLength );
2595 # ; and : are both from definition-lists, so they're equivalent
2596 # for the purposes of determining whether or not we need to open/close
2598 $prefix2 = str_replace( ';', ':', $prefix );
2599 $t = substr( $oLine, $prefixLength );
2600 $this->mInPre
= (bool)$preOpenMatch;
2602 # Don't interpret any other prefixes in preformatted text
2604 $prefix = $prefix2 = '';
2609 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2610 # Same as the last item, so no need to deal with nesting or opening stuff
2611 $output .= $this->nextItem( substr( $prefix, -1 ) );
2612 $paragraphStack = false;
2614 if ( substr( $prefix, -1 ) === ';' ) {
2615 # The one nasty exception: definition lists work like this:
2616 # ; title : definition text
2617 # So we check for : in the remainder text to split up the
2618 # title and definition, without b0rking links.
2620 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2622 $output .= $term . $this->nextItem( ':' );
2625 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2626 # We need to open or close prefixes, or both.
2628 # Either open or close a level...
2629 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2630 $paragraphStack = false;
2632 # Close all the prefixes which aren't shared.
2633 while ( $commonPrefixLength < $lastPrefixLength ) {
2634 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2635 --$lastPrefixLength;
2638 # Continue the current prefix if appropriate.
2639 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2640 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2643 # Open prefixes where appropriate.
2644 if ( $lastPrefix && $prefixLength > $commonPrefixLength ) {
2647 while ( $prefixLength > $commonPrefixLength ) {
2648 $char = substr( $prefix, $commonPrefixLength, 1 );
2649 $output .= $this->openList( $char );
2651 if ( ';' === $char ) {
2652 # @todo FIXME: This is dupe of code above
2653 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2655 $output .= $term . $this->nextItem( ':' );
2658 ++
$commonPrefixLength;
2660 if ( !$prefixLength && $lastPrefix ) {
2663 $lastPrefix = $prefix2;
2666 # If we have no prefixes, go to paragraph mode.
2667 if ( 0 == $prefixLength ) {
2668 wfProfileIn( __METHOD__
. "-paragraph" );
2669 # No prefix (not in list)--go to paragraph mode
2670 # XXX: use a stack for nestable elements like span, table and div
2671 $openmatch = preg_match(
2672 '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|'
2673 . '<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS',
2676 $closematch = preg_match(
2677 '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'
2678 . '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|<\\/mw:|'
2679 . $this->mUniqPrefix
2680 . '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS',
2684 if ( $openmatch ||
$closematch ) {
2685 $paragraphStack = false;
2686 # @todo bug 5718: paragraph closed
2687 $output .= $this->closeParagraph();
2688 if ( $preOpenMatch && !$preCloseMatch ) {
2689 $this->mInPre
= true;
2692 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t, $bqMatch, PREG_OFFSET_CAPTURE
, $bqOffset ) ) {
2693 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
2694 $bqOffset = $bqMatch[0][1] +
strlen( $bqMatch[0][0] );
2696 $inBlockElem = !$closematch;
2697 } elseif ( !$inBlockElem && !$this->mInPre
) {
2698 if ( ' ' == substr( $t, 0, 1 )
2699 && ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' )
2703 if ( $this->mLastSection
!== 'pre' ) {
2704 $paragraphStack = false;
2705 $output .= $this->closeParagraph() . '<pre>';
2706 $this->mLastSection
= 'pre';
2708 $t = substr( $t, 1 );
2711 if ( trim( $t ) === '' ) {
2712 if ( $paragraphStack ) {
2713 $output .= $paragraphStack . '<br />';
2714 $paragraphStack = false;
2715 $this->mLastSection
= 'p';
2717 if ( $this->mLastSection
!== 'p' ) {
2718 $output .= $this->closeParagraph();
2719 $this->mLastSection
= '';
2720 $paragraphStack = '<p>';
2722 $paragraphStack = '</p><p>';
2726 if ( $paragraphStack ) {
2727 $output .= $paragraphStack;
2728 $paragraphStack = false;
2729 $this->mLastSection
= 'p';
2730 } elseif ( $this->mLastSection
!== 'p' ) {
2731 $output .= $this->closeParagraph() . '<p>';
2732 $this->mLastSection
= 'p';
2737 wfProfileOut( __METHOD__
. "-paragraph" );
2739 # somewhere above we forget to get out of pre block (bug 785)
2740 if ( $preCloseMatch && $this->mInPre
) {
2741 $this->mInPre
= false;
2743 if ( $paragraphStack === false ) {
2745 if ( $prefixLength === 0 ) {
2750 while ( $prefixLength ) {
2751 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2753 if ( !$prefixLength ) {
2757 if ( $this->mLastSection
!= '' ) {
2758 $output .= '</' . $this->mLastSection
. '>';
2759 $this->mLastSection
= '';
2762 wfProfileOut( __METHOD__
);
2767 * Split up a string on ':', ignoring any occurrences inside tags
2768 * to prevent illegal overlapping.
2770 * @param string $str The string to split
2771 * @param string &$before Set to everything before the ':'
2772 * @param string &$after Set to everything after the ':'
2773 * @throws MWException
2774 * @return string The position of the ':', or false if none found
2776 public function findColonNoLinks( $str, &$before, &$after ) {
2777 wfProfileIn( __METHOD__
);
2779 $pos = strpos( $str, ':' );
2780 if ( $pos === false ) {
2782 wfProfileOut( __METHOD__
);
2786 $lt = strpos( $str, '<' );
2787 if ( $lt === false ||
$lt > $pos ) {
2788 # Easy; no tag nesting to worry about
2789 $before = substr( $str, 0, $pos );
2790 $after = substr( $str, $pos +
1 );
2791 wfProfileOut( __METHOD__
);
2795 # Ugly state machine to walk through avoiding tags.
2796 $state = self
::COLON_STATE_TEXT
;
2798 $len = strlen( $str );
2799 for ( $i = 0; $i < $len; $i++
) {
2803 # (Using the number is a performance hack for common cases)
2804 case 0: # self::COLON_STATE_TEXT:
2807 # Could be either a <start> tag or an </end> tag
2808 $state = self
::COLON_STATE_TAGSTART
;
2811 if ( $stack == 0 ) {
2813 $before = substr( $str, 0, $i );
2814 $after = substr( $str, $i +
1 );
2815 wfProfileOut( __METHOD__
);
2818 # Embedded in a tag; don't break it.
2821 # Skip ahead looking for something interesting
2822 $colon = strpos( $str, ':', $i );
2823 if ( $colon === false ) {
2824 # Nothing else interesting
2825 wfProfileOut( __METHOD__
);
2828 $lt = strpos( $str, '<', $i );
2829 if ( $stack === 0 ) {
2830 if ( $lt === false ||
$colon < $lt ) {
2832 $before = substr( $str, 0, $colon );
2833 $after = substr( $str, $colon +
1 );
2834 wfProfileOut( __METHOD__
);
2838 if ( $lt === false ) {
2839 # Nothing else interesting to find; abort!
2840 # We're nested, but there's no close tags left. Abort!
2843 # Skip ahead to next tag start
2845 $state = self
::COLON_STATE_TAGSTART
;
2848 case 1: # self::COLON_STATE_TAG:
2853 $state = self
::COLON_STATE_TEXT
;
2856 # Slash may be followed by >?
2857 $state = self
::COLON_STATE_TAGSLASH
;
2863 case 2: # self::COLON_STATE_TAGSTART:
2866 $state = self
::COLON_STATE_CLOSETAG
;
2869 $state = self
::COLON_STATE_COMMENT
;
2872 # Illegal early close? This shouldn't happen D:
2873 $state = self
::COLON_STATE_TEXT
;
2876 $state = self
::COLON_STATE_TAG
;
2879 case 3: # self::COLON_STATE_CLOSETAG:
2884 wfDebug( __METHOD__
. ": Invalid input; too many close tags\n" );
2885 wfProfileOut( __METHOD__
);
2888 $state = self
::COLON_STATE_TEXT
;
2891 case self
::COLON_STATE_TAGSLASH
:
2893 # Yes, a self-closed tag <blah/>
2894 $state = self
::COLON_STATE_TEXT
;
2896 # Probably we're jumping the gun, and this is an attribute
2897 $state = self
::COLON_STATE_TAG
;
2900 case 5: # self::COLON_STATE_COMMENT:
2902 $state = self
::COLON_STATE_COMMENTDASH
;
2905 case self
::COLON_STATE_COMMENTDASH
:
2907 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2909 $state = self
::COLON_STATE_COMMENT
;
2912 case self
::COLON_STATE_COMMENTDASHDASH
:
2914 $state = self
::COLON_STATE_TEXT
;
2916 $state = self
::COLON_STATE_COMMENT
;
2920 wfProfileOut( __METHOD__
);
2921 throw new MWException( "State machine error in " . __METHOD__
);
2925 wfDebug( __METHOD__
. ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2926 wfProfileOut( __METHOD__
);
2929 wfProfileOut( __METHOD__
);
2934 * Return value of a magic variable (like PAGENAME)
2939 * @param bool|PPFrame $frame
2941 * @throws MWException
2944 public function getVariableValue( $index, $frame = false ) {
2945 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2946 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2948 if ( is_null( $this->mTitle
) ) {
2949 // If no title set, bad things are going to happen
2950 // later. Title should always be set since this
2951 // should only be called in the middle of a parse
2952 // operation (but the unit-tests do funky stuff)
2953 throw new MWException( __METHOD__
. ' Should only be '
2954 . ' called while parsing (no title set)' );
2958 * Some of these require message or data lookups and can be
2959 * expensive to check many times.
2961 if ( Hooks
::run( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2962 if ( isset( $this->mVarCache
[$index] ) ) {
2963 return $this->mVarCache
[$index];
2967 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2968 Hooks
::run( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2970 $pageLang = $this->getFunctionLang();
2976 case 'currentmonth':
2977 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ) );
2979 case 'currentmonth1':
2980 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2982 case 'currentmonthname':
2983 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2985 case 'currentmonthnamegen':
2986 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2988 case 'currentmonthabbrev':
2989 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2992 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ) );
2995 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ) );
2998 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ) );
3001 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
3003 case 'localmonthname':
3004 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
3006 case 'localmonthnamegen':
3007 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
3009 case 'localmonthabbrev':
3010 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
3013 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ) );
3016 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ) );
3019 $value = wfEscapeWikiText( $this->mTitle
->getText() );
3022 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
3024 case 'fullpagename':
3025 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
3027 case 'fullpagenamee':
3028 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
3031 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
3033 case 'subpagenamee':
3034 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
3036 case 'rootpagename':
3037 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
3039 case 'rootpagenamee':
3040 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
3043 $this->mTitle
->getRootText()
3046 case 'basepagename':
3047 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
3049 case 'basepagenamee':
3050 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
3053 $this->mTitle
->getBaseText()
3056 case 'talkpagename':
3057 if ( $this->mTitle
->canTalk() ) {
3058 $talkPage = $this->mTitle
->getTalkPage();
3059 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
3064 case 'talkpagenamee':
3065 if ( $this->mTitle
->canTalk() ) {
3066 $talkPage = $this->mTitle
->getTalkPage();
3067 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
3072 case 'subjectpagename':
3073 $subjPage = $this->mTitle
->getSubjectPage();
3074 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
3076 case 'subjectpagenamee':
3077 $subjPage = $this->mTitle
->getSubjectPage();
3078 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
3080 case 'pageid': // requested in bug 23427
3081 $pageid = $this->getTitle()->getArticleID();
3082 if ( $pageid == 0 ) {
3083 # 0 means the page doesn't exist in the database,
3084 # which means the user is previewing a new page.
3085 # The vary-revision flag must be set, because the magic word
3086 # will have a different value once the page is saved.
3087 $this->mOutput
->setFlag( 'vary-revision' );
3088 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
3090 $value = $pageid ?
$pageid : null;
3093 # Let the edit saving system know we should parse the page
3094 # *after* a revision ID has been assigned.
3095 $this->mOutput
->setFlag( 'vary-revision' );
3096 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
3097 $value = $this->mRevisionId
;
3100 # Let the edit saving system know we should parse the page
3101 # *after* a revision ID has been assigned. This is for null edits.
3102 $this->mOutput
->setFlag( 'vary-revision' );
3103 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
3104 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
3106 case 'revisionday2':
3107 # Let the edit saving system know we should parse the page
3108 # *after* a revision ID has been assigned. This is for null edits.
3109 $this->mOutput
->setFlag( 'vary-revision' );
3110 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
3111 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
3113 case 'revisionmonth':
3114 # Let the edit saving system know we should parse the page
3115 # *after* a revision ID has been assigned. This is for null edits.
3116 $this->mOutput
->setFlag( 'vary-revision' );
3117 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
3118 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
3120 case 'revisionmonth1':
3121 # Let the edit saving system know we should parse the page
3122 # *after* a revision ID has been assigned. This is for null edits.
3123 $this->mOutput
->setFlag( 'vary-revision' );
3124 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
3125 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
3127 case 'revisionyear':
3128 # Let the edit saving system know we should parse the page
3129 # *after* a revision ID has been assigned. This is for null edits.
3130 $this->mOutput
->setFlag( 'vary-revision' );
3131 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
3132 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
3134 case 'revisiontimestamp':
3135 # Let the edit saving system know we should parse the page
3136 # *after* a revision ID has been assigned. This is for null edits.
3137 $this->mOutput
->setFlag( 'vary-revision' );
3138 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
3139 $value = $this->getRevisionTimestamp();
3141 case 'revisionuser':
3142 # Let the edit saving system know we should parse the page
3143 # *after* a revision ID has been assigned. This is for null edits.
3144 $this->mOutput
->setFlag( 'vary-revision' );
3145 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
3146 $value = $this->getRevisionUser();
3148 case 'revisionsize':
3149 # Let the edit saving system know we should parse the page
3150 # *after* a revision ID has been assigned. This is for null edits.
3151 $this->mOutput
->setFlag( 'vary-revision' );
3152 wfDebug( __METHOD__
. ": {{REVISIONSIZE}} used, setting vary-revision...\n" );
3153 $value = $this->getRevisionSize();
3156 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3159 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3161 case 'namespacenumber':
3162 $value = $this->mTitle
->getNamespace();
3165 $value = $this->mTitle
->canTalk()
3166 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
3170 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
3172 case 'subjectspace':
3173 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
3175 case 'subjectspacee':
3176 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
3178 case 'currentdayname':
3179 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
3182 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
3185 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
3188 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
3191 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3192 # int to remove the padding
3193 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
3196 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
3198 case 'localdayname':
3199 $value = $pageLang->getWeekdayName(
3200 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
3204 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
3207 $value = $pageLang->time(
3208 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
3214 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
3217 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3218 # int to remove the padding
3219 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
3222 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
3224 case 'numberofarticles':
3225 $value = $pageLang->formatNum( SiteStats
::articles() );
3227 case 'numberoffiles':
3228 $value = $pageLang->formatNum( SiteStats
::images() );
3230 case 'numberofusers':
3231 $value = $pageLang->formatNum( SiteStats
::users() );
3233 case 'numberofactiveusers':
3234 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
3236 case 'numberofpages':
3237 $value = $pageLang->formatNum( SiteStats
::pages() );
3239 case 'numberofadmins':
3240 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
3242 case 'numberofedits':
3243 $value = $pageLang->formatNum( SiteStats
::edits() );
3245 case 'currenttimestamp':
3246 $value = wfTimestamp( TS_MW
, $ts );
3248 case 'localtimestamp':
3249 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
3251 case 'currentversion':
3252 $value = SpecialVersion
::getVersion();
3255 return $wgArticlePath;
3261 return $wgServerName;
3263 return $wgScriptPath;
3265 return $wgStylePath;
3266 case 'directionmark':
3267 return $pageLang->getDirMark();
3268 case 'contentlanguage':
3269 global $wgLanguageCode;
3270 return $wgLanguageCode;
3271 case 'cascadingsources':
3272 $value = CoreParserFunctions
::cascadingsources( $this );
3277 'ParserGetVariableValueSwitch',
3278 array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame )
3285 $this->mVarCache
[$index] = $value;
3292 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3296 public function initialiseVariables() {
3297 wfProfileIn( __METHOD__
);
3298 $variableIDs = MagicWord
::getVariableIDs();
3299 $substIDs = MagicWord
::getSubstIDs();
3301 $this->mVariables
= new MagicWordArray( $variableIDs );
3302 $this->mSubstWords
= new MagicWordArray( $substIDs );
3303 wfProfileOut( __METHOD__
);
3307 * Preprocess some wikitext and return the document tree.
3308 * This is the ghost of replace_variables().
3310 * @param string $text The text to parse
3311 * @param int $flags Bitwise combination of:
3312 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
3313 * included. Default is to assume a direct page view.
3315 * The generated DOM tree must depend only on the input text and the flags.
3316 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3318 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3319 * change in the DOM tree for a given text, must be passed through the section identifier
3320 * in the section edit link and thus back to extractSections().
3322 * The output of this function is currently only cached in process memory, but a persistent
3323 * cache may be implemented at a later date which takes further advantage of these strict
3324 * dependency requirements.
3328 public function preprocessToDom( $text, $flags = 0 ) {
3329 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3334 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3340 public static function splitWhitespace( $s ) {
3341 $ltrimmed = ltrim( $s );
3342 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3343 $trimmed = rtrim( $ltrimmed );
3344 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3346 $w2 = substr( $ltrimmed, -$diff );
3350 return array( $w1, $trimmed, $w2 );
3354 * Replace magic variables, templates, and template arguments
3355 * with the appropriate text. Templates are substituted recursively,
3356 * taking care to avoid infinite loops.
3358 * Note that the substitution depends on value of $mOutputType:
3359 * self::OT_WIKI: only {{subst:}} templates
3360 * self::OT_PREPROCESS: templates but not extension tags
3361 * self::OT_HTML: all templates and extension tags
3363 * @param string $text The text to transform
3364 * @param bool|PPFrame $frame Object describing the arguments passed to the
3365 * template. Arguments may also be provided as an associative array, as
3366 * was the usual case before MW1.12. Providing arguments this way may be
3367 * useful for extensions wishing to perform variable replacement
3369 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3370 * double-brace expansion.
3373 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3374 # Is there any text? Also, Prevent too big inclusions!
3375 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3378 wfProfileIn( __METHOD__
);
3380 if ( $frame === false ) {
3381 $frame = $this->getPreprocessor()->newFrame();
3382 } elseif ( !( $frame instanceof PPFrame
) ) {
3383 wfDebug( __METHOD__
. " called using plain parameters instead of "
3384 . "a PPFrame instance. Creating custom frame.\n" );
3385 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3388 $dom = $this->preprocessToDom( $text );
3389 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3390 $text = $frame->expand( $dom, $flags );
3392 wfProfileOut( __METHOD__
);
3397 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3399 * @param array $args
3403 public static function createAssocArgs( $args ) {
3404 $assocArgs = array();
3406 foreach ( $args as $arg ) {
3407 $eqpos = strpos( $arg, '=' );
3408 if ( $eqpos === false ) {
3409 $assocArgs[$index++
] = $arg;
3411 $name = trim( substr( $arg, 0, $eqpos ) );
3412 $value = trim( substr( $arg, $eqpos +
1 ) );
3413 if ( $value === false ) {
3416 if ( $name !== false ) {
3417 $assocArgs[$name] = $value;
3426 * Warn the user when a parser limitation is reached
3427 * Will warn at most once the user per limitation type
3429 * @param string $limitationType Should be one of:
3430 * 'expensive-parserfunction' (corresponding messages:
3431 * 'expensive-parserfunction-warning',
3432 * 'expensive-parserfunction-category')
3433 * 'post-expand-template-argument' (corresponding messages:
3434 * 'post-expand-template-argument-warning',
3435 * 'post-expand-template-argument-category')
3436 * 'post-expand-template-inclusion' (corresponding messages:
3437 * 'post-expand-template-inclusion-warning',
3438 * 'post-expand-template-inclusion-category')
3439 * 'node-count-exceeded' (corresponding messages:
3440 * 'node-count-exceeded-warning',
3441 * 'node-count-exceeded-category')
3442 * 'expansion-depth-exceeded' (corresponding messages:
3443 * 'expansion-depth-exceeded-warning',
3444 * 'expansion-depth-exceeded-category')
3445 * @param string|int|null $current Current value
3446 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3447 * exceeded, provide the values (optional)
3449 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3450 # does no harm if $current and $max are present but are unnecessary for the message
3451 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3452 ->inLanguage( $this->mOptions
->getUserLangObj() )->text();
3453 $this->mOutput
->addWarning( $warning );
3454 $this->addTrackingCategory( "$limitationType-category" );
3458 * Return the text of a template, after recursively
3459 * replacing any variables or templates within the template.
3461 * @param array $piece The parts of the template
3462 * $piece['title']: the title, i.e. the part before the |
3463 * $piece['parts']: the parameter array
3464 * $piece['lineStart']: whether the brace was at the start of a line
3465 * @param PPFrame $frame The current frame, contains template arguments
3467 * @return string The text of the template
3469 public function braceSubstitution( $piece, $frame ) {
3470 wfProfileIn( __METHOD__
);
3471 wfProfileIn( __METHOD__
. '-setup' );
3475 // $text has been filled
3477 // wiki markup in $text should be escaped
3479 // $text is HTML, armour it against wikitext transformation
3481 // Force interwiki transclusion to be done in raw mode not rendered
3482 $forceRawInterwiki = false;
3483 // $text is a DOM node needing expansion in a child frame
3484 $isChildObj = false;
3485 // $text is a DOM node needing expansion in the current frame
3486 $isLocalObj = false;
3488 # Title object, where $text came from
3491 # $part1 is the bit before the first |, and must contain only title characters.
3492 # Various prefixes will be stripped from it later.
3493 $titleWithSpaces = $frame->expand( $piece['title'] );
3494 $part1 = trim( $titleWithSpaces );
3497 # Original title text preserved for various purposes
3498 $originalTitle = $part1;
3500 # $args is a list of argument nodes, starting from index 0, not including $part1
3501 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3502 # below won't work b/c this $args isn't an object
3503 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3504 wfProfileOut( __METHOD__
. '-setup' );
3506 $profileSection = null; // profile templates
3509 wfProfileIn( __METHOD__
. '-modifiers' );
3512 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3514 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3515 # Decide whether to expand template or keep wikitext as-is.
3516 if ( $this->ot
['wiki'] ) {
3517 if ( $substMatch === false ) {
3518 $literal = true; # literal when in PST with no prefix
3520 $literal = false; # expand when in PST with subst: or safesubst:
3523 if ( $substMatch == 'subst' ) {
3524 $literal = true; # literal when not in PST with plain subst:
3526 $literal = false; # expand when not in PST with safesubst: or no prefix
3530 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3537 if ( !$found && $args->getLength() == 0 ) {
3538 $id = $this->mVariables
->matchStartToEnd( $part1 );
3539 if ( $id !== false ) {
3540 $text = $this->getVariableValue( $id, $frame );
3541 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3542 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3548 # MSG, MSGNW and RAW
3551 $mwMsgnw = MagicWord
::get( 'msgnw' );
3552 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3555 # Remove obsolete MSG:
3556 $mwMsg = MagicWord
::get( 'msg' );
3557 $mwMsg->matchStartAndRemove( $part1 );
3561 $mwRaw = MagicWord
::get( 'raw' );
3562 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3563 $forceRawInterwiki = true;
3566 wfProfileOut( __METHOD__
. '-modifiers' );
3570 wfProfileIn( __METHOD__
. '-pfunc' );
3572 $colonPos = strpos( $part1, ':' );
3573 if ( $colonPos !== false ) {
3574 $func = substr( $part1, 0, $colonPos );
3575 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3576 for ( $i = 0; $i < $args->getLength(); $i++
) {
3577 $funcArgs[] = $args->item( $i );
3580 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3581 } catch ( Exception
$ex ) {
3582 wfProfileOut( __METHOD__
. '-pfunc' );
3583 wfProfileOut( __METHOD__
);
3587 # The interface for parser functions allows for extracting
3588 # flags into the local scope. Extract any forwarded flags
3592 wfProfileOut( __METHOD__
. '-pfunc' );
3595 # Finish mangling title and then check for loops.
3596 # Set $title to a Title object and $titleText to the PDBK
3599 # Split the title into page and subpage
3601 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3602 if ( $part1 !== $relative ) {
3604 $ns = $this->mTitle
->getNamespace();
3606 $title = Title
::newFromText( $part1, $ns );
3608 $titleText = $title->getPrefixedText();
3609 # Check for language variants if the template is not found
3610 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3611 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3613 # Do recursion depth check
3614 $limit = $this->mOptions
->getMaxTemplateDepth();
3615 if ( $frame->depth
>= $limit ) {
3617 $text = '<span class="error">'
3618 . wfMessage( 'parser-template-recursion-depth-warning' )
3619 ->numParams( $limit )->inContentLanguage()->text()
3625 # Load from database
3626 if ( !$found && $title ) {
3627 $profileSection = $this->mProfiler
->scopedProfileIn( $title->getPrefixedDBkey() );
3628 wfProfileIn( __METHOD__
. '-loadtpl' );
3629 if ( !$title->isExternal() ) {
3630 if ( $title->isSpecialPage()
3631 && $this->mOptions
->getAllowSpecialInclusion()
3632 && $this->ot
['html']
3634 // Pass the template arguments as URL parameters.
3635 // "uselang" will have no effect since the Language object
3636 // is forced to the one defined in ParserOptions.
3637 $pageArgs = array();
3638 $argsLength = $args->getLength();
3639 for ( $i = 0; $i < $argsLength; $i++
) {
3640 $bits = $args->item( $i )->splitArg();
3641 if ( strval( $bits['index'] ) === '' ) {
3642 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3643 $value = trim( $frame->expand( $bits['value'] ) );
3644 $pageArgs[$name] = $value;
3648 // Create a new context to execute the special page
3649 $context = new RequestContext
;
3650 $context->setTitle( $title );
3651 $context->setRequest( new FauxRequest( $pageArgs ) );
3652 $context->setUser( $this->getUser() );
3653 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3654 $ret = SpecialPageFactory
::capturePath( $title, $context );
3656 $text = $context->getOutput()->getHTML();
3657 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3660 $this->disableCache();
3662 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3663 $found = false; # access denied
3664 wfDebug( __METHOD__
. ": template inclusion denied for " .
3665 $title->getPrefixedDBkey() . "\n" );
3667 list( $text, $title ) = $this->getTemplateDom( $title );
3668 if ( $text !== false ) {
3674 # If the title is valid but undisplayable, make a link to it
3675 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3676 $text = "[[:$titleText]]";
3679 } elseif ( $title->isTrans() ) {
3680 # Interwiki transclusion
3681 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3682 $text = $this->interwikiTransclude( $title, 'render' );
3685 $text = $this->interwikiTransclude( $title, 'raw' );
3686 # Preprocess it like a template
3687 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3693 # Do infinite loop check
3694 # This has to be done after redirect resolution to avoid infinite loops via redirects
3695 if ( !$frame->loopCheck( $title ) ) {
3697 $text = '<span class="error">'
3698 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3700 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3702 wfProfileOut( __METHOD__
. '-loadtpl' );
3705 # If we haven't found text to substitute by now, we're done
3706 # Recover the source wikitext and return it
3708 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3709 if ( $profileSection ) {
3710 $this->mProfiler
->scopedProfileOut( $profileSection );
3712 wfProfileOut( __METHOD__
);
3713 return array( 'object' => $text );
3716 # Expand DOM-style return values in a child frame
3717 if ( $isChildObj ) {
3718 # Clean up argument array
3719 $newFrame = $frame->newChild( $args, $title );
3722 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3723 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3724 # Expansion is eligible for the empty-frame cache
3725 $text = $newFrame->cachedExpand( $titleText, $text );
3727 # Uncached expansion
3728 $text = $newFrame->expand( $text );
3731 if ( $isLocalObj && $nowiki ) {
3732 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3733 $isLocalObj = false;
3736 if ( $profileSection ) {
3737 $this->mProfiler
->scopedProfileOut( $profileSection );
3740 # Replace raw HTML by a placeholder
3742 $text = $this->insertStripItem( $text );
3743 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3744 # Escape nowiki-style return values
3745 $text = wfEscapeWikiText( $text );
3746 } elseif ( is_string( $text )
3747 && !$piece['lineStart']
3748 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3750 # Bug 529: if the template begins with a table or block-level
3751 # element, it should be treated as beginning a new line.
3752 # This behavior is somewhat controversial.
3753 $text = "\n" . $text;
3756 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3757 # Error, oversize inclusion
3758 if ( $titleText !== false ) {
3759 # Make a working, properly escaped link if possible (bug 23588)
3760 $text = "[[:$titleText]]";
3762 # This will probably not be a working link, but at least it may
3763 # provide some hint of where the problem is
3764 preg_replace( '/^:/', '', $originalTitle );
3765 $text = "[[:$originalTitle]]";
3767 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3768 . 'post-expand include size too large -->' );
3769 $this->limitationWarn( 'post-expand-template-inclusion' );
3772 if ( $isLocalObj ) {
3773 $ret = array( 'object' => $text );
3775 $ret = array( 'text' => $text );
3778 wfProfileOut( __METHOD__
);
3783 * Call a parser function and return an array with text and flags.
3785 * The returned array will always contain a boolean 'found', indicating
3786 * whether the parser function was found or not. It may also contain the
3788 * text: string|object, resulting wikitext or PP DOM object
3789 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3790 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3791 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3792 * nowiki: bool, wiki markup in $text should be escaped
3795 * @param PPFrame $frame The current frame, contains template arguments
3796 * @param string $function Function name
3797 * @param array $args Arguments to the function
3798 * @throws MWException
3801 public function callParserFunction( $frame, $function, array $args = array() ) {
3804 wfProfileIn( __METHOD__
);
3806 # Case sensitive functions
3807 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3808 $function = $this->mFunctionSynonyms
[1][$function];
3810 # Case insensitive functions
3811 $function = $wgContLang->lc( $function );
3812 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3813 $function = $this->mFunctionSynonyms
[0][$function];
3815 wfProfileOut( __METHOD__
);
3816 return array( 'found' => false );
3820 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3821 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3823 # Workaround for PHP bug 35229 and similar
3824 if ( !is_callable( $callback ) ) {
3825 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3826 wfProfileOut( __METHOD__
);
3827 throw new MWException( "Tag hook for $function is not callable\n" );
3830 $allArgs = array( &$this );
3831 if ( $flags & self
::SFH_OBJECT_ARGS
) {
3832 # Convert arguments to PPNodes and collect for appending to $allArgs
3833 $funcArgs = array();
3834 foreach ( $args as $k => $v ) {
3835 if ( $v instanceof PPNode ||
$k === 0 ) {
3838 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( array( $k => $v ) )->item( 0 );
3842 # Add a frame parameter, and pass the arguments as an array
3843 $allArgs[] = $frame;
3844 $allArgs[] = $funcArgs;
3846 # Convert arguments to plain text and append to $allArgs
3847 foreach ( $args as $k => $v ) {
3848 if ( $v instanceof PPNode
) {
3849 $allArgs[] = trim( $frame->expand( $v ) );
3850 } elseif ( is_int( $k ) && $k >= 0 ) {
3851 $allArgs[] = trim( $v );
3853 $allArgs[] = trim( "$k=$v" );
3858 $result = call_user_func_array( $callback, $allArgs );
3860 # The interface for function hooks allows them to return a wikitext
3861 # string or an array containing the string and any flags. This mungs
3862 # things around to match what this method should return.
3863 if ( !is_array( $result ) ) {
3869 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3870 $result['text'] = $result[0];
3872 unset( $result[0] );
3879 $preprocessFlags = 0;
3880 if ( isset( $result['noparse'] ) ) {
3881 $noparse = $result['noparse'];
3883 if ( isset( $result['preprocessFlags'] ) ) {
3884 $preprocessFlags = $result['preprocessFlags'];
3888 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3889 $result['isChildObj'] = true;
3891 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3892 wfProfileOut( __METHOD__
);
3898 * Get the semi-parsed DOM representation of a template with a given title,
3899 * and its redirect destination title. Cached.
3901 * @param Title $title
3905 public function getTemplateDom( $title ) {
3906 $cacheTitle = $title;
3907 $titleText = $title->getPrefixedDBkey();
3909 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3910 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3911 $title = Title
::makeTitle( $ns, $dbk );
3912 $titleText = $title->getPrefixedDBkey();
3914 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3915 return array( $this->mTplDomCache
[$titleText], $title );
3918 # Cache miss, go to the database
3919 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3921 if ( $text === false ) {
3922 $this->mTplDomCache
[$titleText] = false;
3923 return array( false, $title );
3926 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3927 $this->mTplDomCache
[$titleText] = $dom;
3929 if ( !$title->equals( $cacheTitle ) ) {
3930 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3931 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3934 return array( $dom, $title );
3938 * Fetch the current revision of a given title. Note that the revision
3939 * (and even the title) may not exist in the database, so everything
3940 * contributing to the output of the parser should use this method
3941 * where possible, rather than getting the revisions themselves. This
3942 * method also caches its results, so using it benefits performance.
3945 * @param Title $title
3948 public function fetchCurrentRevisionOfTitle( $title ) {
3949 $cacheKey = $title->getPrefixedDBkey();
3950 if ( !$this->currentRevisionCache
) {
3951 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3953 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3954 $this->currentRevisionCache
->set( $cacheKey,
3955 // Defaults to Parser::statelessFetchRevision()
3956 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3959 return $this->currentRevisionCache
->get( $cacheKey );
3963 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3964 * without passing them on to it.
3967 * @param Title $title
3968 * @param Parser|bool $parser
3971 public static function statelessFetchRevision( $title, $parser = false ) {
3972 return Revision
::newFromTitle( $title );
3976 * Fetch the unparsed text of a template and register a reference to it.
3977 * @param Title $title
3978 * @return array ( string or false, Title )
3980 public function fetchTemplateAndTitle( $title ) {
3981 // Defaults to Parser::statelessFetchTemplate()
3982 $templateCb = $this->mOptions
->getTemplateCallback();
3983 $stuff = call_user_func( $templateCb, $title, $this );
3984 $text = $stuff['text'];
3985 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3986 if ( isset( $stuff['deps'] ) ) {
3987 foreach ( $stuff['deps'] as $dep ) {
3988 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3989 if ( $dep['title']->equals( $this->getTitle() ) ) {
3990 // If we transclude ourselves, the final result
3991 // will change based on the new version of the page
3992 $this->mOutput
->setFlag( 'vary-revision' );
3996 return array( $text, $finalTitle );
4000 * Fetch the unparsed text of a template and register a reference to it.
4001 * @param Title $title
4002 * @return string|bool
4004 public function fetchTemplate( $title ) {
4005 $rv = $this->fetchTemplateAndTitle( $title );
4010 * Static function to get a template
4011 * Can be overridden via ParserOptions::setTemplateCallback().
4013 * @param Title $title
4014 * @param bool|Parser $parser
4018 public static function statelessFetchTemplate( $title, $parser = false ) {
4019 $text = $skip = false;
4020 $finalTitle = $title;
4023 # Loop to fetch the article, with up to 1 redirect
4024 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
4025 # Give extensions a chance to select the revision instead
4026 $id = false; # Assume current
4027 Hooks
::run( 'BeforeParserFetchTemplateAndtitle',
4028 array( $parser, $title, &$skip, &$id ) );
4034 'page_id' => $title->getArticleID(),
4041 $rev = Revision
::newFromId( $id );
4042 } elseif ( $parser ) {
4043 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
4045 $rev = Revision
::newFromTitle( $title );
4047 $rev_id = $rev ?
$rev->getId() : 0;
4048 # If there is no current revision, there is no page
4049 if ( $id === false && !$rev ) {
4050 $linkCache = LinkCache
::singleton();
4051 $linkCache->addBadLinkObj( $title );
4056 'page_id' => $title->getArticleID(),
4057 'rev_id' => $rev_id );
4058 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
4059 # We fetched a rev from a different title; register it too...
4061 'title' => $rev->getTitle(),
4062 'page_id' => $rev->getPage(),
4063 'rev_id' => $rev_id );
4067 $content = $rev->getContent();
4068 $text = $content ?
$content->getWikitextForTransclusion() : null;
4070 if ( $text === false ||
$text === null ) {
4074 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
4076 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
4077 if ( !$message->exists() ) {
4081 $content = $message->content();
4082 $text = $message->plain();
4090 $finalTitle = $title;
4091 $title = $content->getRedirectTarget();
4095 'finalTitle' => $finalTitle,
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
4106 public function fetchFile( $title, $options = array() ) {
4107 $res = $this->fetchFileAndTitle( $title, $options );
4112 * Fetch a file and its title and register a reference to it.
4113 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4114 * @param Title $title
4115 * @param array $options Array of options to RepoGroup::findFile
4116 * @return array ( File or false, Title of file )
4118 public function fetchFileAndTitle( $title, $options = array() ) {
4119 $file = $this->fetchFileNoRegister( $title, $options );
4121 $time = $file ?
$file->getTimestamp() : false;
4122 $sha1 = $file ?
$file->getSha1() : false;
4123 # Register the file as a dependency...
4124 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4125 if ( $file && !$title->equals( $file->getTitle() ) ) {
4126 # Update fetched file title
4127 $title = $file->getTitle();
4128 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4130 return array( $file, $title );
4134 * Helper function for fetchFileAndTitle.
4136 * Also useful if you need to fetch a file but not use it yet,
4137 * for example to get the file's handler.
4139 * @param Title $title
4140 * @param array $options Array of options to RepoGroup::findFile
4143 protected function fetchFileNoRegister( $title, $options = array() ) {
4144 if ( isset( $options['broken'] ) ) {
4145 $file = false; // broken thumbnail forced by hook
4146 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
4147 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
4148 } else { // get by (name,timestamp)
4149 $file = wfFindFile( $title, $options );
4155 * Transclude an interwiki link.
4157 * @param Title $title
4158 * @param string $action
4162 public function interwikiTransclude( $title, $action ) {
4163 global $wgEnableScaryTranscluding;
4165 if ( !$wgEnableScaryTranscluding ) {
4166 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
4169 $url = $title->getFullURL( array( 'action' => $action ) );
4171 if ( strlen( $url ) > 255 ) {
4172 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
4174 return $this->fetchScaryTemplateMaybeFromCache( $url );
4178 * @param string $url
4179 * @return mixed|string
4181 public function fetchScaryTemplateMaybeFromCache( $url ) {
4182 global $wgTranscludeCacheExpiry;
4183 $dbr = wfGetDB( DB_SLAVE
);
4184 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
4185 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
4186 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
4188 return $obj->tc_contents
;
4191 $req = MWHttpRequest
::factory( $url );
4192 $status = $req->execute(); // Status object
4193 if ( $status->isOK() ) {
4194 $text = $req->getContent();
4195 } elseif ( $req->getStatus() != 200 ) {
4196 // Though we failed to fetch the content, this status is useless.
4197 return wfMessage( 'scarytranscludefailed-httpstatus' )
4198 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
4200 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
4203 $dbw = wfGetDB( DB_MASTER
);
4204 $dbw->replace( 'transcache', array( 'tc_url' ), array(
4206 'tc_time' => $dbw->timestamp( time() ),
4207 'tc_contents' => $text
4213 * Triple brace replacement -- used for template arguments
4216 * @param array $piece
4217 * @param PPFrame $frame
4221 public function argSubstitution( $piece, $frame ) {
4222 wfProfileIn( __METHOD__
);
4225 $parts = $piece['parts'];
4226 $nameWithSpaces = $frame->expand( $piece['title'] );
4227 $argName = trim( $nameWithSpaces );
4229 $text = $frame->getArgument( $argName );
4230 if ( $text === false && $parts->getLength() > 0
4231 && ( $this->ot
['html']
4233 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
4236 # No match in frame, use the supplied default
4237 $object = $parts->item( 0 )->getChildren();
4239 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
4240 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
4241 $this->limitationWarn( 'post-expand-template-argument' );
4244 if ( $text === false && $object === false ) {
4246 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
4248 if ( $error !== false ) {
4251 if ( $object !== false ) {
4252 $ret = array( 'object' => $object );
4254 $ret = array( 'text' => $text );
4257 wfProfileOut( __METHOD__
);
4262 * Return the text to be used for a given extension tag.
4263 * This is the ghost of strip().
4265 * @param array $params Associative array of parameters:
4266 * name PPNode for the tag name
4267 * attr PPNode for unparsed text where tag attributes are thought to be
4268 * attributes Optional associative array of parsed attributes
4269 * inner Contents of extension element
4270 * noClose Original text did not have a close tag
4271 * @param PPFrame $frame
4273 * @throws MWException
4276 public function extensionSubstitution( $params, $frame ) {
4277 $name = $frame->expand( $params['name'] );
4278 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
4279 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
4280 $marker = "{$this->mUniqPrefix}-$name-"
4281 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
4283 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
4284 ( $this->ot
['html'] ||
$this->ot
['pre'] );
4285 if ( $isFunctionTag ) {
4286 $markerType = 'none';
4288 $markerType = 'general';
4290 if ( $this->ot
['html'] ||
$isFunctionTag ) {
4291 $name = strtolower( $name );
4292 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
4293 if ( isset( $params['attributes'] ) ) {
4294 $attributes = $attributes +
$params['attributes'];
4297 if ( isset( $this->mTagHooks
[$name] ) ) {
4298 # Workaround for PHP bug 35229 and similar
4299 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
4300 throw new MWException( "Tag hook for $name is not callable\n" );
4302 $output = call_user_func_array( $this->mTagHooks
[$name],
4303 array( $content, $attributes, $this, $frame ) );
4304 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
4305 list( $callback, ) = $this->mFunctionTagHooks
[$name];
4306 if ( !is_callable( $callback ) ) {
4307 throw new MWException( "Tag hook for $name is not callable\n" );
4310 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
4312 $output = '<span class="error">Invalid tag extension name: ' .
4313 htmlspecialchars( $name ) . '</span>';
4316 if ( is_array( $output ) ) {
4317 # Extract flags to local scope (to override $markerType)
4319 $output = $flags[0];
4324 if ( is_null( $attrText ) ) {
4327 if ( isset( $params['attributes'] ) ) {
4328 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4329 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4330 htmlspecialchars( $attrValue ) . '"';
4333 if ( $content === null ) {
4334 $output = "<$name$attrText/>";
4336 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4337 $output = "<$name$attrText>$content$close";
4341 if ( $markerType === 'none' ) {
4343 } elseif ( $markerType === 'nowiki' ) {
4344 $this->mStripState
->addNoWiki( $marker, $output );
4345 } elseif ( $markerType === 'general' ) {
4346 $this->mStripState
->addGeneral( $marker, $output );
4348 throw new MWException( __METHOD__
. ': invalid marker type' );
4354 * Increment an include size counter
4356 * @param string $type The type of expansion
4357 * @param int $size The size of the text
4358 * @return bool False if this inclusion would take it over the maximum, true otherwise
4360 public function incrementIncludeSize( $type, $size ) {
4361 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4364 $this->mIncludeSizes
[$type] +
= $size;
4370 * Increment the expensive function count
4372 * @return bool False if the limit has been exceeded
4374 public function incrementExpensiveFunctionCount() {
4375 $this->mExpensiveFunctionCount++
;
4376 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4380 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4381 * Fills $this->mDoubleUnderscores, returns the modified text
4383 * @param string $text
4387 public function doDoubleUnderscore( $text ) {
4388 wfProfileIn( __METHOD__
);
4390 # The position of __TOC__ needs to be recorded
4391 $mw = MagicWord
::get( 'toc' );
4392 if ( $mw->match( $text ) ) {
4393 $this->mShowToc
= true;
4394 $this->mForceTocPosition
= true;
4396 # Set a placeholder. At the end we'll fill it in with the TOC.
4397 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4399 # Only keep the first one.
4400 $text = $mw->replace( '', $text );
4403 # Now match and remove the rest of them
4404 $mwa = MagicWord
::getDoubleUnderscoreArray();
4405 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4407 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4408 $this->mOutput
->mNoGallery
= true;
4410 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4411 $this->mShowToc
= false;
4413 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4414 && $this->mTitle
->getNamespace() == NS_CATEGORY
4416 $this->addTrackingCategory( 'hidden-category-category' );
4418 # (bug 8068) Allow control over whether robots index a page.
4420 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4421 # is not desirable, the last one on the page should win.
4422 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4423 $this->mOutput
->setIndexPolicy( 'noindex' );
4424 $this->addTrackingCategory( 'noindex-category' );
4426 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4427 $this->mOutput
->setIndexPolicy( 'index' );
4428 $this->addTrackingCategory( 'index-category' );
4431 # Cache all double underscores in the database
4432 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4433 $this->mOutput
->setProperty( $key, '' );
4436 wfProfileOut( __METHOD__
);
4441 * @see ParserOutput::addTrackingCategory()
4442 * @param string $msg Message key
4443 * @return bool Whether the addition was successful
4445 public function addTrackingCategory( $msg ) {
4446 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4450 * This function accomplishes several tasks:
4451 * 1) Auto-number headings if that option is enabled
4452 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4453 * 3) Add a Table of contents on the top for users who have enabled the option
4454 * 4) Auto-anchor headings
4456 * It loops through all headlines, collects the necessary data, then splits up the
4457 * string and re-inserts the newly formatted headlines.
4459 * @param string $text
4460 * @param string $origText Original, untouched wikitext
4461 * @param bool $isMain
4462 * @return mixed|string
4465 public function formatHeadings( $text, $origText, $isMain = true ) {
4466 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4468 # Inhibit editsection links if requested in the page
4469 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4470 $maybeShowEditLink = $showEditLink = false;
4472 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4473 $showEditLink = $this->mOptions
->getEditSection();
4475 if ( $showEditLink ) {
4476 $this->mOutput
->setEditSectionTokens( true );
4479 # Get all headlines for numbering them and adding funky stuff like [edit]
4480 # links - this is for later, but we need the number of headlines right now
4482 $numMatches = preg_match_all(
4483 '/<H(?P<level>[1-6])(?P<attrib>.*?' . '>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i',
4488 # if there are fewer than 4 headlines in the article, do not show TOC
4489 # unless it's been explicitly enabled.
4490 $enoughToc = $this->mShowToc
&&
4491 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4493 # Allow user to stipulate that a page should have a "new section"
4494 # link added via __NEWSECTIONLINK__
4495 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4496 $this->mOutput
->setNewSection( true );
4499 # Allow user to remove the "new section"
4500 # link via __NONEWSECTIONLINK__
4501 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4502 $this->mOutput
->hideNewSection( true );
4505 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4506 # override above conditions and always show TOC above first header
4507 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4508 $this->mShowToc
= true;
4516 # Ugh .. the TOC should have neat indentation levels which can be
4517 # passed to the skin functions. These are determined here
4521 $sublevelCount = array();
4522 $levelCount = array();
4527 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4528 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4529 $oldType = $this->mOutputType
;
4530 $this->setOutputType( self
::OT_WIKI
);
4531 $frame = $this->getPreprocessor()->newFrame();
4532 $root = $this->preprocessToDom( $origText );
4533 $node = $root->getFirstChild();
4538 foreach ( $matches[3] as $headline ) {
4539 $isTemplate = false;
4541 $sectionIndex = false;
4543 $markerMatches = array();
4544 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4545 $serial = $markerMatches[1];
4546 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4547 $isTemplate = ( $titleText != $baseTitleText );
4548 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4552 $prevlevel = $level;
4554 $level = $matches[1][$headlineCount];
4556 if ( $level > $prevlevel ) {
4557 # Increase TOC level
4559 $sublevelCount[$toclevel] = 0;
4560 if ( $toclevel < $wgMaxTocLevel ) {
4561 $prevtoclevel = $toclevel;
4562 $toc .= Linker
::tocIndent();
4565 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4566 # Decrease TOC level, find level to jump to
4568 for ( $i = $toclevel; $i > 0; $i-- ) {
4569 if ( $levelCount[$i] == $level ) {
4570 # Found last matching level
4573 } elseif ( $levelCount[$i] < $level ) {
4574 # Found first matching level below current level
4582 if ( $toclevel < $wgMaxTocLevel ) {
4583 if ( $prevtoclevel < $wgMaxTocLevel ) {
4584 # Unindent only if the previous toc level was shown :p
4585 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4586 $prevtoclevel = $toclevel;
4588 $toc .= Linker
::tocLineEnd();
4592 # No change in level, end TOC line
4593 if ( $toclevel < $wgMaxTocLevel ) {
4594 $toc .= Linker
::tocLineEnd();
4598 $levelCount[$toclevel] = $level;
4600 # count number of headlines for each level
4601 $sublevelCount[$toclevel]++
;
4603 for ( $i = 1; $i <= $toclevel; $i++
) {
4604 if ( !empty( $sublevelCount[$i] ) ) {
4608 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4613 # The safe header is a version of the header text safe to use for links
4615 # Remove link placeholders by the link text.
4616 # <!--LINK number-->
4618 # link text with suffix
4619 # Do this before unstrip since link text can contain strip markers
4620 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4622 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4623 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4625 # Strip out HTML (first regex removes any tag not allowed)
4627 # * <sup> and <sub> (bug 8393)
4630 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4632 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4633 # to allow setting directionality in toc items.
4634 $tocline = preg_replace(
4636 '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?' . '>#',
4637 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?' . '>#'
4639 array( '', '<$1>' ),
4642 $tocline = trim( $tocline );
4644 # For the anchor, strip out HTML-y stuff period
4645 $safeHeadline = preg_replace( '/<.*?' . '>/', '', $safeHeadline );
4646 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4648 # Save headline for section edit hint before it's escaped
4649 $headlineHint = $safeHeadline;
4651 if ( $wgExperimentalHtmlIds ) {
4652 # For reverse compatibility, provide an id that's
4653 # HTML4-compatible, like we used to.
4655 # It may be worth noting, academically, that it's possible for
4656 # the legacy anchor to conflict with a non-legacy headline
4657 # anchor on the page. In this case likely the "correct" thing
4658 # would be to either drop the legacy anchors or make sure
4659 # they're numbered first. However, this would require people
4660 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4661 # manually, so let's not bother worrying about it.
4662 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4663 array( 'noninitial', 'legacy' ) );
4664 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4666 if ( $legacyHeadline == $safeHeadline ) {
4667 # No reason to have both (in fact, we can't)
4668 $legacyHeadline = false;
4671 $legacyHeadline = false;
4672 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4676 # HTML names must be case-insensitively unique (bug 10721).
4677 # This does not apply to Unicode characters per
4678 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4679 # @todo FIXME: We may be changing them depending on the current locale.
4680 $arrayKey = strtolower( $safeHeadline );
4681 if ( $legacyHeadline === false ) {
4682 $legacyArrayKey = false;
4684 $legacyArrayKey = strtolower( $legacyHeadline );
4687 # count how many in assoc. array so we can track dupes in anchors
4688 if ( isset( $refers[$arrayKey] ) ) {
4689 $refers[$arrayKey]++
;
4691 $refers[$arrayKey] = 1;
4693 if ( isset( $refers[$legacyArrayKey] ) ) {
4694 $refers[$legacyArrayKey]++
;
4696 $refers[$legacyArrayKey] = 1;
4699 # Don't number the heading if it is the only one (looks silly)
4700 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4701 # the two are different if the line contains a link
4702 $headline = Html
::element(
4704 array( 'class' => 'mw-headline-number' ),
4706 ) . ' ' . $headline;
4709 # Create the anchor for linking from the TOC to the section
4710 $anchor = $safeHeadline;
4711 $legacyAnchor = $legacyHeadline;
4712 if ( $refers[$arrayKey] > 1 ) {
4713 $anchor .= '_' . $refers[$arrayKey];
4715 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4716 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4718 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4719 $toc .= Linker
::tocLine( $anchor, $tocline,
4720 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4723 # Add the section to the section tree
4724 # Find the DOM node for this header
4725 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4726 while ( $node && !$noOffset ) {
4727 if ( $node->getName() === 'h' ) {
4728 $bits = $node->splitHeading();
4729 if ( $bits['i'] == $sectionIndex ) {
4733 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4734 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4735 $node = $node->getNextSibling();
4738 'toclevel' => $toclevel,
4741 'number' => $numbering,
4742 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4743 'fromtitle' => $titleText,
4744 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4745 'anchor' => $anchor,
4748 # give headline the correct <h#> tag
4749 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4750 // Output edit section links as markers with styles that can be customized by skins
4751 if ( $isTemplate ) {
4752 # Put a T flag in the section identifier, to indicate to extractSections()
4753 # that sections inside <includeonly> should be counted.
4754 $editsectionPage = $titleText;
4755 $editsectionSection = "T-$sectionIndex";
4756 $editsectionContent = null;
4758 $editsectionPage = $this->mTitle
->getPrefixedText();
4759 $editsectionSection = $sectionIndex;
4760 $editsectionContent = $headlineHint;
4762 // We use a bit of pesudo-xml for editsection markers. The
4763 // language converter is run later on. Using a UNIQ style marker
4764 // leads to the converter screwing up the tokens when it
4765 // converts stuff. And trying to insert strip tags fails too. At
4766 // this point all real inputted tags have already been escaped,
4767 // so we don't have to worry about a user trying to input one of
4768 // these markers directly. We use a page and section attribute
4769 // to stop the language converter from converting these
4770 // important bits of data, but put the headline hint inside a
4771 // content block because the language converter is supposed to
4772 // be able to convert that piece of data.
4773 // Gets replaced with html in ParserOutput::getText
4774 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4775 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4776 if ( $editsectionContent !== null ) {
4777 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4784 $head[$headlineCount] = Linker
::makeHeadline( $level,
4785 $matches['attrib'][$headlineCount], $anchor, $headline,
4786 $editlink, $legacyAnchor );
4791 $this->setOutputType( $oldType );
4793 # Never ever show TOC if no headers
4794 if ( $numVisible < 1 ) {
4799 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4800 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4802 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4803 $this->mOutput
->setTOCHTML( $toc );
4804 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4805 $this->mOutput
->addModules( 'mediawiki.toc' );
4809 $this->mOutput
->setSections( $tocraw );
4812 # split up and insert constructed headlines
4813 $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text );
4816 // build an array of document sections
4817 $sections = array();
4818 foreach ( $blocks as $block ) {
4819 // $head is zero-based, sections aren't.
4820 if ( empty( $head[$i - 1] ) ) {
4821 $sections[$i] = $block;
4823 $sections[$i] = $head[$i - 1] . $block;
4827 * Send a hook, one per section.
4828 * The idea here is to be able to make section-level DIVs, but to do so in a
4829 * lower-impact, more correct way than r50769
4832 * $section : the section number
4833 * &$sectionContent : ref to the content of the section
4834 * $showEditLinks : boolean describing whether this section has an edit link
4836 Hooks
::run( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4841 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4842 // append the TOC at the beginning
4843 // Top anchor now in skin
4844 $sections[0] = $sections[0] . $toc . "\n";
4847 $full .= join( '', $sections );
4849 if ( $this->mForceTocPosition
) {
4850 return str_replace( '<!--MWTOC-->', $toc, $full );
4857 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4858 * conversion, substituting signatures, {{subst:}} templates, etc.
4860 * @param string $text The text to transform
4861 * @param Title $title The Title object for the current article
4862 * @param User $user The User object describing the current user
4863 * @param ParserOptions $options Parsing options
4864 * @param bool $clearState Whether to clear the parser state first
4865 * @return string The altered wiki markup
4867 public function preSaveTransform( $text, Title
$title, User
$user,
4868 ParserOptions
$options, $clearState = true
4870 if ( $clearState ) {
4871 $magicScopeVariable = $this->lock();
4873 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4874 $this->setUser( $user );
4880 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4881 if ( $options->getPreSaveTransform() ) {
4882 $text = $this->pstPass2( $text, $user );
4884 $text = $this->mStripState
->unstripBoth( $text );
4886 $this->setUser( null ); #Reset
4892 * Pre-save transform helper function
4894 * @param string $text
4899 private function pstPass2( $text, $user ) {
4902 # Note: This is the timestamp saved as hardcoded wikitext to
4903 # the database, we use $wgContLang here in order to give
4904 # everyone the same signature and use the default one rather
4905 # than the one selected in each user's preferences.
4906 # (see also bug 12815)
4907 $ts = $this->mOptions
->getTimestamp();
4908 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4909 $ts = $timestamp->format( 'YmdHis' );
4910 $tzMsg = $timestamp->format( 'T' ); # might vary on DST changeover!
4912 # Allow translation of timezones through wiki. format() can return
4913 # whatever crap the system uses, localised or not, so we cannot
4914 # ship premade translations.
4915 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4916 $msg = wfMessage( $key )->inContentLanguage();
4917 if ( $msg->exists() ) {
4918 $tzMsg = $msg->text();
4921 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4923 # Variable replacement
4924 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4925 $text = $this->replaceVariables( $text );
4927 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4928 # which may corrupt this parser instance via its wfMessage()->text() call-
4931 $sigText = $this->getUserSig( $user );
4932 $text = strtr( $text, array(
4934 '~~~~' => "$sigText $d",
4938 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4939 $tc = '[' . Title
::legalChars() . ']';
4940 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4942 // [[ns:page (context)|]]
4943 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4944 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4945 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4946 // [[ns:page (context), context|]] (using either single or double-width comma)
4947 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4948 // [[|page]] (reverse pipe trick: add context from page title)
4949 $p2 = "/\[\[\\|($tc+)]]/";
4951 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4952 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4953 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4954 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4956 $t = $this->mTitle
->getText();
4958 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4959 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4960 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4961 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4963 # if there's no context, don't bother duplicating the title
4964 $text = preg_replace( $p2, '[[\\1]]', $text );
4967 # Trim trailing whitespace
4968 $text = rtrim( $text );
4974 * Fetch the user's signature text, if any, and normalize to
4975 * validated, ready-to-insert wikitext.
4976 * If you have pre-fetched the nickname or the fancySig option, you can
4977 * specify them here to save a database query.
4978 * Do not reuse this parser instance after calling getUserSig(),
4979 * as it may have changed if it's the $wgParser.
4982 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4983 * @param bool|null $fancySig whether the nicknname is the complete signature
4984 * or null to use default value
4987 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4988 global $wgMaxSigChars;
4990 $username = $user->getName();
4992 # If not given, retrieve from the user object.
4993 if ( $nickname === false ) {
4994 $nickname = $user->getOption( 'nickname' );
4997 if ( is_null( $fancySig ) ) {
4998 $fancySig = $user->getBoolOption( 'fancysig' );
5001 $nickname = $nickname == null ?
$username : $nickname;
5003 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
5004 $nickname = $username;
5005 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
5006 } elseif ( $fancySig !== false ) {
5007 # Sig. might contain markup; validate this
5008 if ( $this->validateSig( $nickname ) !== false ) {
5009 # Validated; clean up (if needed) and return it
5010 return $this->cleanSig( $nickname, true );
5012 # Failed to validate; fall back to the default
5013 $nickname = $username;
5014 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
5018 # Make sure nickname doesnt get a sig in a sig
5019 $nickname = self
::cleanSigInSig( $nickname );
5021 # If we're still here, make it a link to the user page
5022 $userText = wfEscapeWikiText( $username );
5023 $nickText = wfEscapeWikiText( $nickname );
5024 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
5026 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
5027 ->title( $this->getTitle() )->text();
5031 * Check that the user's signature contains no bad XML
5033 * @param string $text
5034 * @return string|bool An expanded string, or false if invalid.
5036 public function validateSig( $text ) {
5037 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
5041 * Clean up signature text
5043 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
5044 * 2) Substitute all transclusions
5046 * @param string $text
5047 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
5048 * @return string Signature text
5050 public function cleanSig( $text, $parsing = false ) {
5053 $magicScopeVariable = $this->lock();
5054 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
5057 # Option to disable this feature
5058 if ( !$this->mOptions
->getCleanSignatures() ) {
5062 # @todo FIXME: Regex doesn't respect extension tags or nowiki
5063 # => Move this logic to braceSubstitution()
5064 $substWord = MagicWord
::get( 'subst' );
5065 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
5066 $substText = '{{' . $substWord->getSynonym( 0 );
5068 $text = preg_replace( $substRegex, $substText, $text );
5069 $text = self
::cleanSigInSig( $text );
5070 $dom = $this->preprocessToDom( $text );
5071 $frame = $this->getPreprocessor()->newFrame();
5072 $text = $frame->expand( $dom );
5075 $text = $this->mStripState
->unstripBoth( $text );
5082 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
5084 * @param string $text
5085 * @return string Signature text with /~{3,5}/ removed
5087 public static function cleanSigInSig( $text ) {
5088 $text = preg_replace( '/~{3,5}/', '', $text );
5093 * Set up some variables which are usually set up in parse()
5094 * so that an external function can call some class members with confidence
5096 * @param Title|null $title
5097 * @param ParserOptions $options
5098 * @param int $outputType
5099 * @param bool $clearState
5101 public function startExternalParse( Title
$title = null, ParserOptions
$options,
5102 $outputType, $clearState = true
5104 $this->startParse( $title, $options, $outputType, $clearState );
5108 * @param Title|null $title
5109 * @param ParserOptions $options
5110 * @param int $outputType
5111 * @param bool $clearState
5113 private function startParse( Title
$title = null, ParserOptions
$options,
5114 $outputType, $clearState = true
5116 $this->setTitle( $title );
5117 $this->mOptions
= $options;
5118 $this->setOutputType( $outputType );
5119 if ( $clearState ) {
5120 $this->clearState();
5125 * Wrapper for preprocess()
5127 * @param string $text The text to preprocess
5128 * @param ParserOptions $options Options
5129 * @param Title|null $title Title object or null to use $wgTitle
5132 public function transformMsg( $text, $options, $title = null ) {
5133 static $executing = false;
5135 # Guard against infinite recursion
5141 wfProfileIn( __METHOD__
);
5147 $text = $this->preprocess( $text, $title, $options );
5150 wfProfileOut( __METHOD__
);
5155 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
5156 * The callback should have the following form:
5157 * function myParserHook( $text, $params, $parser, $frame ) { ... }
5159 * Transform and return $text. Use $parser for any required context, e.g. use
5160 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
5162 * Hooks may return extended information by returning an array, of which the
5163 * first numbered element (index 0) must be the return string, and all other
5164 * entries are extracted into local variables within an internal function
5165 * in the Parser class.
5167 * This interface (introduced r61913) appears to be undocumented, but
5168 * 'markerName' is used by some core tag hooks to override which strip
5169 * array their results are placed in. **Use great caution if attempting
5170 * this interface, as it is not documented and injudicious use could smash
5171 * private variables.**
5173 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5174 * @param callable $callback The callback function (and object) to use for the tag
5175 * @throws MWException
5176 * @return callable|null The old value of the mTagHooks array associated with the hook
5178 public function setHook( $tag, $callback ) {
5179 $tag = strtolower( $tag );
5180 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5181 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
5183 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
5184 $this->mTagHooks
[$tag] = $callback;
5185 if ( !in_array( $tag, $this->mStripList
) ) {
5186 $this->mStripList
[] = $tag;
5193 * As setHook(), but letting the contents be parsed.
5195 * Transparent tag hooks are like regular XML-style tag hooks, except they
5196 * operate late in the transformation sequence, on HTML instead of wikitext.
5198 * This is probably obsoleted by things dealing with parser frames?
5199 * The only extension currently using it is geoserver.
5202 * @todo better document or deprecate this
5204 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5205 * @param callable $callback The callback function (and object) to use for the tag
5206 * @throws MWException
5207 * @return callable|null The old value of the mTagHooks array associated with the hook
5209 public function setTransparentTagHook( $tag, $callback ) {
5210 $tag = strtolower( $tag );
5211 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5212 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
5214 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
5215 $this->mTransparentTagHooks
[$tag] = $callback;
5221 * Remove all tag hooks
5223 public function clearTagHooks() {
5224 $this->mTagHooks
= array();
5225 $this->mFunctionTagHooks
= array();
5226 $this->mStripList
= $this->mDefaultStripList
;
5230 * Create a function, e.g. {{sum:1|2|3}}
5231 * The callback function should have the form:
5232 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
5234 * Or with Parser::SFH_OBJECT_ARGS:
5235 * function myParserFunction( $parser, $frame, $args ) { ... }
5237 * The callback may either return the text result of the function, or an array with the text
5238 * in element 0, and a number of flags in the other elements. The names of the flags are
5239 * specified in the keys. Valid flags are:
5240 * found The text returned is valid, stop processing the template. This
5242 * nowiki Wiki markup in the return value should be escaped
5243 * isHTML The returned text is HTML, armour it against wikitext transformation
5245 * @param string $id The magic word ID
5246 * @param callable $callback The callback function (and object) to use
5247 * @param int $flags A combination of the following flags:
5248 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
5250 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
5251 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
5252 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
5253 * the arguments, and to control the way they are expanded.
5255 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
5256 * arguments, for instance:
5257 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
5259 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
5260 * future versions. Please call $frame->expand() on it anyway so that your code keeps
5261 * working if/when this is changed.
5263 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
5266 * Please read the documentation in includes/parser/Preprocessor.php for more information
5267 * about the methods available in PPFrame and PPNode.
5269 * @throws MWException
5270 * @return string|callable The old callback function for this name, if any
5272 public function setFunctionHook( $id, $callback, $flags = 0 ) {
5275 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
5276 $this->mFunctionHooks
[$id] = array( $callback, $flags );
5278 # Add to function cache
5279 $mw = MagicWord
::get( $id );
5281 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
5284 $synonyms = $mw->getSynonyms();
5285 $sensitive = intval( $mw->isCaseSensitive() );
5287 foreach ( $synonyms as $syn ) {
5289 if ( !$sensitive ) {
5290 $syn = $wgContLang->lc( $syn );
5293 if ( !( $flags & self
::SFH_NO_HASH
) ) {
5296 # Remove trailing colon
5297 if ( substr( $syn, -1, 1 ) === ':' ) {
5298 $syn = substr( $syn, 0, -1 );
5300 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
5306 * Get all registered function hook identifiers
5310 public function getFunctionHooks() {
5311 return array_keys( $this->mFunctionHooks
);
5315 * Create a tag function, e.g. "<test>some stuff</test>".
5316 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5317 * Unlike parser functions, their content is not preprocessed.
5318 * @param string $tag
5319 * @param callable $callback
5321 * @throws MWException
5324 public function setFunctionTagHook( $tag, $callback, $flags ) {
5325 $tag = strtolower( $tag );
5326 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5327 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5329 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
5330 $this->mFunctionTagHooks
[$tag] : null;
5331 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
5333 if ( !in_array( $tag, $this->mStripList
) ) {
5334 $this->mStripList
[] = $tag;
5341 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
5342 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5343 * Placeholders created in Skin::makeLinkObj()
5345 * @param string $text
5346 * @param int $options
5348 public function replaceLinkHolders( &$text, $options = 0 ) {
5349 $this->mLinkHolders
->replace( $text );
5353 * Replace "<!--LINK-->" link placeholders with plain text of links
5354 * (not HTML-formatted).
5356 * @param string $text
5359 public function replaceLinkHoldersText( $text ) {
5360 return $this->mLinkHolders
->replaceText( $text );
5364 * Renders an image gallery from a text with one line per image.
5365 * text labels may be given by using |-style alternative text. E.g.
5366 * Image:one.jpg|The number "1"
5367 * Image:tree.jpg|A tree
5368 * given as text will return the HTML of a gallery with two images,
5369 * labeled 'The number "1"' and
5372 * @param string $text
5373 * @param array $params
5374 * @return string HTML
5376 public function renderImageGallery( $text, $params ) {
5377 wfProfileIn( __METHOD__
);
5380 if ( isset( $params['mode'] ) ) {
5381 $mode = $params['mode'];
5385 $ig = ImageGalleryBase
::factory( $mode );
5386 } catch ( MWException
$e ) {
5387 // If invalid type set, fallback to default.
5388 $ig = ImageGalleryBase
::factory( false );
5391 $ig->setContextTitle( $this->mTitle
);
5392 $ig->setShowBytes( false );
5393 $ig->setShowFilename( false );
5394 $ig->setParser( $this );
5395 $ig->setHideBadImages();
5396 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
5398 if ( isset( $params['showfilename'] ) ) {
5399 $ig->setShowFilename( true );
5401 $ig->setShowFilename( false );
5403 if ( isset( $params['caption'] ) ) {
5404 $caption = $params['caption'];
5405 $caption = htmlspecialchars( $caption );
5406 $caption = $this->replaceInternalLinks( $caption );
5407 $ig->setCaptionHtml( $caption );
5409 if ( isset( $params['perrow'] ) ) {
5410 $ig->setPerRow( $params['perrow'] );
5412 if ( isset( $params['widths'] ) ) {
5413 $ig->setWidths( $params['widths'] );
5415 if ( isset( $params['heights'] ) ) {
5416 $ig->setHeights( $params['heights'] );
5418 $ig->setAdditionalOptions( $params );
5420 Hooks
::run( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5422 $lines = StringUtils
::explode( "\n", $text );
5423 foreach ( $lines as $line ) {
5424 # match lines like these:
5425 # Image:someimage.jpg|This is some image
5427 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5429 if ( count( $matches ) == 0 ) {
5433 if ( strpos( $matches[0], '%' ) !== false ) {
5434 $matches[1] = rawurldecode( $matches[1] );
5436 $title = Title
::newFromText( $matches[1], NS_FILE
);
5437 if ( is_null( $title ) ) {
5438 # Bogus title. Ignore these so we don't bomb out later.
5442 # We need to get what handler the file uses, to figure out parameters.
5443 # Note, a hook can overide the file name, and chose an entirely different
5444 # file (which potentially could be of a different type and have different handler).
5447 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5448 array( $this, $title, &$options, &$descQuery ) );
5449 # Don't register it now, as ImageGallery does that later.
5450 $file = $this->fetchFileNoRegister( $title, $options );
5451 $handler = $file ?
$file->getHandler() : false;
5453 wfProfileIn( __METHOD__
. '-getMagicWord' );
5455 'img_alt' => 'gallery-internal-alt',
5456 'img_link' => 'gallery-internal-link',
5459 $paramMap = $paramMap +
$handler->getParamMap();
5460 // We don't want people to specify per-image widths.
5461 // Additionally the width parameter would need special casing anyhow.
5462 unset( $paramMap['img_width'] );
5465 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5466 wfProfileOut( __METHOD__
. '-getMagicWord' );
5471 $handlerOptions = array();
5472 if ( isset( $matches[3] ) ) {
5473 // look for an |alt= definition while trying not to break existing
5474 // captions with multiple pipes (|) in it, until a more sensible grammar
5475 // is defined for images in galleries
5477 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5478 // splitting on '|' is a bit odd, and different from makeImage.
5479 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5480 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
5482 foreach ( $parameterMatches as $parameterMatch ) {
5483 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5485 $paramName = $paramMap[$magicName];
5487 switch ( $paramName ) {
5488 case 'gallery-internal-alt':
5489 $alt = $this->stripAltText( $match, false );
5491 case 'gallery-internal-link':
5492 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5493 $chars = self
::EXT_LINK_URL_CLASS
;
5494 $prots = $this->mUrlProtocols
;
5495 //check to see if link matches an absolute url, if not then it must be a wiki link.
5496 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5499 $localLinkTitle = Title
::newFromText( $linkValue );
5500 if ( $localLinkTitle !== null ) {
5501 $link = $localLinkTitle->getLinkURL();
5506 // Must be a handler specific parameter.
5507 if ( $handler->validateParam( $paramName, $match ) ) {
5508 $handlerOptions[$paramName] = $match;
5510 // Guess not. Append it to the caption.
5511 wfDebug( "$parameterMatch failed parameter validation\n" );
5512 $label .= '|' . $parameterMatch;
5517 // concatenate all other pipes
5518 $label .= '|' . $parameterMatch;
5521 // remove the first pipe
5522 $label = substr( $label, 1 );
5525 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5527 $html = $ig->toHTML();
5528 Hooks
::run( 'AfterParserFetchFileAndTitle', array( $this, $ig, &$html ) );
5529 wfProfileOut( __METHOD__
);
5534 * @param string $handler
5537 public function getImageParams( $handler ) {
5539 $handlerClass = get_class( $handler );
5543 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5544 # Initialise static lists
5545 static $internalParamNames = array(
5546 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5547 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5548 'bottom', 'text-bottom' ),
5549 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5550 'upright', 'border', 'link', 'alt', 'class' ),
5552 static $internalParamMap;
5553 if ( !$internalParamMap ) {
5554 $internalParamMap = array();
5555 foreach ( $internalParamNames as $type => $names ) {
5556 foreach ( $names as $name ) {
5557 $magicName = str_replace( '-', '_', "img_$name" );
5558 $internalParamMap[$magicName] = array( $type, $name );
5563 # Add handler params
5564 $paramMap = $internalParamMap;
5566 $handlerParamMap = $handler->getParamMap();
5567 foreach ( $handlerParamMap as $magic => $paramName ) {
5568 $paramMap[$magic] = array( 'handler', $paramName );
5571 $this->mImageParams
[$handlerClass] = $paramMap;
5572 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5574 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5578 * Parse image options text and use it to make an image
5580 * @param Title $title
5581 * @param string $options
5582 * @param LinkHolderArray|bool $holders
5583 * @return string HTML
5585 public function makeImage( $title, $options, $holders = false ) {
5586 # Check if the options text is of the form "options|alt text"
5588 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5589 # * left no resizing, just left align. label is used for alt= only
5590 # * right same, but right aligned
5591 # * none same, but not aligned
5592 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5593 # * center center the image
5594 # * frame Keep original image size, no magnify-button.
5595 # * framed Same as "frame"
5596 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5597 # * upright reduce width for upright images, rounded to full __0 px
5598 # * border draw a 1px border around the image
5599 # * alt Text for HTML alt attribute (defaults to empty)
5600 # * class Set a class for img node
5601 # * link Set the target of the image link. Can be external, interwiki, or local
5602 # vertical-align values (no % or length right now):
5612 $parts = StringUtils
::explode( "|", $options );
5614 # Give extensions a chance to select the file revision for us
5617 Hooks
::run( 'BeforeParserFetchFileAndTitle',
5618 array( $this, $title, &$options, &$descQuery ) );
5619 # Fetch and register the file (file title may be different via hooks)
5620 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5623 $handler = $file ?
$file->getHandler() : false;
5625 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5628 $this->addTrackingCategory( 'broken-file-category' );
5631 # Process the input parameters
5633 $params = array( 'frame' => array(), 'handler' => array(),
5634 'horizAlign' => array(), 'vertAlign' => array() );
5635 $seenformat = false;
5636 foreach ( $parts as $part ) {
5637 $part = trim( $part );
5638 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5640 if ( isset( $paramMap[$magicName] ) ) {
5641 list( $type, $paramName ) = $paramMap[$magicName];
5643 # Special case; width and height come in one variable together
5644 if ( $type === 'handler' && $paramName === 'width' ) {
5645 $parsedWidthParam = $this->parseWidthParam( $value );
5646 if ( isset( $parsedWidthParam['width'] ) ) {
5647 $width = $parsedWidthParam['width'];
5648 if ( $handler->validateParam( 'width', $width ) ) {
5649 $params[$type]['width'] = $width;
5653 if ( isset( $parsedWidthParam['height'] ) ) {
5654 $height = $parsedWidthParam['height'];
5655 if ( $handler->validateParam( 'height', $height ) ) {
5656 $params[$type]['height'] = $height;
5660 # else no validation -- bug 13436
5662 if ( $type === 'handler' ) {
5663 # Validate handler parameter
5664 $validated = $handler->validateParam( $paramName, $value );
5666 # Validate internal parameters
5667 switch ( $paramName ) {
5671 # @todo FIXME: Possibly check validity here for
5672 # manualthumb? downstream behavior seems odd with
5673 # missing manual thumbs.
5675 $value = $this->stripAltText( $value, $holders );
5678 $chars = self
::EXT_LINK_URL_CLASS
;
5679 $prots = $this->mUrlProtocols
;
5680 if ( $value === '' ) {
5681 $paramName = 'no-link';
5684 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5685 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5686 $paramName = 'link-url';
5687 $this->mOutput
->addExternalLink( $value );
5688 if ( $this->mOptions
->getExternalLinkTarget() ) {
5689 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5694 $linkTitle = Title
::newFromText( $value );
5696 $paramName = 'link-title';
5697 $value = $linkTitle;
5698 $this->mOutput
->addLink( $linkTitle );
5706 // use first appearing option, discard others.
5707 $validated = ! $seenformat;
5711 # Most other things appear to be empty or numeric...
5712 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5717 $params[$type][$paramName] = $value;
5721 if ( !$validated ) {
5726 # Process alignment parameters
5727 if ( $params['horizAlign'] ) {
5728 $params['frame']['align'] = key( $params['horizAlign'] );
5730 if ( $params['vertAlign'] ) {
5731 $params['frame']['valign'] = key( $params['vertAlign'] );
5734 $params['frame']['caption'] = $caption;
5736 # Will the image be presented in a frame, with the caption below?
5737 $imageIsFramed = isset( $params['frame']['frame'] )
5738 ||
isset( $params['frame']['framed'] )
5739 ||
isset( $params['frame']['thumbnail'] )
5740 ||
isset( $params['frame']['manualthumb'] );
5742 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5743 # came to also set the caption, ordinary text after the image -- which
5744 # makes no sense, because that just repeats the text multiple times in
5745 # screen readers. It *also* came to set the title attribute.
5747 # Now that we have an alt attribute, we should not set the alt text to
5748 # equal the caption: that's worse than useless, it just repeats the
5749 # text. This is the framed/thumbnail case. If there's no caption, we
5750 # use the unnamed parameter for alt text as well, just for the time be-
5751 # ing, if the unnamed param is set and the alt param is not.
5753 # For the future, we need to figure out if we want to tweak this more,
5754 # e.g., introducing a title= parameter for the title; ignoring the un-
5755 # named parameter entirely for images without a caption; adding an ex-
5756 # plicit caption= parameter and preserving the old magic unnamed para-
5758 if ( $imageIsFramed ) { # Framed image
5759 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5760 # No caption or alt text, add the filename as the alt text so
5761 # that screen readers at least get some description of the image
5762 $params['frame']['alt'] = $title->getText();
5764 # Do not set $params['frame']['title'] because tooltips don't make sense
5766 } else { # Inline image
5767 if ( !isset( $params['frame']['alt'] ) ) {
5768 # No alt text, use the "caption" for the alt text
5769 if ( $caption !== '' ) {
5770 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5772 # No caption, fall back to using the filename for the
5774 $params['frame']['alt'] = $title->getText();
5777 # Use the "caption" for the tooltip text
5778 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5781 Hooks
::run( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5783 # Linker does the rest
5784 $time = isset( $options['time'] ) ?
$options['time'] : false;
5785 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5786 $time, $descQuery, $this->mOptions
->getThumbSize() );
5788 # Give the handler a chance to modify the parser object
5790 $handler->parserTransformHook( $this, $file );
5797 * @param string $caption
5798 * @param LinkHolderArray|bool $holders
5799 * @return mixed|string
5801 protected function stripAltText( $caption, $holders ) {
5802 # Strip bad stuff out of the title (tooltip). We can't just use
5803 # replaceLinkHoldersText() here, because if this function is called
5804 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5806 $tooltip = $holders->replaceText( $caption );
5808 $tooltip = $this->replaceLinkHoldersText( $caption );
5811 # make sure there are no placeholders in thumbnail attributes
5812 # that are later expanded to html- so expand them now and
5814 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5815 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5821 * Set a flag in the output object indicating that the content is dynamic and
5822 * shouldn't be cached.
5824 public function disableCache() {
5825 wfDebug( "Parser output marked as uncacheable.\n" );
5826 if ( !$this->mOutput
) {
5827 throw new MWException( __METHOD__
.
5828 " can only be called when actually parsing something" );
5830 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5831 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5835 * Callback from the Sanitizer for expanding items found in HTML attribute
5836 * values, so they can be safely tested and escaped.
5838 * @param string $text
5839 * @param bool|PPFrame $frame
5842 public function attributeStripCallback( &$text, $frame = false ) {
5843 $text = $this->replaceVariables( $text, $frame );
5844 $text = $this->mStripState
->unstripBoth( $text );
5853 public function getTags() {
5855 array_keys( $this->mTransparentTagHooks
),
5856 array_keys( $this->mTagHooks
),
5857 array_keys( $this->mFunctionTagHooks
)
5862 * Replace transparent tags in $text with the values given by the callbacks.
5864 * Transparent tag hooks are like regular XML-style tag hooks, except they
5865 * operate late in the transformation sequence, on HTML instead of wikitext.
5867 * @param string $text
5871 public function replaceTransparentTags( $text ) {
5873 $elements = array_keys( $this->mTransparentTagHooks
);
5874 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5875 $replacements = array();
5877 foreach ( $matches as $marker => $data ) {
5878 list( $element, $content, $params, $tag ) = $data;
5879 $tagName = strtolower( $element );
5880 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5881 $output = call_user_func_array(
5882 $this->mTransparentTagHooks
[$tagName],
5883 array( $content, $params, $this )
5888 $replacements[$marker] = $output;
5890 return strtr( $text, $replacements );
5894 * Break wikitext input into sections, and either pull or replace
5895 * some particular section's text.
5897 * External callers should use the getSection and replaceSection methods.
5899 * @param string $text Page wikitext
5900 * @param string|number $sectionId A section identifier string of the form:
5901 * "<flag1> - <flag2> - ... - <section number>"
5903 * Currently the only recognised flag is "T", which means the target section number
5904 * was derived during a template inclusion parse, in other words this is a template
5905 * section edit link. If no flags are given, it was an ordinary section edit link.
5906 * This flag is required to avoid a section numbering mismatch when a section is
5907 * enclosed by "<includeonly>" (bug 6563).
5909 * The section number 0 pulls the text before the first heading; other numbers will
5910 * pull the given section along with its lower-level subsections. If the section is
5911 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5913 * Section 0 is always considered to exist, even if it only contains the empty
5914 * string. If $text is the empty string and section 0 is replaced, $newText is
5917 * @param string $mode One of "get" or "replace"
5918 * @param string $newText Replacement text for section data.
5919 * @return string For "get", the extracted section text.
5920 * for "replace", the whole page with the section replaced.
5922 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5923 global $wgTitle; # not generally used but removes an ugly failure mode
5925 $magicScopeVariable = $this->lock();
5926 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5928 $frame = $this->getPreprocessor()->newFrame();
5930 # Process section extraction flags
5932 $sectionParts = explode( '-', $sectionId );
5933 $sectionIndex = array_pop( $sectionParts );
5934 foreach ( $sectionParts as $part ) {
5935 if ( $part === 'T' ) {
5936 $flags |
= self
::PTD_FOR_INCLUSION
;
5940 # Check for empty input
5941 if ( strval( $text ) === '' ) {
5942 # Only sections 0 and T-0 exist in an empty document
5943 if ( $sectionIndex == 0 ) {
5944 if ( $mode === 'get' ) {
5950 if ( $mode === 'get' ) {
5958 # Preprocess the text
5959 $root = $this->preprocessToDom( $text, $flags );
5961 # <h> nodes indicate section breaks
5962 # They can only occur at the top level, so we can find them by iterating the root's children
5963 $node = $root->getFirstChild();
5965 # Find the target section
5966 if ( $sectionIndex == 0 ) {
5967 # Section zero doesn't nest, level=big
5968 $targetLevel = 1000;
5971 if ( $node->getName() === 'h' ) {
5972 $bits = $node->splitHeading();
5973 if ( $bits['i'] == $sectionIndex ) {
5974 $targetLevel = $bits['level'];
5978 if ( $mode === 'replace' ) {
5979 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5981 $node = $node->getNextSibling();
5987 if ( $mode === 'get' ) {
5994 # Find the end of the section, including nested sections
5996 if ( $node->getName() === 'h' ) {
5997 $bits = $node->splitHeading();
5998 $curLevel = $bits['level'];
5999 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
6003 if ( $mode === 'get' ) {
6004 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
6006 $node = $node->getNextSibling();
6009 # Write out the remainder (in replace mode only)
6010 if ( $mode === 'replace' ) {
6011 # Output the replacement text
6012 # Add two newlines on -- trailing whitespace in $newText is conventionally
6013 # stripped by the editor, so we need both newlines to restore the paragraph gap
6014 # Only add trailing whitespace if there is newText
6015 if ( $newText != "" ) {
6016 $outText .= $newText . "\n\n";
6020 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
6021 $node = $node->getNextSibling();
6025 if ( is_string( $outText ) ) {
6026 # Re-insert stripped tags
6027 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
6034 * This function returns the text of a section, specified by a number ($section).
6035 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
6036 * the first section before any such heading (section 0).
6038 * If a section contains subsections, these are also returned.
6040 * @param string $text Text to look in
6041 * @param string|number $sectionId Section identifier as a number or string
6042 * (e.g. 0, 1 or 'T-1').
6043 * @param string $defaultText Default to return if section is not found
6045 * @return string Text of the requested section
6047 public function getSection( $text, $sectionId, $defaultText = '' ) {
6048 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
6052 * This function returns $oldtext after the content of the section
6053 * specified by $section has been replaced with $text. If the target
6054 * section does not exist, $oldtext is returned unchanged.
6056 * @param string $oldText Former text of the article
6057 * @param string|number $sectionId Section identifier as a number or string
6058 * (e.g. 0, 1 or 'T-1').
6059 * @param string $newText Replacing text
6061 * @return string Modified text
6063 public function replaceSection( $oldText, $sectionId, $newText ) {
6064 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
6068 * Get the ID of the revision we are parsing
6072 public function getRevisionId() {
6073 return $this->mRevisionId
;
6077 * Get the revision object for $this->mRevisionId
6079 * @return Revision|null Either a Revision object or null
6080 * @since 1.23 (public since 1.23)
6082 public function getRevisionObject() {
6083 if ( !is_null( $this->mRevisionObject
) ) {
6084 return $this->mRevisionObject
;
6086 if ( is_null( $this->mRevisionId
) ) {
6090 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
6091 return $this->mRevisionObject
;
6095 * Get the timestamp associated with the current revision, adjusted for
6096 * the default server-local timestamp
6099 public function getRevisionTimestamp() {
6100 if ( is_null( $this->mRevisionTimestamp
) ) {
6101 wfProfileIn( __METHOD__
);
6105 $revObject = $this->getRevisionObject();
6106 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
6108 # The cryptic '' timezone parameter tells to use the site-default
6109 # timezone offset instead of the user settings.
6111 # Since this value will be saved into the parser cache, served
6112 # to other users, and potentially even used inside links and such,
6113 # it needs to be consistent for all visitors.
6114 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
6116 wfProfileOut( __METHOD__
);
6118 return $this->mRevisionTimestamp
;
6122 * Get the name of the user that edited the last revision
6124 * @return string User name
6126 public function getRevisionUser() {
6127 if ( is_null( $this->mRevisionUser
) ) {
6128 $revObject = $this->getRevisionObject();
6130 # if this template is subst: the revision id will be blank,
6131 # so just use the current user's name
6133 $this->mRevisionUser
= $revObject->getUserText();
6134 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6135 $this->mRevisionUser
= $this->getUser()->getName();
6138 return $this->mRevisionUser
;
6142 * Get the size of the revision
6144 * @return int|null Revision size
6146 public function getRevisionSize() {
6147 if ( is_null( $this->mRevisionSize
) ) {
6148 $revObject = $this->getRevisionObject();
6150 # if this variable is subst: the revision id will be blank,
6151 # so just use the parser input size, because the own substituation
6152 # will change the size.
6154 $this->mRevisionSize
= $revObject->getSize();
6155 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6156 $this->mRevisionSize
= $this->mInputSize
;
6159 return $this->mRevisionSize
;
6163 * Mutator for $mDefaultSort
6165 * @param string $sort New value
6167 public function setDefaultSort( $sort ) {
6168 $this->mDefaultSort
= $sort;
6169 $this->mOutput
->setProperty( 'defaultsort', $sort );
6173 * Accessor for $mDefaultSort
6174 * Will use the empty string if none is set.
6176 * This value is treated as a prefix, so the
6177 * empty string is equivalent to sorting by
6182 public function getDefaultSort() {
6183 if ( $this->mDefaultSort
!== false ) {
6184 return $this->mDefaultSort
;
6191 * Accessor for $mDefaultSort
6192 * Unlike getDefaultSort(), will return false if none is set
6194 * @return string|bool
6196 public function getCustomDefaultSort() {
6197 return $this->mDefaultSort
;
6201 * Try to guess the section anchor name based on a wikitext fragment
6202 * presumably extracted from a heading, for example "Header" from
6205 * @param string $text
6209 public function guessSectionNameFromWikiText( $text ) {
6210 # Strip out wikitext links(they break the anchor)
6211 $text = $this->stripSectionName( $text );
6212 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6213 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
6217 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6218 * instead. For use in redirects, since IE6 interprets Redirect: headers
6219 * as something other than UTF-8 (apparently?), resulting in breakage.
6221 * @param string $text The section name
6222 * @return string An anchor
6224 public function guessLegacySectionNameFromWikiText( $text ) {
6225 # Strip out wikitext links(they break the anchor)
6226 $text = $this->stripSectionName( $text );
6227 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6228 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
6232 * Strips a text string of wikitext for use in a section anchor
6234 * Accepts a text string and then removes all wikitext from the
6235 * string and leaves only the resultant text (i.e. the result of
6236 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6237 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6238 * to create valid section anchors by mimicing the output of the
6239 * parser when headings are parsed.
6241 * @param string $text Text string to be stripped of wikitext
6242 * for use in a Section anchor
6243 * @return string Filtered text string
6245 public function stripSectionName( $text ) {
6246 # Strip internal link markup
6247 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6248 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6250 # Strip external link markup
6251 # @todo FIXME: Not tolerant to blank link text
6252 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6253 # on how many empty links there are on the page - need to figure that out.
6254 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6256 # Parse wikitext quotes (italics & bold)
6257 $text = $this->doQuotes( $text );
6260 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
6265 * strip/replaceVariables/unstrip for preprocessor regression testing
6267 * @param string $text
6268 * @param Title $title
6269 * @param ParserOptions $options
6270 * @param int $outputType
6274 public function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
6275 $magicScopeVariable = $this->lock();
6276 $this->startParse( $title, $options, $outputType, true );
6278 $text = $this->replaceVariables( $text );
6279 $text = $this->mStripState
->unstripBoth( $text );
6280 $text = Sanitizer
::removeHTMLtags( $text );
6285 * @param string $text
6286 * @param Title $title
6287 * @param ParserOptions $options
6290 public function testPst( $text, Title
$title, ParserOptions
$options ) {
6291 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6295 * @param string $text
6296 * @param Title $title
6297 * @param ParserOptions $options
6300 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
6301 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
6305 * Call a callback function on all regions of the given text that are not
6306 * inside strip markers, and replace those regions with the return value
6307 * of the callback. For example, with input:
6311 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6312 * two strings will be replaced with the value returned by the callback in
6316 * @param callable $callback
6320 public function markerSkipCallback( $s, $callback ) {
6323 while ( $i < strlen( $s ) ) {
6324 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
6325 if ( $markerStart === false ) {
6326 $out .= call_user_func( $callback, substr( $s, $i ) );
6329 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6330 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6331 if ( $markerEnd === false ) {
6332 $out .= substr( $s, $markerStart );
6335 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6336 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6345 * Remove any strip markers found in the given text.
6347 * @param string $text Input string
6350 public function killMarkers( $text ) {
6351 return $this->mStripState
->killMarkers( $text );
6355 * Save the parser state required to convert the given half-parsed text to
6356 * HTML. "Half-parsed" in this context means the output of
6357 * recursiveTagParse() or internalParse(). This output has strip markers
6358 * from replaceVariables (extensionSubstitution() etc.), and link
6359 * placeholders from replaceLinkHolders().
6361 * Returns an array which can be serialized and stored persistently. This
6362 * array can later be loaded into another parser instance with
6363 * unserializeHalfParsedText(). The text can then be safely incorporated into
6364 * the return value of a parser hook.
6366 * @param string $text
6370 public function serializeHalfParsedText( $text ) {
6371 wfProfileIn( __METHOD__
);
6374 'version' => self
::HALF_PARSED_VERSION
,
6375 'stripState' => $this->mStripState
->getSubState( $text ),
6376 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6378 wfProfileOut( __METHOD__
);
6383 * Load the parser state given in the $data array, which is assumed to
6384 * have been generated by serializeHalfParsedText(). The text contents is
6385 * extracted from the array, and its markers are transformed into markers
6386 * appropriate for the current Parser instance. This transformed text is
6387 * returned, and can be safely included in the return value of a parser
6390 * If the $data array has been stored persistently, the caller should first
6391 * check whether it is still valid, by calling isValidHalfParsedText().
6393 * @param array $data Serialized data
6394 * @throws MWException
6397 public function unserializeHalfParsedText( $data ) {
6398 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6399 throw new MWException( __METHOD__
. ': invalid version' );
6402 # First, extract the strip state.
6403 $texts = array( $data['text'] );
6404 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6406 # Now renumber links
6407 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6409 # Should be good to go.
6414 * Returns true if the given array, presumed to be generated by
6415 * serializeHalfParsedText(), is compatible with the current version of the
6418 * @param array $data
6422 public function isValidHalfParsedText( $data ) {
6423 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6427 * Parsed a width param of imagelink like 300px or 200x300px
6429 * @param string $value
6434 public function parseWidthParam( $value ) {
6435 $parsedWidthParam = array();
6436 if ( $value === '' ) {
6437 return $parsedWidthParam;
6440 # (bug 13500) In both cases (width/height and width only),
6441 # permit trailing "px" for backward compatibility.
6442 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6443 $width = intval( $m[1] );
6444 $height = intval( $m[2] );
6445 $parsedWidthParam['width'] = $width;
6446 $parsedWidthParam['height'] = $height;
6447 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6448 $width = intval( $value );
6449 $parsedWidthParam['width'] = $width;
6451 return $parsedWidthParam;
6455 * Lock the current instance of the parser.
6457 * This is meant to stop someone from calling the parser
6458 * recursively and messing up all the strip state.
6460 * @throws MWException If parser is in a parse
6461 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6463 protected function lock() {
6464 if ( $this->mInParse
) {
6465 throw new MWException( "Parser state cleared while parsing. "
6466 . "Did you call Parser::parse recursively?" );
6468 $this->mInParse
= true;
6471 $recursiveCheck = new ScopedCallback( function() use ( $that ) {
6472 $that->mInParse
= false;
6475 return $recursiveCheck;
6479 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6481 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6482 * or if there is more than one <p/> tag in the input HTML.
6484 * @param string $html
6488 public static function stripOuterParagraph( $html ) {
6490 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6491 if ( strpos( $m[1], '</p>' ) === false ) {
6500 * Return this parser if it is not doing anything, otherwise
6501 * get a fresh parser. You can use this method by doing
6502 * $myParser = $wgParser->getFreshParser(), or more simply
6503 * $wgParser->getFreshParser()->parse( ... );
6504 * if you're unsure if $wgParser is safe to use.
6507 * @return Parser A parser object that is not parsing anything
6509 public function getFreshParser() {
6510 global $wgParserConf;
6511 if ( $this->mInParse
) {
6512 return new $wgParserConf['class']( $wgParserConf );