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 wfRunHooks( '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 wfRunHooks( '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 wfRunHooks( '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 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
433 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
434 $text = $this->internalParse( $text );
435 wfRunHooks( '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 wfRunHooks( '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 ( wfRunHooks( '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 wfRunHooks( '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 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
591 wfRunHooks( '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 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
641 wfRunHooks( '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 ( !wfRunHooks( '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 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1248 $text = Sanitizer
::removeHTMLtags(
1250 array( &$this, 'attributeStripCallback' ),
1252 array_keys( $this->mTransparentTagHooks
)
1254 wfRunHooks( '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 wfRunHooks( '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 wfRunHooks( '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 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1398 ISBN\s+(\b # 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 $numSepChars = strspn( strrev( $url ), $sep );
1488 if ( $numSepChars ) {
1489 $trail = substr( $url, -$numSepChars ) . $trail;
1490 $url = substr( $url, 0, -$numSepChars );
1493 $url = Sanitizer
::cleanUrl( $url );
1495 # Is this an external image?
1496 $text = $this->maybeMakeExternalImage( $url );
1497 if ( $text === false ) {
1498 # Not an image, make a link
1499 $text = Linker
::makeExternalLink( $url,
1500 $this->getConverterLanguage()->markNoConversion( $url, true ),
1502 $this->getExternalLinkAttribs( $url ) );
1503 # Register it in the output object...
1504 # Replace unnecessary URL escape codes with their equivalent characters
1505 $pasteurized = self
::normalizeLinkUrl( $url );
1506 $this->mOutput
->addExternalLink( $pasteurized );
1508 wfProfileOut( __METHOD__
);
1509 return $text . $trail;
1513 * Parse headers and return html
1517 * @param string $text
1521 public function doHeadings( $text ) {
1522 wfProfileIn( __METHOD__
);
1523 for ( $i = 6; $i >= 1; --$i ) {
1524 $h = str_repeat( '=', $i );
1525 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1527 wfProfileOut( __METHOD__
);
1532 * Replace single quotes with HTML markup
1535 * @param string $text
1537 * @return string The altered text
1539 public function doAllQuotes( $text ) {
1540 wfProfileIn( __METHOD__
);
1542 $lines = StringUtils
::explode( "\n", $text );
1543 foreach ( $lines as $line ) {
1544 $outtext .= $this->doQuotes( $line ) . "\n";
1546 $outtext = substr( $outtext, 0, -1 );
1547 wfProfileOut( __METHOD__
);
1552 * Helper function for doAllQuotes()
1554 * @param string $text
1558 public function doQuotes( $text ) {
1559 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1560 $countarr = count( $arr );
1561 if ( $countarr == 1 ) {
1565 // First, do some preliminary work. This may shift some apostrophes from
1566 // being mark-up to being text. It also counts the number of occurrences
1567 // of bold and italics mark-ups.
1570 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1571 $thislen = strlen( $arr[$i] );
1572 // If there are ever four apostrophes, assume the first is supposed to
1573 // be text, and the remaining three constitute mark-up for bold text.
1574 // (bug 13227: ''''foo'''' turns into ' ''' foo ' ''')
1575 if ( $thislen == 4 ) {
1576 $arr[$i - 1] .= "'";
1579 } elseif ( $thislen > 5 ) {
1580 // If there are more than 5 apostrophes in a row, assume they're all
1581 // text except for the last 5.
1582 // (bug 13227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1583 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1587 // Count the number of occurrences of bold and italics mark-ups.
1588 if ( $thislen == 2 ) {
1590 } elseif ( $thislen == 3 ) {
1592 } elseif ( $thislen == 5 ) {
1598 // If there is an odd number of both bold and italics, it is likely
1599 // that one of the bold ones was meant to be an apostrophe followed
1600 // by italics. Which one we cannot know for certain, but it is more
1601 // likely to be one that has a single-letter word before it.
1602 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1603 $firstsingleletterword = -1;
1604 $firstmultiletterword = -1;
1606 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1607 if ( strlen( $arr[$i] ) == 3 ) {
1608 $x1 = substr( $arr[$i - 1], -1 );
1609 $x2 = substr( $arr[$i - 1], -2, 1 );
1610 if ( $x1 === ' ' ) {
1611 if ( $firstspace == -1 ) {
1614 } elseif ( $x2 === ' ' ) {
1615 if ( $firstsingleletterword == -1 ) {
1616 $firstsingleletterword = $i;
1617 // if $firstsingleletterword is set, we don't
1618 // look at the other options, so we can bail early.
1622 if ( $firstmultiletterword == -1 ) {
1623 $firstmultiletterword = $i;
1629 // If there is a single-letter word, use it!
1630 if ( $firstsingleletterword > -1 ) {
1631 $arr[$firstsingleletterword] = "''";
1632 $arr[$firstsingleletterword - 1] .= "'";
1633 } elseif ( $firstmultiletterword > -1 ) {
1634 // If not, but there's a multi-letter word, use that one.
1635 $arr[$firstmultiletterword] = "''";
1636 $arr[$firstmultiletterword - 1] .= "'";
1637 } elseif ( $firstspace > -1 ) {
1638 // ... otherwise use the first one that has neither.
1639 // (notice that it is possible for all three to be -1 if, for example,
1640 // there is only one pentuple-apostrophe in the line)
1641 $arr[$firstspace] = "''";
1642 $arr[$firstspace - 1] .= "'";
1646 // Now let's actually convert our apostrophic mush to HTML!
1651 foreach ( $arr as $r ) {
1652 if ( ( $i %
2 ) == 0 ) {
1653 if ( $state === 'both' ) {
1659 $thislen = strlen( $r );
1660 if ( $thislen == 2 ) {
1661 if ( $state === 'i' ) {
1664 } elseif ( $state === 'bi' ) {
1667 } elseif ( $state === 'ib' ) {
1668 $output .= '</b></i><b>';
1670 } elseif ( $state === 'both' ) {
1671 $output .= '<b><i>' . $buffer . '</i>';
1673 } else { // $state can be 'b' or ''
1677 } elseif ( $thislen == 3 ) {
1678 if ( $state === 'b' ) {
1681 } elseif ( $state === 'bi' ) {
1682 $output .= '</i></b><i>';
1684 } elseif ( $state === 'ib' ) {
1687 } elseif ( $state === 'both' ) {
1688 $output .= '<i><b>' . $buffer . '</b>';
1690 } else { // $state can be 'i' or ''
1694 } elseif ( $thislen == 5 ) {
1695 if ( $state === 'b' ) {
1696 $output .= '</b><i>';
1698 } elseif ( $state === 'i' ) {
1699 $output .= '</i><b>';
1701 } elseif ( $state === 'bi' ) {
1702 $output .= '</i></b>';
1704 } elseif ( $state === 'ib' ) {
1705 $output .= '</b></i>';
1707 } elseif ( $state === 'both' ) {
1708 $output .= '<i><b>' . $buffer . '</b></i>';
1710 } else { // ($state == '')
1718 // Now close all remaining tags. Notice that the order is important.
1719 if ( $state === 'b' ||
$state === 'ib' ) {
1722 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1725 if ( $state === 'bi' ) {
1728 // There might be lonely ''''', so make sure we have a buffer
1729 if ( $state === 'both' && $buffer ) {
1730 $output .= '<b><i>' . $buffer . '</i></b>';
1736 * Replace external links (REL)
1738 * Note: this is all very hackish and the order of execution matters a lot.
1739 * Make sure to run tests/parserTests.php if you change this code.
1743 * @param string $text
1745 * @throws MWException
1748 public function replaceExternalLinks( $text ) {
1749 wfProfileIn( __METHOD__
);
1751 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1752 if ( $bits === false ) {
1753 wfProfileOut( __METHOD__
);
1754 throw new MWException( "PCRE needs to be compiled with "
1755 . "--enable-unicode-properties in order for MediaWiki to function" );
1757 $s = array_shift( $bits );
1760 while ( $i < count( $bits ) ) {
1763 $text = $bits[$i++
];
1764 $trail = $bits[$i++
];
1766 # The characters '<' and '>' (which were escaped by
1767 # removeHTMLtags()) should not be included in
1768 # URLs, per RFC 2396.
1770 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1771 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1772 $url = substr( $url, 0, $m2[0][1] );
1775 # If the link text is an image URL, replace it with an <img> tag
1776 # This happened by accident in the original parser, but some people used it extensively
1777 $img = $this->maybeMakeExternalImage( $text );
1778 if ( $img !== false ) {
1784 # Set linktype for CSS - if URL==text, link is essentially free
1785 $linktype = ( $text === $url ) ?
'free' : 'text';
1787 # No link text, e.g. [http://domain.tld/some.link]
1788 if ( $text == '' ) {
1790 $langObj = $this->getTargetLanguage();
1791 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1792 $linktype = 'autonumber';
1794 # Have link text, e.g. [http://domain.tld/some.link text]s
1796 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1799 $text = $this->getConverterLanguage()->markNoConversion( $text );
1801 $url = Sanitizer
::cleanUrl( $url );
1803 # Use the encoded URL
1804 # This means that users can paste URLs directly into the text
1805 # Funny characters like ö aren't valid in URLs anyway
1806 # This was changed in August 2004
1807 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1808 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1810 # Register link in the output object.
1811 # Replace unnecessary URL escape codes with the referenced character
1812 # This prevents spammers from hiding links from the filters
1813 $pasteurized = self
::normalizeLinkUrl( $url );
1814 $this->mOutput
->addExternalLink( $pasteurized );
1817 wfProfileOut( __METHOD__
);
1822 * Get the rel attribute for a particular external link.
1825 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1826 * nofollow if appropriate
1827 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1828 * @return string|null Rel attribute for $url
1830 public static function getExternalLinkRel( $url = false, $title = null ) {
1831 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1832 $ns = $title ?
$title->getNamespace() : false;
1833 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1834 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1842 * Get an associative array of additional HTML attributes appropriate for a
1843 * particular external link. This currently may include rel => nofollow
1844 * (depending on configuration, namespace, and the URL's domain) and/or a
1845 * target attribute (depending on configuration).
1847 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1848 * nofollow if appropriate
1849 * @return array Associative array of HTML attributes
1851 public function getExternalLinkAttribs( $url = false ) {
1853 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1855 if ( $this->mOptions
->getExternalLinkTarget() ) {
1856 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1862 * Replace unusual escape codes in a URL with their equivalent characters
1864 * @deprecated since 1.24, use normalizeLinkUrl
1865 * @param string $url
1868 public static function replaceUnusualEscapes( $url ) {
1869 wfDeprecated( __METHOD__
, '1.24' );
1870 return self
::normalizeLinkUrl( $url );
1874 * Replace unusual escape codes in a URL with their equivalent characters
1876 * This generally follows the syntax defined in RFC 3986, with special
1877 * consideration for HTTP query strings.
1879 * @param string $url
1882 public static function normalizeLinkUrl( $url ) {
1883 # First, make sure unsafe characters are encoded
1884 $url = preg_replace_callback( '/[\x00-\x20"<>\[\\\\\]^`{|}\x7F-\xFF]/',
1886 return rawurlencode( $m[0] );
1892 $end = strlen( $url );
1894 # Fragment part - 'fragment'
1895 $start = strpos( $url, '#' );
1896 if ( $start !== false && $start < $end ) {
1897 $ret = self
::normalizeUrlComponent(
1898 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}' ) . $ret;
1902 # Query part - 'query' minus &=+;
1903 $start = strpos( $url, '?' );
1904 if ( $start !== false && $start < $end ) {
1905 $ret = self
::normalizeUrlComponent(
1906 substr( $url, $start, $end - $start ), '"#%<>[\]^`{|}&=+;' ) . $ret;
1910 # Scheme and path part - 'pchar'
1911 # (we assume no userinfo or encoded colons in the host)
1912 $ret = self
::normalizeUrlComponent(
1913 substr( $url, 0, $end ), '"#%<>[\]^`{|}/?' ) . $ret;
1918 private static function normalizeUrlComponent( $component, $unsafe ) {
1919 $callback = function ( $matches ) use ( $unsafe ) {
1920 $char = urldecode( $matches[0] );
1921 $ord = ord( $char );
1922 if ( $ord > 32 && $ord < 127 && strpos( $unsafe, $char ) === false ) {
1926 # Leave it escaped, but use uppercase for a-f
1927 return strtoupper( $matches[0] );
1930 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/', $callback, $component );
1934 * make an image if it's allowed, either through the global
1935 * option, through the exception, or through the on-wiki whitelist
1937 * @param string $url
1941 private function maybeMakeExternalImage( $url ) {
1942 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1943 $imagesexception = !empty( $imagesfrom );
1945 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1946 if ( $imagesexception && is_array( $imagesfrom ) ) {
1947 $imagematch = false;
1948 foreach ( $imagesfrom as $match ) {
1949 if ( strpos( $url, $match ) === 0 ) {
1954 } elseif ( $imagesexception ) {
1955 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1957 $imagematch = false;
1960 if ( $this->mOptions
->getAllowExternalImages()
1961 ||
( $imagesexception && $imagematch )
1963 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1965 $text = Linker
::makeExternalImage( $url );
1968 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1969 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
1971 $whitelist = explode(
1973 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
1976 foreach ( $whitelist as $entry ) {
1977 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1978 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1981 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1982 # Image matches a whitelist entry
1983 $text = Linker
::makeExternalImage( $url );
1992 * Process [[ ]] wikilinks
1996 * @return string Processed text
2000 public function replaceInternalLinks( $s ) {
2001 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
2006 * Process [[ ]] wikilinks (RIL)
2008 * @throws MWException
2009 * @return LinkHolderArray
2013 public function replaceInternalLinks2( &$s ) {
2014 global $wgExtraInterlanguageLinkPrefixes;
2015 wfProfileIn( __METHOD__
);
2017 wfProfileIn( __METHOD__
. '-setup' );
2018 static $tc = false, $e1, $e1_img;
2019 # the % is needed to support urlencoded titles as well
2021 $tc = Title
::legalChars() . '#%';
2022 # Match a link having the form [[namespace:link|alternate]]trail
2023 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
2024 # Match cases where there is no "]]", which might still be images
2025 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
2028 $holders = new LinkHolderArray( $this );
2030 # split the entire text string on occurrences of [[
2031 $a = StringUtils
::explode( '[[', ' ' . $s );
2032 # get the first element (all text up to first [[), and remove the space we added
2035 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2036 $s = substr( $s, 1 );
2038 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2040 if ( $useLinkPrefixExtension ) {
2041 # Match the end of a line for a word that's not followed by whitespace,
2042 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2044 $charset = $wgContLang->linkPrefixCharset();
2045 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2048 if ( is_null( $this->mTitle
) ) {
2049 wfProfileOut( __METHOD__
. '-setup' );
2050 wfProfileOut( __METHOD__
);
2051 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
2053 $nottalk = !$this->mTitle
->isTalkPage();
2055 if ( $useLinkPrefixExtension ) {
2057 if ( preg_match( $e2, $s, $m ) ) {
2058 $first_prefix = $m[2];
2060 $first_prefix = false;
2066 $useSubpages = $this->areSubpagesAllowed();
2067 wfProfileOut( __METHOD__
. '-setup' );
2069 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
2070 # Loop for each link
2071 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2072 // @codingStandardsIgnoreStart
2074 # Check for excessive memory usage
2075 if ( $holders->isBig() ) {
2077 # Do the existence check, replace the link holders and clear the array
2078 $holders->replace( $s );
2082 if ( $useLinkPrefixExtension ) {
2083 wfProfileIn( __METHOD__
. '-prefixhandling' );
2084 if ( preg_match( $e2, $s, $m ) ) {
2091 if ( $first_prefix ) {
2092 $prefix = $first_prefix;
2093 $first_prefix = false;
2095 wfProfileOut( __METHOD__
. '-prefixhandling' );
2098 $might_be_img = false;
2100 wfProfileIn( __METHOD__
. "-e1" );
2101 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2103 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2104 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2105 # the real problem is with the $e1 regex
2108 # Still some problems for cases where the ] is meant to be outside punctuation,
2109 # and no image is in sight. See bug 2095.
2112 && substr( $m[3], 0, 1 ) === ']'
2113 && strpos( $text, '[' ) !== false
2115 $text .= ']'; # so that replaceExternalLinks($text) works later
2116 $m[3] = substr( $m[3], 1 );
2118 # fix up urlencoded title texts
2119 if ( strpos( $m[1], '%' ) !== false ) {
2120 # Should anchors '#' also be rejected?
2121 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) );
2124 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2125 # Invalid, but might be an image with a link in its caption
2126 $might_be_img = true;
2128 if ( strpos( $m[1], '%' ) !== false ) {
2129 $m[1] = rawurldecode( $m[1] );
2132 } else { # Invalid form; output directly
2133 $s .= $prefix . '[[' . $line;
2134 wfProfileOut( __METHOD__
. "-e1" );
2137 wfProfileOut( __METHOD__
. "-e1" );
2138 wfProfileIn( __METHOD__
. "-misc" );
2142 # Don't allow internal links to pages containing
2143 # PROTO: where PROTO is a valid URL protocol; these
2144 # should be external links.
2145 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $origLink ) ) {
2146 $s .= $prefix . '[[' . $line;
2147 wfProfileOut( __METHOD__
. "-misc" );
2151 # Make subpage if necessary
2152 if ( $useSubpages ) {
2153 $link = $this->maybeDoSubpageLink( $origLink, $text );
2158 $noforce = ( substr( $origLink, 0, 1 ) !== ':' );
2160 # Strip off leading ':'
2161 $link = substr( $link, 1 );
2164 wfProfileOut( __METHOD__
. "-misc" );
2165 wfProfileIn( __METHOD__
. "-title" );
2166 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
2167 if ( $nt === null ) {
2168 $s .= $prefix . '[[' . $line;
2169 wfProfileOut( __METHOD__
. "-title" );
2173 $ns = $nt->getNamespace();
2174 $iw = $nt->getInterwiki();
2175 wfProfileOut( __METHOD__
. "-title" );
2177 if ( $might_be_img ) { # if this is actually an invalid link
2178 wfProfileIn( __METHOD__
. "-might_be_img" );
2179 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2182 # look at the next 'line' to see if we can close it there
2184 $next_line = $a->current();
2185 if ( $next_line === false ||
$next_line === null ) {
2188 $m = explode( ']]', $next_line, 3 );
2189 if ( count( $m ) == 3 ) {
2190 # the first ]] closes the inner link, the second the image
2192 $text .= "[[{$m[0]}]]{$m[1]}";
2195 } elseif ( count( $m ) == 2 ) {
2196 # if there's exactly one ]] that's fine, we'll keep looking
2197 $text .= "[[{$m[0]}]]{$m[1]}";
2199 # if $next_line is invalid too, we need look no further
2200 $text .= '[[' . $next_line;
2205 # we couldn't find the end of this imageLink, so output it raw
2206 # but don't ignore what might be perfectly normal links in the text we've examined
2207 $holders->merge( $this->replaceInternalLinks2( $text ) );
2208 $s .= "{$prefix}[[$link|$text";
2209 # note: no $trail, because without an end, there *is* no trail
2210 wfProfileOut( __METHOD__
. "-might_be_img" );
2213 } else { # it's not an image, so output it raw
2214 $s .= "{$prefix}[[$link|$text";
2215 # note: no $trail, because without an end, there *is* no trail
2216 wfProfileOut( __METHOD__
. "-might_be_img" );
2219 wfProfileOut( __METHOD__
. "-might_be_img" );
2222 $wasblank = ( $text == '' );
2226 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
2227 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2228 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2229 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2230 $text = $this->doQuotes( $text );
2233 # Link not escaped by : , create the various objects
2234 if ( $noforce && !$nt->wasLocalInterwiki() ) {
2236 wfProfileIn( __METHOD__
. "-interwiki" );
2238 $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && (
2239 Language
::fetchLanguageName( $iw, null, 'mw' ) ||
2240 in_array( $iw, $wgExtraInterlanguageLinkPrefixes )
2243 # Bug 24502: filter duplicates
2244 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2245 $this->mLangLinkLanguages
[$iw] = true;
2246 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2249 $s = rtrim( $s . $prefix );
2250 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2251 wfProfileOut( __METHOD__
. "-interwiki" );
2254 wfProfileOut( __METHOD__
. "-interwiki" );
2256 if ( $ns == NS_FILE
) {
2257 wfProfileIn( __METHOD__
. "-image" );
2258 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2260 # if no parameters were passed, $text
2261 # becomes something like "File:Foo.png",
2262 # which we don't want to pass on to the
2266 # recursively parse links inside the image caption
2267 # actually, this will parse them in any other parameters, too,
2268 # but it might be hard to fix that, and it doesn't matter ATM
2269 $text = $this->replaceExternalLinks( $text );
2270 $holders->merge( $this->replaceInternalLinks2( $text ) );
2272 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2273 $s .= $prefix . $this->armorLinks(
2274 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2276 $s .= $prefix . $trail;
2278 wfProfileOut( __METHOD__
. "-image" );
2282 if ( $ns == NS_CATEGORY
) {
2283 wfProfileIn( __METHOD__
. "-category" );
2284 $s = rtrim( $s . "\n" ); # bug 87
2287 $sortkey = $this->getDefaultSort();
2291 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2292 $sortkey = str_replace( "\n", '', $sortkey );
2293 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2294 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2297 * Strip the whitespace Category links produce, see bug 87
2299 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2301 wfProfileOut( __METHOD__
. "-category" );
2306 # Self-link checking. For some languages, variants of the title are checked in
2307 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2308 # for linking to a different variant.
2309 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2310 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2314 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2315 # @todo FIXME: Should do batch file existence checks, see comment below
2316 if ( $ns == NS_MEDIA
) {
2317 wfProfileIn( __METHOD__
. "-media" );
2318 # Give extensions a chance to select the file revision for us
2321 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2322 array( $this, $nt, &$options, &$descQuery ) );
2323 # Fetch and register the file (file title may be different via hooks)
2324 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2325 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2326 $s .= $prefix . $this->armorLinks(
2327 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2328 wfProfileOut( __METHOD__
. "-media" );
2332 wfProfileIn( __METHOD__
. "-always_known" );
2333 # Some titles, such as valid special pages or files in foreign repos, should
2334 # be shown as bluelinks even though they're not included in the page table
2336 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2337 # batch file existence checks for NS_FILE and NS_MEDIA
2338 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2339 $this->mOutput
->addLink( $nt );
2340 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2342 # Links will be added to the output link list after checking
2343 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2345 wfProfileOut( __METHOD__
. "-always_known" );
2347 wfProfileOut( __METHOD__
);
2352 * Render a forced-blue link inline; protect against double expansion of
2353 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2354 * Since this little disaster has to split off the trail text to avoid
2355 * breaking URLs in the following text without breaking trails on the
2356 * wiki links, it's been made into a horrible function.
2359 * @param string $text
2360 * @param array|string $query
2361 * @param string $trail
2362 * @param string $prefix
2363 * @return string HTML-wikitext mix oh yuck
2365 public function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2366 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2368 if ( is_string( $query ) ) {
2369 $query = wfCgiToArray( $query );
2371 if ( $text == '' ) {
2372 $text = htmlspecialchars( $nt->getPrefixedText() );
2375 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2377 return $this->armorLinks( $link ) . $trail;
2381 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2382 * going to go through further parsing steps before inline URL expansion.
2384 * Not needed quite as much as it used to be since free links are a bit
2385 * more sensible these days. But bracketed links are still an issue.
2387 * @param string $text More-or-less HTML
2388 * @return string Less-or-more HTML with NOPARSE bits
2390 public function armorLinks( $text ) {
2391 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2392 "{$this->mUniqPrefix}NOPARSE$1", $text );
2396 * Return true if subpage links should be expanded on this page.
2399 public function areSubpagesAllowed() {
2400 # Some namespaces don't allow subpages
2401 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2405 * Handle link to subpage if necessary
2407 * @param string $target The source of the link
2408 * @param string &$text The link text, modified as necessary
2409 * @return string The full name of the link
2412 public function maybeDoSubpageLink( $target, &$text ) {
2413 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2417 * Used by doBlockLevels()
2422 public function closeParagraph() {
2424 if ( $this->mLastSection
!= '' ) {
2425 $result = '</' . $this->mLastSection
. ">\n";
2427 $this->mInPre
= false;
2428 $this->mLastSection
= '';
2433 * getCommon() returns the length of the longest common substring
2434 * of both arguments, starting at the beginning of both.
2437 * @param string $st1
2438 * @param string $st2
2442 public function getCommon( $st1, $st2 ) {
2443 $fl = strlen( $st1 );
2444 $shorter = strlen( $st2 );
2445 if ( $fl < $shorter ) {
2449 for ( $i = 0; $i < $shorter; ++
$i ) {
2450 if ( $st1[$i] != $st2[$i] ) {
2458 * These next three functions open, continue, and close the list
2459 * element appropriate to the prefix character passed into them.
2462 * @param string $char
2466 public function openList( $char ) {
2467 $result = $this->closeParagraph();
2469 if ( '*' === $char ) {
2470 $result .= "<ul><li>";
2471 } elseif ( '#' === $char ) {
2472 $result .= "<ol><li>";
2473 } elseif ( ':' === $char ) {
2474 $result .= "<dl><dd>";
2475 } elseif ( ';' === $char ) {
2476 $result .= "<dl><dt>";
2477 $this->mDTopen
= true;
2479 $result = '<!-- ERR 1 -->';
2487 * @param string $char
2492 public function nextItem( $char ) {
2493 if ( '*' === $char ||
'#' === $char ) {
2494 return "</li>\n<li>";
2495 } elseif ( ':' === $char ||
';' === $char ) {
2497 if ( $this->mDTopen
) {
2500 if ( ';' === $char ) {
2501 $this->mDTopen
= true;
2502 return $close . '<dt>';
2504 $this->mDTopen
= false;
2505 return $close . '<dd>';
2508 return '<!-- ERR 2 -->';
2513 * @param string $char
2518 public function closeList( $char ) {
2519 if ( '*' === $char ) {
2520 $text = "</li></ul>";
2521 } elseif ( '#' === $char ) {
2522 $text = "</li></ol>";
2523 } elseif ( ':' === $char ) {
2524 if ( $this->mDTopen
) {
2525 $this->mDTopen
= false;
2526 $text = "</dt></dl>";
2528 $text = "</dd></dl>";
2531 return '<!-- ERR 3 -->';
2538 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2540 * @param string $text
2541 * @param bool $linestart Whether or not this is at the start of a line.
2543 * @return string The lists rendered as HTML
2545 public function doBlockLevels( $text, $linestart ) {
2546 wfProfileIn( __METHOD__
);
2548 # Parsing through the text line by line. The main thing
2549 # happening here is handling of block-level elements p, pre,
2550 # and making lists from lines starting with * # : etc.
2552 $textLines = StringUtils
::explode( "\n", $text );
2554 $lastPrefix = $output = '';
2555 $this->mDTopen
= $inBlockElem = false;
2557 $paragraphStack = false;
2558 $inBlockquote = false;
2560 foreach ( $textLines as $oLine ) {
2562 if ( !$linestart ) {
2572 $lastPrefixLength = strlen( $lastPrefix );
2573 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2574 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2575 # If not in a <pre> element, scan for and figure out what prefixes are there.
2576 if ( !$this->mInPre
) {
2577 # Multiple prefixes may abut each other for nested lists.
2578 $prefixLength = strspn( $oLine, '*#:;' );
2579 $prefix = substr( $oLine, 0, $prefixLength );
2582 # ; and : are both from definition-lists, so they're equivalent
2583 # for the purposes of determining whether or not we need to open/close
2585 $prefix2 = str_replace( ';', ':', $prefix );
2586 $t = substr( $oLine, $prefixLength );
2587 $this->mInPre
= (bool)$preOpenMatch;
2589 # Don't interpret any other prefixes in preformatted text
2591 $prefix = $prefix2 = '';
2596 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2597 # Same as the last item, so no need to deal with nesting or opening stuff
2598 $output .= $this->nextItem( substr( $prefix, -1 ) );
2599 $paragraphStack = false;
2601 if ( substr( $prefix, -1 ) === ';' ) {
2602 # The one nasty exception: definition lists work like this:
2603 # ; title : definition text
2604 # So we check for : in the remainder text to split up the
2605 # title and definition, without b0rking links.
2607 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2609 $output .= $term . $this->nextItem( ':' );
2612 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2613 # We need to open or close prefixes, or both.
2615 # Either open or close a level...
2616 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2617 $paragraphStack = false;
2619 # Close all the prefixes which aren't shared.
2620 while ( $commonPrefixLength < $lastPrefixLength ) {
2621 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2622 --$lastPrefixLength;
2625 # Continue the current prefix if appropriate.
2626 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2627 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2630 # Open prefixes where appropriate.
2631 if ( $lastPrefix && $prefixLength > $commonPrefixLength ) {
2634 while ( $prefixLength > $commonPrefixLength ) {
2635 $char = substr( $prefix, $commonPrefixLength, 1 );
2636 $output .= $this->openList( $char );
2638 if ( ';' === $char ) {
2639 # @todo FIXME: This is dupe of code above
2640 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2642 $output .= $term . $this->nextItem( ':' );
2645 ++
$commonPrefixLength;
2647 if ( !$prefixLength && $lastPrefix ) {
2650 $lastPrefix = $prefix2;
2653 # If we have no prefixes, go to paragraph mode.
2654 if ( 0 == $prefixLength ) {
2655 wfProfileIn( __METHOD__
. "-paragraph" );
2656 # No prefix (not in list)--go to paragraph mode
2657 # XXX: use a stack for nestable elements like span, table and div
2658 $openmatch = preg_match(
2659 '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|'
2660 . '<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS',
2663 $closematch = preg_match(
2664 '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'
2665 . '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|<\\/mw:|'
2666 . $this->mUniqPrefix
2667 . '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS',
2671 if ( $openmatch ||
$closematch ) {
2672 $paragraphStack = false;
2673 # @todo bug 5718: paragraph closed
2674 $output .= $this->closeParagraph();
2675 if ( $preOpenMatch && !$preCloseMatch ) {
2676 $this->mInPre
= true;
2679 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t, $bqMatch, PREG_OFFSET_CAPTURE
, $bqOffset ) ) {
2680 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
2681 $bqOffset = $bqMatch[0][1] +
strlen( $bqMatch[0][0] );
2683 $inBlockElem = !$closematch;
2684 } elseif ( !$inBlockElem && !$this->mInPre
) {
2685 if ( ' ' == substr( $t, 0, 1 )
2686 && ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' )
2690 if ( $this->mLastSection
!== 'pre' ) {
2691 $paragraphStack = false;
2692 $output .= $this->closeParagraph() . '<pre>';
2693 $this->mLastSection
= 'pre';
2695 $t = substr( $t, 1 );
2698 if ( trim( $t ) === '' ) {
2699 if ( $paragraphStack ) {
2700 $output .= $paragraphStack . '<br />';
2701 $paragraphStack = false;
2702 $this->mLastSection
= 'p';
2704 if ( $this->mLastSection
!== 'p' ) {
2705 $output .= $this->closeParagraph();
2706 $this->mLastSection
= '';
2707 $paragraphStack = '<p>';
2709 $paragraphStack = '</p><p>';
2713 if ( $paragraphStack ) {
2714 $output .= $paragraphStack;
2715 $paragraphStack = false;
2716 $this->mLastSection
= 'p';
2717 } elseif ( $this->mLastSection
!== 'p' ) {
2718 $output .= $this->closeParagraph() . '<p>';
2719 $this->mLastSection
= 'p';
2724 wfProfileOut( __METHOD__
. "-paragraph" );
2726 # somewhere above we forget to get out of pre block (bug 785)
2727 if ( $preCloseMatch && $this->mInPre
) {
2728 $this->mInPre
= false;
2730 if ( $paragraphStack === false ) {
2732 if ( $prefixLength === 0 ) {
2737 while ( $prefixLength ) {
2738 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2740 if ( !$prefixLength ) {
2744 if ( $this->mLastSection
!= '' ) {
2745 $output .= '</' . $this->mLastSection
. '>';
2746 $this->mLastSection
= '';
2749 wfProfileOut( __METHOD__
);
2754 * Split up a string on ':', ignoring any occurrences inside tags
2755 * to prevent illegal overlapping.
2757 * @param string $str The string to split
2758 * @param string &$before Set to everything before the ':'
2759 * @param string &$after Set to everything after the ':'
2760 * @throws MWException
2761 * @return string The position of the ':', or false if none found
2763 public function findColonNoLinks( $str, &$before, &$after ) {
2764 wfProfileIn( __METHOD__
);
2766 $pos = strpos( $str, ':' );
2767 if ( $pos === false ) {
2769 wfProfileOut( __METHOD__
);
2773 $lt = strpos( $str, '<' );
2774 if ( $lt === false ||
$lt > $pos ) {
2775 # Easy; no tag nesting to worry about
2776 $before = substr( $str, 0, $pos );
2777 $after = substr( $str, $pos +
1 );
2778 wfProfileOut( __METHOD__
);
2782 # Ugly state machine to walk through avoiding tags.
2783 $state = self
::COLON_STATE_TEXT
;
2785 $len = strlen( $str );
2786 for ( $i = 0; $i < $len; $i++
) {
2790 # (Using the number is a performance hack for common cases)
2791 case 0: # self::COLON_STATE_TEXT:
2794 # Could be either a <start> tag or an </end> tag
2795 $state = self
::COLON_STATE_TAGSTART
;
2798 if ( $stack == 0 ) {
2800 $before = substr( $str, 0, $i );
2801 $after = substr( $str, $i +
1 );
2802 wfProfileOut( __METHOD__
);
2805 # Embedded in a tag; don't break it.
2808 # Skip ahead looking for something interesting
2809 $colon = strpos( $str, ':', $i );
2810 if ( $colon === false ) {
2811 # Nothing else interesting
2812 wfProfileOut( __METHOD__
);
2815 $lt = strpos( $str, '<', $i );
2816 if ( $stack === 0 ) {
2817 if ( $lt === false ||
$colon < $lt ) {
2819 $before = substr( $str, 0, $colon );
2820 $after = substr( $str, $colon +
1 );
2821 wfProfileOut( __METHOD__
);
2825 if ( $lt === false ) {
2826 # Nothing else interesting to find; abort!
2827 # We're nested, but there's no close tags left. Abort!
2830 # Skip ahead to next tag start
2832 $state = self
::COLON_STATE_TAGSTART
;
2835 case 1: # self::COLON_STATE_TAG:
2840 $state = self
::COLON_STATE_TEXT
;
2843 # Slash may be followed by >?
2844 $state = self
::COLON_STATE_TAGSLASH
;
2850 case 2: # self::COLON_STATE_TAGSTART:
2853 $state = self
::COLON_STATE_CLOSETAG
;
2856 $state = self
::COLON_STATE_COMMENT
;
2859 # Illegal early close? This shouldn't happen D:
2860 $state = self
::COLON_STATE_TEXT
;
2863 $state = self
::COLON_STATE_TAG
;
2866 case 3: # self::COLON_STATE_CLOSETAG:
2871 wfDebug( __METHOD__
. ": Invalid input; too many close tags\n" );
2872 wfProfileOut( __METHOD__
);
2875 $state = self
::COLON_STATE_TEXT
;
2878 case self
::COLON_STATE_TAGSLASH
:
2880 # Yes, a self-closed tag <blah/>
2881 $state = self
::COLON_STATE_TEXT
;
2883 # Probably we're jumping the gun, and this is an attribute
2884 $state = self
::COLON_STATE_TAG
;
2887 case 5: # self::COLON_STATE_COMMENT:
2889 $state = self
::COLON_STATE_COMMENTDASH
;
2892 case self
::COLON_STATE_COMMENTDASH
:
2894 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2896 $state = self
::COLON_STATE_COMMENT
;
2899 case self
::COLON_STATE_COMMENTDASHDASH
:
2901 $state = self
::COLON_STATE_TEXT
;
2903 $state = self
::COLON_STATE_COMMENT
;
2907 wfProfileOut( __METHOD__
);
2908 throw new MWException( "State machine error in " . __METHOD__
);
2912 wfDebug( __METHOD__
. ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2913 wfProfileOut( __METHOD__
);
2916 wfProfileOut( __METHOD__
);
2921 * Return value of a magic variable (like PAGENAME)
2926 * @param bool|PPFrame $frame
2928 * @throws MWException
2931 public function getVariableValue( $index, $frame = false ) {
2932 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2933 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2935 if ( is_null( $this->mTitle
) ) {
2936 // If no title set, bad things are going to happen
2937 // later. Title should always be set since this
2938 // should only be called in the middle of a parse
2939 // operation (but the unit-tests do funky stuff)
2940 throw new MWException( __METHOD__
. ' Should only be '
2941 . ' called while parsing (no title set)' );
2945 * Some of these require message or data lookups and can be
2946 * expensive to check many times.
2948 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2949 if ( isset( $this->mVarCache
[$index] ) ) {
2950 return $this->mVarCache
[$index];
2954 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2955 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2957 $pageLang = $this->getFunctionLang();
2963 case 'currentmonth':
2964 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ) );
2966 case 'currentmonth1':
2967 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2969 case 'currentmonthname':
2970 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2972 case 'currentmonthnamegen':
2973 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2975 case 'currentmonthabbrev':
2976 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2979 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ) );
2982 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ) );
2985 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ) );
2988 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2990 case 'localmonthname':
2991 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2993 case 'localmonthnamegen':
2994 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2996 case 'localmonthabbrev':
2997 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
3000 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ) );
3003 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ) );
3006 $value = wfEscapeWikiText( $this->mTitle
->getText() );
3009 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
3011 case 'fullpagename':
3012 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
3014 case 'fullpagenamee':
3015 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
3018 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
3020 case 'subpagenamee':
3021 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
3023 case 'rootpagename':
3024 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
3026 case 'rootpagenamee':
3027 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
3030 $this->mTitle
->getRootText()
3033 case 'basepagename':
3034 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
3036 case 'basepagenamee':
3037 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
3040 $this->mTitle
->getBaseText()
3043 case 'talkpagename':
3044 if ( $this->mTitle
->canTalk() ) {
3045 $talkPage = $this->mTitle
->getTalkPage();
3046 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
3051 case 'talkpagenamee':
3052 if ( $this->mTitle
->canTalk() ) {
3053 $talkPage = $this->mTitle
->getTalkPage();
3054 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
3059 case 'subjectpagename':
3060 $subjPage = $this->mTitle
->getSubjectPage();
3061 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
3063 case 'subjectpagenamee':
3064 $subjPage = $this->mTitle
->getSubjectPage();
3065 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
3067 case 'pageid': // requested in bug 23427
3068 $pageid = $this->getTitle()->getArticleID();
3069 if ( $pageid == 0 ) {
3070 # 0 means the page doesn't exist in the database,
3071 # which means the user is previewing a new page.
3072 # The vary-revision flag must be set, because the magic word
3073 # will have a different value once the page is saved.
3074 $this->mOutput
->setFlag( 'vary-revision' );
3075 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
3077 $value = $pageid ?
$pageid : null;
3080 # Let the edit saving system know we should parse the page
3081 # *after* a revision ID has been assigned.
3082 $this->mOutput
->setFlag( 'vary-revision' );
3083 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
3084 $value = $this->mRevisionId
;
3087 # Let the edit saving system know we should parse the page
3088 # *after* a revision ID has been assigned. This is for null edits.
3089 $this->mOutput
->setFlag( 'vary-revision' );
3090 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
3091 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
3093 case 'revisionday2':
3094 # Let the edit saving system know we should parse the page
3095 # *after* a revision ID has been assigned. This is for null edits.
3096 $this->mOutput
->setFlag( 'vary-revision' );
3097 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
3098 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
3100 case 'revisionmonth':
3101 # Let the edit saving system know we should parse the page
3102 # *after* a revision ID has been assigned. This is for null edits.
3103 $this->mOutput
->setFlag( 'vary-revision' );
3104 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
3105 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
3107 case 'revisionmonth1':
3108 # Let the edit saving system know we should parse the page
3109 # *after* a revision ID has been assigned. This is for null edits.
3110 $this->mOutput
->setFlag( 'vary-revision' );
3111 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
3112 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
3114 case 'revisionyear':
3115 # Let the edit saving system know we should parse the page
3116 # *after* a revision ID has been assigned. This is for null edits.
3117 $this->mOutput
->setFlag( 'vary-revision' );
3118 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
3119 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
3121 case 'revisiontimestamp':
3122 # Let the edit saving system know we should parse the page
3123 # *after* a revision ID has been assigned. This is for null edits.
3124 $this->mOutput
->setFlag( 'vary-revision' );
3125 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
3126 $value = $this->getRevisionTimestamp();
3128 case 'revisionuser':
3129 # Let the edit saving system know we should parse the page
3130 # *after* a revision ID has been assigned. This is for null edits.
3131 $this->mOutput
->setFlag( 'vary-revision' );
3132 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
3133 $value = $this->getRevisionUser();
3135 case 'revisionsize':
3136 # Let the edit saving system know we should parse the page
3137 # *after* a revision ID has been assigned. This is for null edits.
3138 $this->mOutput
->setFlag( 'vary-revision' );
3139 wfDebug( __METHOD__
. ": {{REVISIONSIZE}} used, setting vary-revision...\n" );
3140 $value = $this->getRevisionSize();
3143 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3146 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3148 case 'namespacenumber':
3149 $value = $this->mTitle
->getNamespace();
3152 $value = $this->mTitle
->canTalk()
3153 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
3157 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
3159 case 'subjectspace':
3160 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
3162 case 'subjectspacee':
3163 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
3165 case 'currentdayname':
3166 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
3169 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
3172 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
3175 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
3178 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3179 # int to remove the padding
3180 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
3183 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
3185 case 'localdayname':
3186 $value = $pageLang->getWeekdayName(
3187 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
3191 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
3194 $value = $pageLang->time(
3195 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
3201 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
3204 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3205 # int to remove the padding
3206 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
3209 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
3211 case 'numberofarticles':
3212 $value = $pageLang->formatNum( SiteStats
::articles() );
3214 case 'numberoffiles':
3215 $value = $pageLang->formatNum( SiteStats
::images() );
3217 case 'numberofusers':
3218 $value = $pageLang->formatNum( SiteStats
::users() );
3220 case 'numberofactiveusers':
3221 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
3223 case 'numberofpages':
3224 $value = $pageLang->formatNum( SiteStats
::pages() );
3226 case 'numberofadmins':
3227 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
3229 case 'numberofedits':
3230 $value = $pageLang->formatNum( SiteStats
::edits() );
3232 case 'currenttimestamp':
3233 $value = wfTimestamp( TS_MW
, $ts );
3235 case 'localtimestamp':
3236 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
3238 case 'currentversion':
3239 $value = SpecialVersion
::getVersion();
3242 return $wgArticlePath;
3248 return $wgServerName;
3250 return $wgScriptPath;
3252 return $wgStylePath;
3253 case 'directionmark':
3254 return $pageLang->getDirMark();
3255 case 'contentlanguage':
3256 global $wgLanguageCode;
3257 return $wgLanguageCode;
3258 case 'cascadingsources':
3259 $value = CoreParserFunctions
::cascadingsources( $this );
3264 'ParserGetVariableValueSwitch',
3265 array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame )
3272 $this->mVarCache
[$index] = $value;
3279 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3283 public function initialiseVariables() {
3284 wfProfileIn( __METHOD__
);
3285 $variableIDs = MagicWord
::getVariableIDs();
3286 $substIDs = MagicWord
::getSubstIDs();
3288 $this->mVariables
= new MagicWordArray( $variableIDs );
3289 $this->mSubstWords
= new MagicWordArray( $substIDs );
3290 wfProfileOut( __METHOD__
);
3294 * Preprocess some wikitext and return the document tree.
3295 * This is the ghost of replace_variables().
3297 * @param string $text The text to parse
3298 * @param int $flags Bitwise combination of:
3299 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
3300 * included. Default is to assume a direct page view.
3302 * The generated DOM tree must depend only on the input text and the flags.
3303 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3305 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3306 * change in the DOM tree for a given text, must be passed through the section identifier
3307 * in the section edit link and thus back to extractSections().
3309 * The output of this function is currently only cached in process memory, but a persistent
3310 * cache may be implemented at a later date which takes further advantage of these strict
3311 * dependency requirements.
3315 public function preprocessToDom( $text, $flags = 0 ) {
3316 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3321 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3327 public static function splitWhitespace( $s ) {
3328 $ltrimmed = ltrim( $s );
3329 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3330 $trimmed = rtrim( $ltrimmed );
3331 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3333 $w2 = substr( $ltrimmed, -$diff );
3337 return array( $w1, $trimmed, $w2 );
3341 * Replace magic variables, templates, and template arguments
3342 * with the appropriate text. Templates are substituted recursively,
3343 * taking care to avoid infinite loops.
3345 * Note that the substitution depends on value of $mOutputType:
3346 * self::OT_WIKI: only {{subst:}} templates
3347 * self::OT_PREPROCESS: templates but not extension tags
3348 * self::OT_HTML: all templates and extension tags
3350 * @param string $text The text to transform
3351 * @param bool|PPFrame $frame Object describing the arguments passed to the
3352 * template. Arguments may also be provided as an associative array, as
3353 * was the usual case before MW1.12. Providing arguments this way may be
3354 * useful for extensions wishing to perform variable replacement
3356 * @param bool $argsOnly Only do argument (triple-brace) expansion, not
3357 * double-brace expansion.
3360 public function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3361 # Is there any text? Also, Prevent too big inclusions!
3362 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3365 wfProfileIn( __METHOD__
);
3367 if ( $frame === false ) {
3368 $frame = $this->getPreprocessor()->newFrame();
3369 } elseif ( !( $frame instanceof PPFrame
) ) {
3370 wfDebug( __METHOD__
. " called using plain parameters instead of "
3371 . "a PPFrame instance. Creating custom frame.\n" );
3372 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3375 $dom = $this->preprocessToDom( $text );
3376 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3377 $text = $frame->expand( $dom, $flags );
3379 wfProfileOut( __METHOD__
);
3384 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3386 * @param array $args
3390 public static function createAssocArgs( $args ) {
3391 $assocArgs = array();
3393 foreach ( $args as $arg ) {
3394 $eqpos = strpos( $arg, '=' );
3395 if ( $eqpos === false ) {
3396 $assocArgs[$index++
] = $arg;
3398 $name = trim( substr( $arg, 0, $eqpos ) );
3399 $value = trim( substr( $arg, $eqpos +
1 ) );
3400 if ( $value === false ) {
3403 if ( $name !== false ) {
3404 $assocArgs[$name] = $value;
3413 * Warn the user when a parser limitation is reached
3414 * Will warn at most once the user per limitation type
3416 * @param string $limitationType Should be one of:
3417 * 'expensive-parserfunction' (corresponding messages:
3418 * 'expensive-parserfunction-warning',
3419 * 'expensive-parserfunction-category')
3420 * 'post-expand-template-argument' (corresponding messages:
3421 * 'post-expand-template-argument-warning',
3422 * 'post-expand-template-argument-category')
3423 * 'post-expand-template-inclusion' (corresponding messages:
3424 * 'post-expand-template-inclusion-warning',
3425 * 'post-expand-template-inclusion-category')
3426 * 'node-count-exceeded' (corresponding messages:
3427 * 'node-count-exceeded-warning',
3428 * 'node-count-exceeded-category')
3429 * 'expansion-depth-exceeded' (corresponding messages:
3430 * 'expansion-depth-exceeded-warning',
3431 * 'expansion-depth-exceeded-category')
3432 * @param string|int|null $current Current value
3433 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3434 * exceeded, provide the values (optional)
3436 public function limitationWarn( $limitationType, $current = '', $max = '' ) {
3437 # does no harm if $current and $max are present but are unnecessary for the message
3438 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3439 ->inLanguage( $this->mOptions
->getUserLangObj() )->text();
3440 $this->mOutput
->addWarning( $warning );
3441 $this->addTrackingCategory( "$limitationType-category" );
3445 * Return the text of a template, after recursively
3446 * replacing any variables or templates within the template.
3448 * @param array $piece The parts of the template
3449 * $piece['title']: the title, i.e. the part before the |
3450 * $piece['parts']: the parameter array
3451 * $piece['lineStart']: whether the brace was at the start of a line
3452 * @param PPFrame $frame The current frame, contains template arguments
3454 * @return string The text of the template
3456 public function braceSubstitution( $piece, $frame ) {
3457 wfProfileIn( __METHOD__
);
3458 wfProfileIn( __METHOD__
. '-setup' );
3462 // $text has been filled
3464 // wiki markup in $text should be escaped
3466 // $text is HTML, armour it against wikitext transformation
3468 // Force interwiki transclusion to be done in raw mode not rendered
3469 $forceRawInterwiki = false;
3470 // $text is a DOM node needing expansion in a child frame
3471 $isChildObj = false;
3472 // $text is a DOM node needing expansion in the current frame
3473 $isLocalObj = false;
3475 # Title object, where $text came from
3478 # $part1 is the bit before the first |, and must contain only title characters.
3479 # Various prefixes will be stripped from it later.
3480 $titleWithSpaces = $frame->expand( $piece['title'] );
3481 $part1 = trim( $titleWithSpaces );
3484 # Original title text preserved for various purposes
3485 $originalTitle = $part1;
3487 # $args is a list of argument nodes, starting from index 0, not including $part1
3488 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3489 # below won't work b/c this $args isn't an object
3490 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3491 wfProfileOut( __METHOD__
. '-setup' );
3493 $profileSection = null; // profile templates
3496 wfProfileIn( __METHOD__
. '-modifiers' );
3499 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3501 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3502 # Decide whether to expand template or keep wikitext as-is.
3503 if ( $this->ot
['wiki'] ) {
3504 if ( $substMatch === false ) {
3505 $literal = true; # literal when in PST with no prefix
3507 $literal = false; # expand when in PST with subst: or safesubst:
3510 if ( $substMatch == 'subst' ) {
3511 $literal = true; # literal when not in PST with plain subst:
3513 $literal = false; # expand when not in PST with safesubst: or no prefix
3517 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3524 if ( !$found && $args->getLength() == 0 ) {
3525 $id = $this->mVariables
->matchStartToEnd( $part1 );
3526 if ( $id !== false ) {
3527 $text = $this->getVariableValue( $id, $frame );
3528 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3529 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3535 # MSG, MSGNW and RAW
3538 $mwMsgnw = MagicWord
::get( 'msgnw' );
3539 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3542 # Remove obsolete MSG:
3543 $mwMsg = MagicWord
::get( 'msg' );
3544 $mwMsg->matchStartAndRemove( $part1 );
3548 $mwRaw = MagicWord
::get( 'raw' );
3549 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3550 $forceRawInterwiki = true;
3553 wfProfileOut( __METHOD__
. '-modifiers' );
3557 wfProfileIn( __METHOD__
. '-pfunc' );
3559 $colonPos = strpos( $part1, ':' );
3560 if ( $colonPos !== false ) {
3561 $func = substr( $part1, 0, $colonPos );
3562 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3563 for ( $i = 0; $i < $args->getLength(); $i++
) {
3564 $funcArgs[] = $args->item( $i );
3567 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3568 } catch ( Exception
$ex ) {
3569 wfProfileOut( __METHOD__
. '-pfunc' );
3570 wfProfileOut( __METHOD__
);
3574 # The interface for parser functions allows for extracting
3575 # flags into the local scope. Extract any forwarded flags
3579 wfProfileOut( __METHOD__
. '-pfunc' );
3582 # Finish mangling title and then check for loops.
3583 # Set $title to a Title object and $titleText to the PDBK
3586 # Split the title into page and subpage
3588 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3589 if ( $part1 !== $relative ) {
3591 $ns = $this->mTitle
->getNamespace();
3593 $title = Title
::newFromText( $part1, $ns );
3595 $titleText = $title->getPrefixedText();
3596 # Check for language variants if the template is not found
3597 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3598 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3600 # Do recursion depth check
3601 $limit = $this->mOptions
->getMaxTemplateDepth();
3602 if ( $frame->depth
>= $limit ) {
3604 $text = '<span class="error">'
3605 . wfMessage( 'parser-template-recursion-depth-warning' )
3606 ->numParams( $limit )->inContentLanguage()->text()
3612 # Load from database
3613 if ( !$found && $title ) {
3614 $profileSection = $this->mProfiler
->scopedProfileIn( $title->getPrefixedDBkey() );
3615 wfProfileIn( __METHOD__
. '-loadtpl' );
3616 if ( !$title->isExternal() ) {
3617 if ( $title->isSpecialPage()
3618 && $this->mOptions
->getAllowSpecialInclusion()
3619 && $this->ot
['html']
3621 // Pass the template arguments as URL parameters.
3622 // "uselang" will have no effect since the Language object
3623 // is forced to the one defined in ParserOptions.
3624 $pageArgs = array();
3625 $argsLength = $args->getLength();
3626 for ( $i = 0; $i < $argsLength; $i++
) {
3627 $bits = $args->item( $i )->splitArg();
3628 if ( strval( $bits['index'] ) === '' ) {
3629 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3630 $value = trim( $frame->expand( $bits['value'] ) );
3631 $pageArgs[$name] = $value;
3635 // Create a new context to execute the special page
3636 $context = new RequestContext
;
3637 $context->setTitle( $title );
3638 $context->setRequest( new FauxRequest( $pageArgs ) );
3639 $context->setUser( $this->getUser() );
3640 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3641 $ret = SpecialPageFactory
::capturePath( $title, $context );
3643 $text = $context->getOutput()->getHTML();
3644 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3647 $this->disableCache();
3649 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3650 $found = false; # access denied
3651 wfDebug( __METHOD__
. ": template inclusion denied for " .
3652 $title->getPrefixedDBkey() . "\n" );
3654 list( $text, $title ) = $this->getTemplateDom( $title );
3655 if ( $text !== false ) {
3661 # If the title is valid but undisplayable, make a link to it
3662 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3663 $text = "[[:$titleText]]";
3666 } elseif ( $title->isTrans() ) {
3667 # Interwiki transclusion
3668 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3669 $text = $this->interwikiTransclude( $title, 'render' );
3672 $text = $this->interwikiTransclude( $title, 'raw' );
3673 # Preprocess it like a template
3674 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3680 # Do infinite loop check
3681 # This has to be done after redirect resolution to avoid infinite loops via redirects
3682 if ( !$frame->loopCheck( $title ) ) {
3684 $text = '<span class="error">'
3685 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3687 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3689 wfProfileOut( __METHOD__
. '-loadtpl' );
3692 # If we haven't found text to substitute by now, we're done
3693 # Recover the source wikitext and return it
3695 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3696 if ( $profileSection ) {
3697 $this->mProfiler
->scopedProfileOut( $profileSection );
3699 wfProfileOut( __METHOD__
);
3700 return array( 'object' => $text );
3703 # Expand DOM-style return values in a child frame
3704 if ( $isChildObj ) {
3705 # Clean up argument array
3706 $newFrame = $frame->newChild( $args, $title );
3709 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3710 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3711 # Expansion is eligible for the empty-frame cache
3712 $text = $newFrame->cachedExpand( $titleText, $text );
3714 # Uncached expansion
3715 $text = $newFrame->expand( $text );
3718 if ( $isLocalObj && $nowiki ) {
3719 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3720 $isLocalObj = false;
3723 if ( $profileSection ) {
3724 $this->mProfiler
->scopedProfileOut( $profileSection );
3727 # Replace raw HTML by a placeholder
3729 $text = $this->insertStripItem( $text );
3730 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3731 # Escape nowiki-style return values
3732 $text = wfEscapeWikiText( $text );
3733 } elseif ( is_string( $text )
3734 && !$piece['lineStart']
3735 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3737 # Bug 529: if the template begins with a table or block-level
3738 # element, it should be treated as beginning a new line.
3739 # This behavior is somewhat controversial.
3740 $text = "\n" . $text;
3743 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3744 # Error, oversize inclusion
3745 if ( $titleText !== false ) {
3746 # Make a working, properly escaped link if possible (bug 23588)
3747 $text = "[[:$titleText]]";
3749 # This will probably not be a working link, but at least it may
3750 # provide some hint of where the problem is
3751 preg_replace( '/^:/', '', $originalTitle );
3752 $text = "[[:$originalTitle]]";
3754 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3755 . 'post-expand include size too large -->' );
3756 $this->limitationWarn( 'post-expand-template-inclusion' );
3759 if ( $isLocalObj ) {
3760 $ret = array( 'object' => $text );
3762 $ret = array( 'text' => $text );
3765 wfProfileOut( __METHOD__
);
3770 * Call a parser function and return an array with text and flags.
3772 * The returned array will always contain a boolean 'found', indicating
3773 * whether the parser function was found or not. It may also contain the
3775 * text: string|object, resulting wikitext or PP DOM object
3776 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3777 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3778 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3779 * nowiki: bool, wiki markup in $text should be escaped
3782 * @param PPFrame $frame The current frame, contains template arguments
3783 * @param string $function Function name
3784 * @param array $args Arguments to the function
3785 * @throws MWException
3788 public function callParserFunction( $frame, $function, array $args = array() ) {
3791 wfProfileIn( __METHOD__
);
3793 # Case sensitive functions
3794 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3795 $function = $this->mFunctionSynonyms
[1][$function];
3797 # Case insensitive functions
3798 $function = $wgContLang->lc( $function );
3799 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3800 $function = $this->mFunctionSynonyms
[0][$function];
3802 wfProfileOut( __METHOD__
);
3803 return array( 'found' => false );
3807 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3808 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3810 # Workaround for PHP bug 35229 and similar
3811 if ( !is_callable( $callback ) ) {
3812 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3813 wfProfileOut( __METHOD__
);
3814 throw new MWException( "Tag hook for $function is not callable\n" );
3817 $allArgs = array( &$this );
3818 if ( $flags & self
::SFH_OBJECT_ARGS
) {
3819 # Convert arguments to PPNodes and collect for appending to $allArgs
3820 $funcArgs = array();
3821 foreach ( $args as $k => $v ) {
3822 if ( $v instanceof PPNode ||
$k === 0 ) {
3825 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( array( $k => $v ) )->item( 0 );
3829 # Add a frame parameter, and pass the arguments as an array
3830 $allArgs[] = $frame;
3831 $allArgs[] = $funcArgs;
3833 # Convert arguments to plain text and append to $allArgs
3834 foreach ( $args as $k => $v ) {
3835 if ( $v instanceof PPNode
) {
3836 $allArgs[] = trim( $frame->expand( $v ) );
3837 } elseif ( is_int( $k ) && $k >= 0 ) {
3838 $allArgs[] = trim( $v );
3840 $allArgs[] = trim( "$k=$v" );
3845 $result = call_user_func_array( $callback, $allArgs );
3847 # The interface for function hooks allows them to return a wikitext
3848 # string or an array containing the string and any flags. This mungs
3849 # things around to match what this method should return.
3850 if ( !is_array( $result ) ) {
3856 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3857 $result['text'] = $result[0];
3859 unset( $result[0] );
3866 $preprocessFlags = 0;
3867 if ( isset( $result['noparse'] ) ) {
3868 $noparse = $result['noparse'];
3870 if ( isset( $result['preprocessFlags'] ) ) {
3871 $preprocessFlags = $result['preprocessFlags'];
3875 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3876 $result['isChildObj'] = true;
3878 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3879 wfProfileOut( __METHOD__
);
3885 * Get the semi-parsed DOM representation of a template with a given title,
3886 * and its redirect destination title. Cached.
3888 * @param Title $title
3892 public function getTemplateDom( $title ) {
3893 $cacheTitle = $title;
3894 $titleText = $title->getPrefixedDBkey();
3896 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3897 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3898 $title = Title
::makeTitle( $ns, $dbk );
3899 $titleText = $title->getPrefixedDBkey();
3901 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3902 return array( $this->mTplDomCache
[$titleText], $title );
3905 # Cache miss, go to the database
3906 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3908 if ( $text === false ) {
3909 $this->mTplDomCache
[$titleText] = false;
3910 return array( false, $title );
3913 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3914 $this->mTplDomCache
[$titleText] = $dom;
3916 if ( !$title->equals( $cacheTitle ) ) {
3917 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3918 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3921 return array( $dom, $title );
3925 * Fetch the current revision of a given title. Note that the revision
3926 * (and even the title) may not exist in the database, so everything
3927 * contributing to the output of the parser should use this method
3928 * where possible, rather than getting the revisions themselves. This
3929 * method also caches its results, so using it benefits performance.
3932 * @param Title $title
3935 public function fetchCurrentRevisionOfTitle( $title ) {
3936 $cacheKey = $title->getPrefixedDBkey();
3937 if ( !$this->currentRevisionCache
) {
3938 $this->currentRevisionCache
= new MapCacheLRU( 100 );
3940 if ( !$this->currentRevisionCache
->has( $cacheKey ) ) {
3941 $this->currentRevisionCache
->set( $cacheKey,
3942 // Defaults to Parser::statelessFetchRevision()
3943 call_user_func( $this->mOptions
->getCurrentRevisionCallback(), $title, $this )
3946 return $this->currentRevisionCache
->get( $cacheKey );
3950 * Wrapper around Revision::newFromTitle to allow passing additional parameters
3951 * without passing them on to it.
3954 * @param Title $title
3955 * @param Parser|bool $parser
3958 public static function statelessFetchRevision( $title, $parser = false ) {
3959 return Revision
::newFromTitle( $title );
3963 * Fetch the unparsed text of a template and register a reference to it.
3964 * @param Title $title
3965 * @return array ( string or false, Title )
3967 public function fetchTemplateAndTitle( $title ) {
3968 // Defaults to Parser::statelessFetchTemplate()
3969 $templateCb = $this->mOptions
->getTemplateCallback();
3970 $stuff = call_user_func( $templateCb, $title, $this );
3971 $text = $stuff['text'];
3972 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3973 if ( isset( $stuff['deps'] ) ) {
3974 foreach ( $stuff['deps'] as $dep ) {
3975 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3976 if ( $dep['title']->equals( $this->getTitle() ) ) {
3977 // If we transclude ourselves, the final result
3978 // will change based on the new version of the page
3979 $this->mOutput
->setFlag( 'vary-revision' );
3983 return array( $text, $finalTitle );
3987 * Fetch the unparsed text of a template and register a reference to it.
3988 * @param Title $title
3989 * @return string|bool
3991 public function fetchTemplate( $title ) {
3992 $rv = $this->fetchTemplateAndTitle( $title );
3997 * Static function to get a template
3998 * Can be overridden via ParserOptions::setTemplateCallback().
4000 * @param Title $title
4001 * @param bool|Parser $parser
4005 public static function statelessFetchTemplate( $title, $parser = false ) {
4006 $text = $skip = false;
4007 $finalTitle = $title;
4010 # Loop to fetch the article, with up to 1 redirect
4011 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
4012 # Give extensions a chance to select the revision instead
4013 $id = false; # Assume current
4014 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
4015 array( $parser, $title, &$skip, &$id ) );
4021 'page_id' => $title->getArticleID(),
4028 $rev = Revision
::newFromId( $id );
4029 } elseif ( $parser ) {
4030 $rev = $parser->fetchCurrentRevisionOfTitle( $title );
4032 $rev = Revision
::newFromTitle( $title );
4034 $rev_id = $rev ?
$rev->getId() : 0;
4035 # If there is no current revision, there is no page
4036 if ( $id === false && !$rev ) {
4037 $linkCache = LinkCache
::singleton();
4038 $linkCache->addBadLinkObj( $title );
4043 'page_id' => $title->getArticleID(),
4044 'rev_id' => $rev_id );
4045 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
4046 # We fetched a rev from a different title; register it too...
4048 'title' => $rev->getTitle(),
4049 'page_id' => $rev->getPage(),
4050 'rev_id' => $rev_id );
4054 $content = $rev->getContent();
4055 $text = $content ?
$content->getWikitextForTransclusion() : null;
4057 if ( $text === false ||
$text === null ) {
4061 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
4063 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
4064 if ( !$message->exists() ) {
4068 $content = $message->content();
4069 $text = $message->plain();
4077 $finalTitle = $title;
4078 $title = $content->getRedirectTarget();
4082 'finalTitle' => $finalTitle,
4087 * Fetch a file and its title and register a reference to it.
4088 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4089 * @param Title $title
4090 * @param array $options Array of options to RepoGroup::findFile
4093 public function fetchFile( $title, $options = array() ) {
4094 $res = $this->fetchFileAndTitle( $title, $options );
4099 * Fetch a file and its title and register a reference to it.
4100 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4101 * @param Title $title
4102 * @param array $options Array of options to RepoGroup::findFile
4103 * @return array ( File or false, Title of file )
4105 public function fetchFileAndTitle( $title, $options = array() ) {
4106 $file = $this->fetchFileNoRegister( $title, $options );
4108 $time = $file ?
$file->getTimestamp() : false;
4109 $sha1 = $file ?
$file->getSha1() : false;
4110 # Register the file as a dependency...
4111 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4112 if ( $file && !$title->equals( $file->getTitle() ) ) {
4113 # Update fetched file title
4114 $title = $file->getTitle();
4115 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4117 return array( $file, $title );
4121 * Helper function for fetchFileAndTitle.
4123 * Also useful if you need to fetch a file but not use it yet,
4124 * for example to get the file's handler.
4126 * @param Title $title
4127 * @param array $options Array of options to RepoGroup::findFile
4130 protected function fetchFileNoRegister( $title, $options = array() ) {
4131 if ( isset( $options['broken'] ) ) {
4132 $file = false; // broken thumbnail forced by hook
4133 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
4134 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
4135 } else { // get by (name,timestamp)
4136 $file = wfFindFile( $title, $options );
4142 * Transclude an interwiki link.
4144 * @param Title $title
4145 * @param string $action
4149 public function interwikiTransclude( $title, $action ) {
4150 global $wgEnableScaryTranscluding;
4152 if ( !$wgEnableScaryTranscluding ) {
4153 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
4156 $url = $title->getFullURL( array( 'action' => $action ) );
4158 if ( strlen( $url ) > 255 ) {
4159 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
4161 return $this->fetchScaryTemplateMaybeFromCache( $url );
4165 * @param string $url
4166 * @return mixed|string
4168 public function fetchScaryTemplateMaybeFromCache( $url ) {
4169 global $wgTranscludeCacheExpiry;
4170 $dbr = wfGetDB( DB_SLAVE
);
4171 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
4172 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
4173 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
4175 return $obj->tc_contents
;
4178 $req = MWHttpRequest
::factory( $url );
4179 $status = $req->execute(); // Status object
4180 if ( $status->isOK() ) {
4181 $text = $req->getContent();
4182 } elseif ( $req->getStatus() != 200 ) {
4183 // Though we failed to fetch the content, this status is useless.
4184 return wfMessage( 'scarytranscludefailed-httpstatus' )
4185 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
4187 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
4190 $dbw = wfGetDB( DB_MASTER
);
4191 $dbw->replace( 'transcache', array( 'tc_url' ), array(
4193 'tc_time' => $dbw->timestamp( time() ),
4194 'tc_contents' => $text
4200 * Triple brace replacement -- used for template arguments
4203 * @param array $piece
4204 * @param PPFrame $frame
4208 public function argSubstitution( $piece, $frame ) {
4209 wfProfileIn( __METHOD__
);
4212 $parts = $piece['parts'];
4213 $nameWithSpaces = $frame->expand( $piece['title'] );
4214 $argName = trim( $nameWithSpaces );
4216 $text = $frame->getArgument( $argName );
4217 if ( $text === false && $parts->getLength() > 0
4218 && ( $this->ot
['html']
4220 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
4223 # No match in frame, use the supplied default
4224 $object = $parts->item( 0 )->getChildren();
4226 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
4227 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
4228 $this->limitationWarn( 'post-expand-template-argument' );
4231 if ( $text === false && $object === false ) {
4233 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
4235 if ( $error !== false ) {
4238 if ( $object !== false ) {
4239 $ret = array( 'object' => $object );
4241 $ret = array( 'text' => $text );
4244 wfProfileOut( __METHOD__
);
4249 * Return the text to be used for a given extension tag.
4250 * This is the ghost of strip().
4252 * @param array $params Associative array of parameters:
4253 * name PPNode for the tag name
4254 * attr PPNode for unparsed text where tag attributes are thought to be
4255 * attributes Optional associative array of parsed attributes
4256 * inner Contents of extension element
4257 * noClose Original text did not have a close tag
4258 * @param PPFrame $frame
4260 * @throws MWException
4263 public function extensionSubstitution( $params, $frame ) {
4264 $name = $frame->expand( $params['name'] );
4265 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
4266 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
4267 $marker = "{$this->mUniqPrefix}-$name-"
4268 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
4270 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
4271 ( $this->ot
['html'] ||
$this->ot
['pre'] );
4272 if ( $isFunctionTag ) {
4273 $markerType = 'none';
4275 $markerType = 'general';
4277 if ( $this->ot
['html'] ||
$isFunctionTag ) {
4278 $name = strtolower( $name );
4279 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
4280 if ( isset( $params['attributes'] ) ) {
4281 $attributes = $attributes +
$params['attributes'];
4284 if ( isset( $this->mTagHooks
[$name] ) ) {
4285 # Workaround for PHP bug 35229 and similar
4286 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
4287 throw new MWException( "Tag hook for $name is not callable\n" );
4289 $output = call_user_func_array( $this->mTagHooks
[$name],
4290 array( $content, $attributes, $this, $frame ) );
4291 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
4292 list( $callback, ) = $this->mFunctionTagHooks
[$name];
4293 if ( !is_callable( $callback ) ) {
4294 throw new MWException( "Tag hook for $name is not callable\n" );
4297 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
4299 $output = '<span class="error">Invalid tag extension name: ' .
4300 htmlspecialchars( $name ) . '</span>';
4303 if ( is_array( $output ) ) {
4304 # Extract flags to local scope (to override $markerType)
4306 $output = $flags[0];
4311 if ( is_null( $attrText ) ) {
4314 if ( isset( $params['attributes'] ) ) {
4315 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4316 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4317 htmlspecialchars( $attrValue ) . '"';
4320 if ( $content === null ) {
4321 $output = "<$name$attrText/>";
4323 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4324 $output = "<$name$attrText>$content$close";
4328 if ( $markerType === 'none' ) {
4330 } elseif ( $markerType === 'nowiki' ) {
4331 $this->mStripState
->addNoWiki( $marker, $output );
4332 } elseif ( $markerType === 'general' ) {
4333 $this->mStripState
->addGeneral( $marker, $output );
4335 throw new MWException( __METHOD__
. ': invalid marker type' );
4341 * Increment an include size counter
4343 * @param string $type The type of expansion
4344 * @param int $size The size of the text
4345 * @return bool False if this inclusion would take it over the maximum, true otherwise
4347 public function incrementIncludeSize( $type, $size ) {
4348 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4351 $this->mIncludeSizes
[$type] +
= $size;
4357 * Increment the expensive function count
4359 * @return bool False if the limit has been exceeded
4361 public function incrementExpensiveFunctionCount() {
4362 $this->mExpensiveFunctionCount++
;
4363 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4367 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4368 * Fills $this->mDoubleUnderscores, returns the modified text
4370 * @param string $text
4374 public function doDoubleUnderscore( $text ) {
4375 wfProfileIn( __METHOD__
);
4377 # The position of __TOC__ needs to be recorded
4378 $mw = MagicWord
::get( 'toc' );
4379 if ( $mw->match( $text ) ) {
4380 $this->mShowToc
= true;
4381 $this->mForceTocPosition
= true;
4383 # Set a placeholder. At the end we'll fill it in with the TOC.
4384 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4386 # Only keep the first one.
4387 $text = $mw->replace( '', $text );
4390 # Now match and remove the rest of them
4391 $mwa = MagicWord
::getDoubleUnderscoreArray();
4392 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4394 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4395 $this->mOutput
->mNoGallery
= true;
4397 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4398 $this->mShowToc
= false;
4400 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4401 && $this->mTitle
->getNamespace() == NS_CATEGORY
4403 $this->addTrackingCategory( 'hidden-category-category' );
4405 # (bug 8068) Allow control over whether robots index a page.
4407 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4408 # is not desirable, the last one on the page should win.
4409 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4410 $this->mOutput
->setIndexPolicy( 'noindex' );
4411 $this->addTrackingCategory( 'noindex-category' );
4413 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4414 $this->mOutput
->setIndexPolicy( 'index' );
4415 $this->addTrackingCategory( 'index-category' );
4418 # Cache all double underscores in the database
4419 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4420 $this->mOutput
->setProperty( $key, '' );
4423 wfProfileOut( __METHOD__
);
4428 * @see ParserOutput::addTrackingCategory()
4429 * @param string $msg Message key
4430 * @return bool Whether the addition was successful
4432 public function addTrackingCategory( $msg ) {
4433 return $this->mOutput
->addTrackingCategory( $msg, $this->mTitle
);
4437 * This function accomplishes several tasks:
4438 * 1) Auto-number headings if that option is enabled
4439 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4440 * 3) Add a Table of contents on the top for users who have enabled the option
4441 * 4) Auto-anchor headings
4443 * It loops through all headlines, collects the necessary data, then splits up the
4444 * string and re-inserts the newly formatted headlines.
4446 * @param string $text
4447 * @param string $origText Original, untouched wikitext
4448 * @param bool $isMain
4449 * @return mixed|string
4452 public function formatHeadings( $text, $origText, $isMain = true ) {
4453 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4455 # Inhibit editsection links if requested in the page
4456 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4457 $maybeShowEditLink = $showEditLink = false;
4459 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4460 $showEditLink = $this->mOptions
->getEditSection();
4462 if ( $showEditLink ) {
4463 $this->mOutput
->setEditSectionTokens( true );
4466 # Get all headlines for numbering them and adding funky stuff like [edit]
4467 # links - this is for later, but we need the number of headlines right now
4469 $numMatches = preg_match_all(
4470 '/<H(?P<level>[1-6])(?P<attrib>.*?' . '>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i',
4475 # if there are fewer than 4 headlines in the article, do not show TOC
4476 # unless it's been explicitly enabled.
4477 $enoughToc = $this->mShowToc
&&
4478 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4480 # Allow user to stipulate that a page should have a "new section"
4481 # link added via __NEWSECTIONLINK__
4482 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4483 $this->mOutput
->setNewSection( true );
4486 # Allow user to remove the "new section"
4487 # link via __NONEWSECTIONLINK__
4488 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4489 $this->mOutput
->hideNewSection( true );
4492 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4493 # override above conditions and always show TOC above first header
4494 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4495 $this->mShowToc
= true;
4503 # Ugh .. the TOC should have neat indentation levels which can be
4504 # passed to the skin functions. These are determined here
4508 $sublevelCount = array();
4509 $levelCount = array();
4514 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4515 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4516 $oldType = $this->mOutputType
;
4517 $this->setOutputType( self
::OT_WIKI
);
4518 $frame = $this->getPreprocessor()->newFrame();
4519 $root = $this->preprocessToDom( $origText );
4520 $node = $root->getFirstChild();
4525 foreach ( $matches[3] as $headline ) {
4526 $isTemplate = false;
4528 $sectionIndex = false;
4530 $markerMatches = array();
4531 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4532 $serial = $markerMatches[1];
4533 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4534 $isTemplate = ( $titleText != $baseTitleText );
4535 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4539 $prevlevel = $level;
4541 $level = $matches[1][$headlineCount];
4543 if ( $level > $prevlevel ) {
4544 # Increase TOC level
4546 $sublevelCount[$toclevel] = 0;
4547 if ( $toclevel < $wgMaxTocLevel ) {
4548 $prevtoclevel = $toclevel;
4549 $toc .= Linker
::tocIndent();
4552 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4553 # Decrease TOC level, find level to jump to
4555 for ( $i = $toclevel; $i > 0; $i-- ) {
4556 if ( $levelCount[$i] == $level ) {
4557 # Found last matching level
4560 } elseif ( $levelCount[$i] < $level ) {
4561 # Found first matching level below current level
4569 if ( $toclevel < $wgMaxTocLevel ) {
4570 if ( $prevtoclevel < $wgMaxTocLevel ) {
4571 # Unindent only if the previous toc level was shown :p
4572 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4573 $prevtoclevel = $toclevel;
4575 $toc .= Linker
::tocLineEnd();
4579 # No change in level, end TOC line
4580 if ( $toclevel < $wgMaxTocLevel ) {
4581 $toc .= Linker
::tocLineEnd();
4585 $levelCount[$toclevel] = $level;
4587 # count number of headlines for each level
4588 $sublevelCount[$toclevel]++
;
4590 for ( $i = 1; $i <= $toclevel; $i++
) {
4591 if ( !empty( $sublevelCount[$i] ) ) {
4595 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4600 # The safe header is a version of the header text safe to use for links
4602 # Remove link placeholders by the link text.
4603 # <!--LINK number-->
4605 # link text with suffix
4606 # Do this before unstrip since link text can contain strip markers
4607 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4609 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4610 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4612 # Strip out HTML (first regex removes any tag not allowed)
4614 # * <sup> and <sub> (bug 8393)
4617 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4619 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4620 # to allow setting directionality in toc items.
4621 $tocline = preg_replace(
4623 '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?' . '>#',
4624 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?' . '>#'
4626 array( '', '<$1>' ),
4629 $tocline = trim( $tocline );
4631 # For the anchor, strip out HTML-y stuff period
4632 $safeHeadline = preg_replace( '/<.*?' . '>/', '', $safeHeadline );
4633 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4635 # Save headline for section edit hint before it's escaped
4636 $headlineHint = $safeHeadline;
4638 if ( $wgExperimentalHtmlIds ) {
4639 # For reverse compatibility, provide an id that's
4640 # HTML4-compatible, like we used to.
4642 # It may be worth noting, academically, that it's possible for
4643 # the legacy anchor to conflict with a non-legacy headline
4644 # anchor on the page. In this case likely the "correct" thing
4645 # would be to either drop the legacy anchors or make sure
4646 # they're numbered first. However, this would require people
4647 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4648 # manually, so let's not bother worrying about it.
4649 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4650 array( 'noninitial', 'legacy' ) );
4651 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4653 if ( $legacyHeadline == $safeHeadline ) {
4654 # No reason to have both (in fact, we can't)
4655 $legacyHeadline = false;
4658 $legacyHeadline = false;
4659 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4663 # HTML names must be case-insensitively unique (bug 10721).
4664 # This does not apply to Unicode characters per
4665 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4666 # @todo FIXME: We may be changing them depending on the current locale.
4667 $arrayKey = strtolower( $safeHeadline );
4668 if ( $legacyHeadline === false ) {
4669 $legacyArrayKey = false;
4671 $legacyArrayKey = strtolower( $legacyHeadline );
4674 # count how many in assoc. array so we can track dupes in anchors
4675 if ( isset( $refers[$arrayKey] ) ) {
4676 $refers[$arrayKey]++
;
4678 $refers[$arrayKey] = 1;
4680 if ( isset( $refers[$legacyArrayKey] ) ) {
4681 $refers[$legacyArrayKey]++
;
4683 $refers[$legacyArrayKey] = 1;
4686 # Don't number the heading if it is the only one (looks silly)
4687 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4688 # the two are different if the line contains a link
4689 $headline = Html
::element(
4691 array( 'class' => 'mw-headline-number' ),
4693 ) . ' ' . $headline;
4696 # Create the anchor for linking from the TOC to the section
4697 $anchor = $safeHeadline;
4698 $legacyAnchor = $legacyHeadline;
4699 if ( $refers[$arrayKey] > 1 ) {
4700 $anchor .= '_' . $refers[$arrayKey];
4702 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4703 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4705 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4706 $toc .= Linker
::tocLine( $anchor, $tocline,
4707 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4710 # Add the section to the section tree
4711 # Find the DOM node for this header
4712 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4713 while ( $node && !$noOffset ) {
4714 if ( $node->getName() === 'h' ) {
4715 $bits = $node->splitHeading();
4716 if ( $bits['i'] == $sectionIndex ) {
4720 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4721 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4722 $node = $node->getNextSibling();
4725 'toclevel' => $toclevel,
4728 'number' => $numbering,
4729 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4730 'fromtitle' => $titleText,
4731 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4732 'anchor' => $anchor,
4735 # give headline the correct <h#> tag
4736 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4737 // Output edit section links as markers with styles that can be customized by skins
4738 if ( $isTemplate ) {
4739 # Put a T flag in the section identifier, to indicate to extractSections()
4740 # that sections inside <includeonly> should be counted.
4741 $editsectionPage = $titleText;
4742 $editsectionSection = "T-$sectionIndex";
4743 $editsectionContent = null;
4745 $editsectionPage = $this->mTitle
->getPrefixedText();
4746 $editsectionSection = $sectionIndex;
4747 $editsectionContent = $headlineHint;
4749 // We use a bit of pesudo-xml for editsection markers. The
4750 // language converter is run later on. Using a UNIQ style marker
4751 // leads to the converter screwing up the tokens when it
4752 // converts stuff. And trying to insert strip tags fails too. At
4753 // this point all real inputted tags have already been escaped,
4754 // so we don't have to worry about a user trying to input one of
4755 // these markers directly. We use a page and section attribute
4756 // to stop the language converter from converting these
4757 // important bits of data, but put the headline hint inside a
4758 // content block because the language converter is supposed to
4759 // be able to convert that piece of data.
4760 // Gets replaced with html in ParserOutput::getText
4761 $editlink = '<mw:editsection page="' . htmlspecialchars( $editsectionPage );
4762 $editlink .= '" section="' . htmlspecialchars( $editsectionSection ) . '"';
4763 if ( $editsectionContent !== null ) {
4764 $editlink .= '>' . $editsectionContent . '</mw:editsection>';
4771 $head[$headlineCount] = Linker
::makeHeadline( $level,
4772 $matches['attrib'][$headlineCount], $anchor, $headline,
4773 $editlink, $legacyAnchor );
4778 $this->setOutputType( $oldType );
4780 # Never ever show TOC if no headers
4781 if ( $numVisible < 1 ) {
4786 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4787 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4789 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4790 $this->mOutput
->setTOCHTML( $toc );
4791 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4792 $this->mOutput
->addModules( 'mediawiki.toc' );
4796 $this->mOutput
->setSections( $tocraw );
4799 # split up and insert constructed headlines
4800 $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text );
4803 // build an array of document sections
4804 $sections = array();
4805 foreach ( $blocks as $block ) {
4806 // $head is zero-based, sections aren't.
4807 if ( empty( $head[$i - 1] ) ) {
4808 $sections[$i] = $block;
4810 $sections[$i] = $head[$i - 1] . $block;
4814 * Send a hook, one per section.
4815 * The idea here is to be able to make section-level DIVs, but to do so in a
4816 * lower-impact, more correct way than r50769
4819 * $section : the section number
4820 * &$sectionContent : ref to the content of the section
4821 * $showEditLinks : boolean describing whether this section has an edit link
4823 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4828 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4829 // append the TOC at the beginning
4830 // Top anchor now in skin
4831 $sections[0] = $sections[0] . $toc . "\n";
4834 $full .= join( '', $sections );
4836 if ( $this->mForceTocPosition
) {
4837 return str_replace( '<!--MWTOC-->', $toc, $full );
4844 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4845 * conversion, substituting signatures, {{subst:}} templates, etc.
4847 * @param string $text The text to transform
4848 * @param Title $title The Title object for the current article
4849 * @param User $user The User object describing the current user
4850 * @param ParserOptions $options Parsing options
4851 * @param bool $clearState Whether to clear the parser state first
4852 * @return string The altered wiki markup
4854 public function preSaveTransform( $text, Title
$title, User
$user,
4855 ParserOptions
$options, $clearState = true
4857 if ( $clearState ) {
4858 $magicScopeVariable = $this->lock();
4860 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4861 $this->setUser( $user );
4866 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4867 if ( $options->getPreSaveTransform() ) {
4868 $text = $this->pstPass2( $text, $user );
4870 $text = $this->mStripState
->unstripBoth( $text );
4872 $this->setUser( null ); #Reset
4878 * Pre-save transform helper function
4880 * @param string $text
4885 private function pstPass2( $text, $user ) {
4888 # Note: This is the timestamp saved as hardcoded wikitext to
4889 # the database, we use $wgContLang here in order to give
4890 # everyone the same signature and use the default one rather
4891 # than the one selected in each user's preferences.
4892 # (see also bug 12815)
4893 $ts = $this->mOptions
->getTimestamp();
4894 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4895 $ts = $timestamp->format( 'YmdHis' );
4896 $tzMsg = $timestamp->format( 'T' ); # might vary on DST changeover!
4898 # Allow translation of timezones through wiki. format() can return
4899 # whatever crap the system uses, localised or not, so we cannot
4900 # ship premade translations.
4901 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4902 $msg = wfMessage( $key )->inContentLanguage();
4903 if ( $msg->exists() ) {
4904 $tzMsg = $msg->text();
4907 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4909 # Variable replacement
4910 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4911 $text = $this->replaceVariables( $text );
4913 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4914 # which may corrupt this parser instance via its wfMessage()->text() call-
4917 $sigText = $this->getUserSig( $user );
4918 $text = strtr( $text, array(
4920 '~~~~' => "$sigText $d",
4924 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4925 $tc = '[' . Title
::legalChars() . ']';
4926 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4928 // [[ns:page (context)|]]
4929 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4930 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4931 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4932 // [[ns:page (context), context|]] (using either single or double-width comma)
4933 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4934 // [[|page]] (reverse pipe trick: add context from page title)
4935 $p2 = "/\[\[\\|($tc+)]]/";
4937 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4938 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4939 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4940 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4942 $t = $this->mTitle
->getText();
4944 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4945 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4946 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4947 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4949 # if there's no context, don't bother duplicating the title
4950 $text = preg_replace( $p2, '[[\\1]]', $text );
4953 # Trim trailing whitespace
4954 $text = rtrim( $text );
4960 * Fetch the user's signature text, if any, and normalize to
4961 * validated, ready-to-insert wikitext.
4962 * If you have pre-fetched the nickname or the fancySig option, you can
4963 * specify them here to save a database query.
4964 * Do not reuse this parser instance after calling getUserSig(),
4965 * as it may have changed if it's the $wgParser.
4968 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4969 * @param bool|null $fancySig whether the nicknname is the complete signature
4970 * or null to use default value
4973 public function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4974 global $wgMaxSigChars;
4976 $username = $user->getName();
4978 # If not given, retrieve from the user object.
4979 if ( $nickname === false ) {
4980 $nickname = $user->getOption( 'nickname' );
4983 if ( is_null( $fancySig ) ) {
4984 $fancySig = $user->getBoolOption( 'fancysig' );
4987 $nickname = $nickname == null ?
$username : $nickname;
4989 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4990 $nickname = $username;
4991 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4992 } elseif ( $fancySig !== false ) {
4993 # Sig. might contain markup; validate this
4994 if ( $this->validateSig( $nickname ) !== false ) {
4995 # Validated; clean up (if needed) and return it
4996 return $this->cleanSig( $nickname, true );
4998 # Failed to validate; fall back to the default
4999 $nickname = $username;
5000 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
5004 # Make sure nickname doesnt get a sig in a sig
5005 $nickname = self
::cleanSigInSig( $nickname );
5007 # If we're still here, make it a link to the user page
5008 $userText = wfEscapeWikiText( $username );
5009 $nickText = wfEscapeWikiText( $nickname );
5010 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
5012 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
5013 ->title( $this->getTitle() )->text();
5017 * Check that the user's signature contains no bad XML
5019 * @param string $text
5020 * @return string|bool An expanded string, or false if invalid.
5022 public function validateSig( $text ) {
5023 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
5027 * Clean up signature text
5029 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
5030 * 2) Substitute all transclusions
5032 * @param string $text
5033 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
5034 * @return string Signature text
5036 public function cleanSig( $text, $parsing = false ) {
5039 $magicScopeVariable = $this->lock();
5040 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
5043 # Option to disable this feature
5044 if ( !$this->mOptions
->getCleanSignatures() ) {
5048 # @todo FIXME: Regex doesn't respect extension tags or nowiki
5049 # => Move this logic to braceSubstitution()
5050 $substWord = MagicWord
::get( 'subst' );
5051 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
5052 $substText = '{{' . $substWord->getSynonym( 0 );
5054 $text = preg_replace( $substRegex, $substText, $text );
5055 $text = self
::cleanSigInSig( $text );
5056 $dom = $this->preprocessToDom( $text );
5057 $frame = $this->getPreprocessor()->newFrame();
5058 $text = $frame->expand( $dom );
5061 $text = $this->mStripState
->unstripBoth( $text );
5068 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
5070 * @param string $text
5071 * @return string Signature text with /~{3,5}/ removed
5073 public static function cleanSigInSig( $text ) {
5074 $text = preg_replace( '/~{3,5}/', '', $text );
5079 * Set up some variables which are usually set up in parse()
5080 * so that an external function can call some class members with confidence
5082 * @param Title|null $title
5083 * @param ParserOptions $options
5084 * @param int $outputType
5085 * @param bool $clearState
5087 public function startExternalParse( Title
$title = null, ParserOptions
$options,
5088 $outputType, $clearState = true
5090 $this->startParse( $title, $options, $outputType, $clearState );
5094 * @param Title|null $title
5095 * @param ParserOptions $options
5096 * @param int $outputType
5097 * @param bool $clearState
5099 private function startParse( Title
$title = null, ParserOptions
$options,
5100 $outputType, $clearState = true
5102 $this->setTitle( $title );
5103 $this->mOptions
= $options;
5104 $this->setOutputType( $outputType );
5105 if ( $clearState ) {
5106 $this->clearState();
5111 * Wrapper for preprocess()
5113 * @param string $text The text to preprocess
5114 * @param ParserOptions $options Options
5115 * @param Title|null $title Title object or null to use $wgTitle
5118 public function transformMsg( $text, $options, $title = null ) {
5119 static $executing = false;
5121 # Guard against infinite recursion
5127 wfProfileIn( __METHOD__
);
5133 $text = $this->preprocess( $text, $title, $options );
5136 wfProfileOut( __METHOD__
);
5141 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
5142 * The callback should have the following form:
5143 * function myParserHook( $text, $params, $parser, $frame ) { ... }
5145 * Transform and return $text. Use $parser for any required context, e.g. use
5146 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
5148 * Hooks may return extended information by returning an array, of which the
5149 * first numbered element (index 0) must be the return string, and all other
5150 * entries are extracted into local variables within an internal function
5151 * in the Parser class.
5153 * This interface (introduced r61913) appears to be undocumented, but
5154 * 'markerName' is used by some core tag hooks to override which strip
5155 * array their results are placed in. **Use great caution if attempting
5156 * this interface, as it is not documented and injudicious use could smash
5157 * private variables.**
5159 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5160 * @param callable $callback The callback function (and object) to use for the tag
5161 * @throws MWException
5162 * @return callable|null The old value of the mTagHooks array associated with the hook
5164 public function setHook( $tag, $callback ) {
5165 $tag = strtolower( $tag );
5166 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5167 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
5169 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
5170 $this->mTagHooks
[$tag] = $callback;
5171 if ( !in_array( $tag, $this->mStripList
) ) {
5172 $this->mStripList
[] = $tag;
5179 * As setHook(), but letting the contents be parsed.
5181 * Transparent tag hooks are like regular XML-style tag hooks, except they
5182 * operate late in the transformation sequence, on HTML instead of wikitext.
5184 * This is probably obsoleted by things dealing with parser frames?
5185 * The only extension currently using it is geoserver.
5188 * @todo better document or deprecate this
5190 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5191 * @param callable $callback The callback function (and object) to use for the tag
5192 * @throws MWException
5193 * @return callable|null The old value of the mTagHooks array associated with the hook
5195 public function setTransparentTagHook( $tag, $callback ) {
5196 $tag = strtolower( $tag );
5197 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5198 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
5200 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
5201 $this->mTransparentTagHooks
[$tag] = $callback;
5207 * Remove all tag hooks
5209 public function clearTagHooks() {
5210 $this->mTagHooks
= array();
5211 $this->mFunctionTagHooks
= array();
5212 $this->mStripList
= $this->mDefaultStripList
;
5216 * Create a function, e.g. {{sum:1|2|3}}
5217 * The callback function should have the form:
5218 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
5220 * Or with Parser::SFH_OBJECT_ARGS:
5221 * function myParserFunction( $parser, $frame, $args ) { ... }
5223 * The callback may either return the text result of the function, or an array with the text
5224 * in element 0, and a number of flags in the other elements. The names of the flags are
5225 * specified in the keys. Valid flags are:
5226 * found The text returned is valid, stop processing the template. This
5228 * nowiki Wiki markup in the return value should be escaped
5229 * isHTML The returned text is HTML, armour it against wikitext transformation
5231 * @param string $id The magic word ID
5232 * @param callable $callback The callback function (and object) to use
5233 * @param int $flags A combination of the following flags:
5234 * Parser::SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
5236 * Parser::SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text.
5237 * This allows for conditional expansion of the parse tree, allowing you to eliminate dead
5238 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
5239 * the arguments, and to control the way they are expanded.
5241 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
5242 * arguments, for instance:
5243 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
5245 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
5246 * future versions. Please call $frame->expand() on it anyway so that your code keeps
5247 * working if/when this is changed.
5249 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
5252 * Please read the documentation in includes/parser/Preprocessor.php for more information
5253 * about the methods available in PPFrame and PPNode.
5255 * @throws MWException
5256 * @return string|callable The old callback function for this name, if any
5258 public function setFunctionHook( $id, $callback, $flags = 0 ) {
5261 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
5262 $this->mFunctionHooks
[$id] = array( $callback, $flags );
5264 # Add to function cache
5265 $mw = MagicWord
::get( $id );
5267 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
5270 $synonyms = $mw->getSynonyms();
5271 $sensitive = intval( $mw->isCaseSensitive() );
5273 foreach ( $synonyms as $syn ) {
5275 if ( !$sensitive ) {
5276 $syn = $wgContLang->lc( $syn );
5279 if ( !( $flags & self
::SFH_NO_HASH
) ) {
5282 # Remove trailing colon
5283 if ( substr( $syn, -1, 1 ) === ':' ) {
5284 $syn = substr( $syn, 0, -1 );
5286 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
5292 * Get all registered function hook identifiers
5296 public function getFunctionHooks() {
5297 return array_keys( $this->mFunctionHooks
);
5301 * Create a tag function, e.g. "<test>some stuff</test>".
5302 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5303 * Unlike parser functions, their content is not preprocessed.
5304 * @param string $tag
5305 * @param callable $callback
5307 * @throws MWException
5310 public function setFunctionTagHook( $tag, $callback, $flags ) {
5311 $tag = strtolower( $tag );
5312 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5313 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5315 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
5316 $this->mFunctionTagHooks
[$tag] : null;
5317 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
5319 if ( !in_array( $tag, $this->mStripList
) ) {
5320 $this->mStripList
[] = $tag;
5327 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
5328 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5329 * Placeholders created in Skin::makeLinkObj()
5331 * @param string $text
5332 * @param int $options
5334 public function replaceLinkHolders( &$text, $options = 0 ) {
5335 $this->mLinkHolders
->replace( $text );
5339 * Replace "<!--LINK-->" link placeholders with plain text of links
5340 * (not HTML-formatted).
5342 * @param string $text
5345 public function replaceLinkHoldersText( $text ) {
5346 return $this->mLinkHolders
->replaceText( $text );
5350 * Renders an image gallery from a text with one line per image.
5351 * text labels may be given by using |-style alternative text. E.g.
5352 * Image:one.jpg|The number "1"
5353 * Image:tree.jpg|A tree
5354 * given as text will return the HTML of a gallery with two images,
5355 * labeled 'The number "1"' and
5358 * @param string $text
5359 * @param array $params
5360 * @return string HTML
5362 public function renderImageGallery( $text, $params ) {
5363 wfProfileIn( __METHOD__
);
5366 if ( isset( $params['mode'] ) ) {
5367 $mode = $params['mode'];
5371 $ig = ImageGalleryBase
::factory( $mode );
5372 } catch ( MWException
$e ) {
5373 // If invalid type set, fallback to default.
5374 $ig = ImageGalleryBase
::factory( false );
5377 $ig->setContextTitle( $this->mTitle
);
5378 $ig->setShowBytes( false );
5379 $ig->setShowFilename( false );
5380 $ig->setParser( $this );
5381 $ig->setHideBadImages();
5382 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
5384 if ( isset( $params['showfilename'] ) ) {
5385 $ig->setShowFilename( true );
5387 $ig->setShowFilename( false );
5389 if ( isset( $params['caption'] ) ) {
5390 $caption = $params['caption'];
5391 $caption = htmlspecialchars( $caption );
5392 $caption = $this->replaceInternalLinks( $caption );
5393 $ig->setCaptionHtml( $caption );
5395 if ( isset( $params['perrow'] ) ) {
5396 $ig->setPerRow( $params['perrow'] );
5398 if ( isset( $params['widths'] ) ) {
5399 $ig->setWidths( $params['widths'] );
5401 if ( isset( $params['heights'] ) ) {
5402 $ig->setHeights( $params['heights'] );
5404 $ig->setAdditionalOptions( $params );
5406 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5408 $lines = StringUtils
::explode( "\n", $text );
5409 foreach ( $lines as $line ) {
5410 # match lines like these:
5411 # Image:someimage.jpg|This is some image
5413 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5415 if ( count( $matches ) == 0 ) {
5419 if ( strpos( $matches[0], '%' ) !== false ) {
5420 $matches[1] = rawurldecode( $matches[1] );
5422 $title = Title
::newFromText( $matches[1], NS_FILE
);
5423 if ( is_null( $title ) ) {
5424 # Bogus title. Ignore these so we don't bomb out later.
5428 # We need to get what handler the file uses, to figure out parameters.
5429 # Note, a hook can overide the file name, and chose an entirely different
5430 # file (which potentially could be of a different type and have different handler).
5433 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5434 array( $this, $title, &$options, &$descQuery ) );
5435 # Don't register it now, as ImageGallery does that later.
5436 $file = $this->fetchFileNoRegister( $title, $options );
5437 $handler = $file ?
$file->getHandler() : false;
5439 wfProfileIn( __METHOD__
. '-getMagicWord' );
5441 'img_alt' => 'gallery-internal-alt',
5442 'img_link' => 'gallery-internal-link',
5445 $paramMap = $paramMap +
$handler->getParamMap();
5446 // We don't want people to specify per-image widths.
5447 // Additionally the width parameter would need special casing anyhow.
5448 unset( $paramMap['img_width'] );
5451 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5452 wfProfileOut( __METHOD__
. '-getMagicWord' );
5457 $handlerOptions = array();
5458 if ( isset( $matches[3] ) ) {
5459 // look for an |alt= definition while trying not to break existing
5460 // captions with multiple pipes (|) in it, until a more sensible grammar
5461 // is defined for images in galleries
5463 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5464 // splitting on '|' is a bit odd, and different from makeImage.
5465 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5466 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
5468 foreach ( $parameterMatches as $parameterMatch ) {
5469 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5471 $paramName = $paramMap[$magicName];
5473 switch ( $paramName ) {
5474 case 'gallery-internal-alt':
5475 $alt = $this->stripAltText( $match, false );
5477 case 'gallery-internal-link':
5478 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5479 $chars = self
::EXT_LINK_URL_CLASS
;
5480 $prots = $this->mUrlProtocols
;
5481 //check to see if link matches an absolute url, if not then it must be a wiki link.
5482 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5485 $localLinkTitle = Title
::newFromText( $linkValue );
5486 if ( $localLinkTitle !== null ) {
5487 $link = $localLinkTitle->getLinkURL();
5492 // Must be a handler specific parameter.
5493 if ( $handler->validateParam( $paramName, $match ) ) {
5494 $handlerOptions[$paramName] = $match;
5496 // Guess not. Append it to the caption.
5497 wfDebug( "$parameterMatch failed parameter validation\n" );
5498 $label .= '|' . $parameterMatch;
5503 // concatenate all other pipes
5504 $label .= '|' . $parameterMatch;
5507 // remove the first pipe
5508 $label = substr( $label, 1 );
5511 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5513 $html = $ig->toHTML();
5514 wfRunHooks( 'AfterParserFetchFileAndTitle', array( $this, $ig, &$html ) );
5515 wfProfileOut( __METHOD__
);
5520 * @param string $handler
5523 public function getImageParams( $handler ) {
5525 $handlerClass = get_class( $handler );
5529 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5530 # Initialise static lists
5531 static $internalParamNames = array(
5532 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5533 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5534 'bottom', 'text-bottom' ),
5535 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5536 'upright', 'border', 'link', 'alt', 'class' ),
5538 static $internalParamMap;
5539 if ( !$internalParamMap ) {
5540 $internalParamMap = array();
5541 foreach ( $internalParamNames as $type => $names ) {
5542 foreach ( $names as $name ) {
5543 $magicName = str_replace( '-', '_', "img_$name" );
5544 $internalParamMap[$magicName] = array( $type, $name );
5549 # Add handler params
5550 $paramMap = $internalParamMap;
5552 $handlerParamMap = $handler->getParamMap();
5553 foreach ( $handlerParamMap as $magic => $paramName ) {
5554 $paramMap[$magic] = array( 'handler', $paramName );
5557 $this->mImageParams
[$handlerClass] = $paramMap;
5558 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5560 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5564 * Parse image options text and use it to make an image
5566 * @param Title $title
5567 * @param string $options
5568 * @param LinkHolderArray|bool $holders
5569 * @return string HTML
5571 public function makeImage( $title, $options, $holders = false ) {
5572 # Check if the options text is of the form "options|alt text"
5574 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5575 # * left no resizing, just left align. label is used for alt= only
5576 # * right same, but right aligned
5577 # * none same, but not aligned
5578 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5579 # * center center the image
5580 # * frame Keep original image size, no magnify-button.
5581 # * framed Same as "frame"
5582 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5583 # * upright reduce width for upright images, rounded to full __0 px
5584 # * border draw a 1px border around the image
5585 # * alt Text for HTML alt attribute (defaults to empty)
5586 # * class Set a class for img node
5587 # * link Set the target of the image link. Can be external, interwiki, or local
5588 # vertical-align values (no % or length right now):
5598 $parts = StringUtils
::explode( "|", $options );
5600 # Give extensions a chance to select the file revision for us
5603 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5604 array( $this, $title, &$options, &$descQuery ) );
5605 # Fetch and register the file (file title may be different via hooks)
5606 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5609 $handler = $file ?
$file->getHandler() : false;
5611 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5614 $this->addTrackingCategory( 'broken-file-category' );
5617 # Process the input parameters
5619 $params = array( 'frame' => array(), 'handler' => array(),
5620 'horizAlign' => array(), 'vertAlign' => array() );
5621 $seenformat = false;
5622 foreach ( $parts as $part ) {
5623 $part = trim( $part );
5624 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5626 if ( isset( $paramMap[$magicName] ) ) {
5627 list( $type, $paramName ) = $paramMap[$magicName];
5629 # Special case; width and height come in one variable together
5630 if ( $type === 'handler' && $paramName === 'width' ) {
5631 $parsedWidthParam = $this->parseWidthParam( $value );
5632 if ( isset( $parsedWidthParam['width'] ) ) {
5633 $width = $parsedWidthParam['width'];
5634 if ( $handler->validateParam( 'width', $width ) ) {
5635 $params[$type]['width'] = $width;
5639 if ( isset( $parsedWidthParam['height'] ) ) {
5640 $height = $parsedWidthParam['height'];
5641 if ( $handler->validateParam( 'height', $height ) ) {
5642 $params[$type]['height'] = $height;
5646 # else no validation -- bug 13436
5648 if ( $type === 'handler' ) {
5649 # Validate handler parameter
5650 $validated = $handler->validateParam( $paramName, $value );
5652 # Validate internal parameters
5653 switch ( $paramName ) {
5657 # @todo FIXME: Possibly check validity here for
5658 # manualthumb? downstream behavior seems odd with
5659 # missing manual thumbs.
5661 $value = $this->stripAltText( $value, $holders );
5664 $chars = self
::EXT_LINK_URL_CLASS
;
5665 $prots = $this->mUrlProtocols
;
5666 if ( $value === '' ) {
5667 $paramName = 'no-link';
5670 } elseif ( preg_match( "/^((?i)$prots)/", $value ) ) {
5671 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5672 $paramName = 'link-url';
5673 $this->mOutput
->addExternalLink( $value );
5674 if ( $this->mOptions
->getExternalLinkTarget() ) {
5675 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5680 $linkTitle = Title
::newFromText( $value );
5682 $paramName = 'link-title';
5683 $value = $linkTitle;
5684 $this->mOutput
->addLink( $linkTitle );
5692 // use first appearing option, discard others.
5693 $validated = ! $seenformat;
5697 # Most other things appear to be empty or numeric...
5698 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5703 $params[$type][$paramName] = $value;
5707 if ( !$validated ) {
5712 # Process alignment parameters
5713 if ( $params['horizAlign'] ) {
5714 $params['frame']['align'] = key( $params['horizAlign'] );
5716 if ( $params['vertAlign'] ) {
5717 $params['frame']['valign'] = key( $params['vertAlign'] );
5720 $params['frame']['caption'] = $caption;
5722 # Will the image be presented in a frame, with the caption below?
5723 $imageIsFramed = isset( $params['frame']['frame'] )
5724 ||
isset( $params['frame']['framed'] )
5725 ||
isset( $params['frame']['thumbnail'] )
5726 ||
isset( $params['frame']['manualthumb'] );
5728 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5729 # came to also set the caption, ordinary text after the image -- which
5730 # makes no sense, because that just repeats the text multiple times in
5731 # screen readers. It *also* came to set the title attribute.
5733 # Now that we have an alt attribute, we should not set the alt text to
5734 # equal the caption: that's worse than useless, it just repeats the
5735 # text. This is the framed/thumbnail case. If there's no caption, we
5736 # use the unnamed parameter for alt text as well, just for the time be-
5737 # ing, if the unnamed param is set and the alt param is not.
5739 # For the future, we need to figure out if we want to tweak this more,
5740 # e.g., introducing a title= parameter for the title; ignoring the un-
5741 # named parameter entirely for images without a caption; adding an ex-
5742 # plicit caption= parameter and preserving the old magic unnamed para-
5744 if ( $imageIsFramed ) { # Framed image
5745 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5746 # No caption or alt text, add the filename as the alt text so
5747 # that screen readers at least get some description of the image
5748 $params['frame']['alt'] = $title->getText();
5750 # Do not set $params['frame']['title'] because tooltips don't make sense
5752 } else { # Inline image
5753 if ( !isset( $params['frame']['alt'] ) ) {
5754 # No alt text, use the "caption" for the alt text
5755 if ( $caption !== '' ) {
5756 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5758 # No caption, fall back to using the filename for the
5760 $params['frame']['alt'] = $title->getText();
5763 # Use the "caption" for the tooltip text
5764 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5767 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5769 # Linker does the rest
5770 $time = isset( $options['time'] ) ?
$options['time'] : false;
5771 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5772 $time, $descQuery, $this->mOptions
->getThumbSize() );
5774 # Give the handler a chance to modify the parser object
5776 $handler->parserTransformHook( $this, $file );
5783 * @param string $caption
5784 * @param LinkHolderArray|bool $holders
5785 * @return mixed|string
5787 protected function stripAltText( $caption, $holders ) {
5788 # Strip bad stuff out of the title (tooltip). We can't just use
5789 # replaceLinkHoldersText() here, because if this function is called
5790 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5792 $tooltip = $holders->replaceText( $caption );
5794 $tooltip = $this->replaceLinkHoldersText( $caption );
5797 # make sure there are no placeholders in thumbnail attributes
5798 # that are later expanded to html- so expand them now and
5800 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5801 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5807 * Set a flag in the output object indicating that the content is dynamic and
5808 * shouldn't be cached.
5810 public function disableCache() {
5811 wfDebug( "Parser output marked as uncacheable.\n" );
5812 if ( !$this->mOutput
) {
5813 throw new MWException( __METHOD__
.
5814 " can only be called when actually parsing something" );
5816 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5817 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5821 * Callback from the Sanitizer for expanding items found in HTML attribute
5822 * values, so they can be safely tested and escaped.
5824 * @param string $text
5825 * @param bool|PPFrame $frame
5828 public function attributeStripCallback( &$text, $frame = false ) {
5829 $text = $this->replaceVariables( $text, $frame );
5830 $text = $this->mStripState
->unstripBoth( $text );
5839 public function getTags() {
5841 array_keys( $this->mTransparentTagHooks
),
5842 array_keys( $this->mTagHooks
),
5843 array_keys( $this->mFunctionTagHooks
)
5848 * Replace transparent tags in $text with the values given by the callbacks.
5850 * Transparent tag hooks are like regular XML-style tag hooks, except they
5851 * operate late in the transformation sequence, on HTML instead of wikitext.
5853 * @param string $text
5857 public function replaceTransparentTags( $text ) {
5859 $elements = array_keys( $this->mTransparentTagHooks
);
5860 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5861 $replacements = array();
5863 foreach ( $matches as $marker => $data ) {
5864 list( $element, $content, $params, $tag ) = $data;
5865 $tagName = strtolower( $element );
5866 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5867 $output = call_user_func_array(
5868 $this->mTransparentTagHooks
[$tagName],
5869 array( $content, $params, $this )
5874 $replacements[$marker] = $output;
5876 return strtr( $text, $replacements );
5880 * Break wikitext input into sections, and either pull or replace
5881 * some particular section's text.
5883 * External callers should use the getSection and replaceSection methods.
5885 * @param string $text Page wikitext
5886 * @param string|number $sectionId A section identifier string of the form:
5887 * "<flag1> - <flag2> - ... - <section number>"
5889 * Currently the only recognised flag is "T", which means the target section number
5890 * was derived during a template inclusion parse, in other words this is a template
5891 * section edit link. If no flags are given, it was an ordinary section edit link.
5892 * This flag is required to avoid a section numbering mismatch when a section is
5893 * enclosed by "<includeonly>" (bug 6563).
5895 * The section number 0 pulls the text before the first heading; other numbers will
5896 * pull the given section along with its lower-level subsections. If the section is
5897 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5899 * Section 0 is always considered to exist, even if it only contains the empty
5900 * string. If $text is the empty string and section 0 is replaced, $newText is
5903 * @param string $mode One of "get" or "replace"
5904 * @param string $newText Replacement text for section data.
5905 * @return string For "get", the extracted section text.
5906 * for "replace", the whole page with the section replaced.
5908 private function extractSections( $text, $sectionId, $mode, $newText = '' ) {
5909 global $wgTitle; # not generally used but removes an ugly failure mode
5911 $magicScopeVariable = $this->lock();
5912 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5914 $frame = $this->getPreprocessor()->newFrame();
5916 # Process section extraction flags
5918 $sectionParts = explode( '-', $sectionId );
5919 $sectionIndex = array_pop( $sectionParts );
5920 foreach ( $sectionParts as $part ) {
5921 if ( $part === 'T' ) {
5922 $flags |
= self
::PTD_FOR_INCLUSION
;
5926 # Check for empty input
5927 if ( strval( $text ) === '' ) {
5928 # Only sections 0 and T-0 exist in an empty document
5929 if ( $sectionIndex == 0 ) {
5930 if ( $mode === 'get' ) {
5936 if ( $mode === 'get' ) {
5944 # Preprocess the text
5945 $root = $this->preprocessToDom( $text, $flags );
5947 # <h> nodes indicate section breaks
5948 # They can only occur at the top level, so we can find them by iterating the root's children
5949 $node = $root->getFirstChild();
5951 # Find the target section
5952 if ( $sectionIndex == 0 ) {
5953 # Section zero doesn't nest, level=big
5954 $targetLevel = 1000;
5957 if ( $node->getName() === 'h' ) {
5958 $bits = $node->splitHeading();
5959 if ( $bits['i'] == $sectionIndex ) {
5960 $targetLevel = $bits['level'];
5964 if ( $mode === 'replace' ) {
5965 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5967 $node = $node->getNextSibling();
5973 if ( $mode === 'get' ) {
5980 # Find the end of the section, including nested sections
5982 if ( $node->getName() === 'h' ) {
5983 $bits = $node->splitHeading();
5984 $curLevel = $bits['level'];
5985 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5989 if ( $mode === 'get' ) {
5990 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5992 $node = $node->getNextSibling();
5995 # Write out the remainder (in replace mode only)
5996 if ( $mode === 'replace' ) {
5997 # Output the replacement text
5998 # Add two newlines on -- trailing whitespace in $newText is conventionally
5999 # stripped by the editor, so we need both newlines to restore the paragraph gap
6000 # Only add trailing whitespace if there is newText
6001 if ( $newText != "" ) {
6002 $outText .= $newText . "\n\n";
6006 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
6007 $node = $node->getNextSibling();
6011 if ( is_string( $outText ) ) {
6012 # Re-insert stripped tags
6013 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
6020 * This function returns the text of a section, specified by a number ($section).
6021 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
6022 * the first section before any such heading (section 0).
6024 * If a section contains subsections, these are also returned.
6026 * @param string $text Text to look in
6027 * @param string|number $sectionId Section identifier as a number or string
6028 * (e.g. 0, 1 or 'T-1').
6029 * @param string $defaultText Default to return if section is not found
6031 * @return string Text of the requested section
6033 public function getSection( $text, $sectionId, $defaultText = '' ) {
6034 return $this->extractSections( $text, $sectionId, 'get', $defaultText );
6038 * This function returns $oldtext after the content of the section
6039 * specified by $section has been replaced with $text. If the target
6040 * section does not exist, $oldtext is returned unchanged.
6042 * @param string $oldText Former text of the article
6043 * @param string|number $sectionId Section identifier as a number or string
6044 * (e.g. 0, 1 or 'T-1').
6045 * @param string $newText Replacing text
6047 * @return string Modified text
6049 public function replaceSection( $oldText, $sectionId, $newText ) {
6050 return $this->extractSections( $oldText, $sectionId, 'replace', $newText );
6054 * Get the ID of the revision we are parsing
6058 public function getRevisionId() {
6059 return $this->mRevisionId
;
6063 * Get the revision object for $this->mRevisionId
6065 * @return Revision|null Either a Revision object or null
6066 * @since 1.23 (public since 1.23)
6068 public function getRevisionObject() {
6069 if ( !is_null( $this->mRevisionObject
) ) {
6070 return $this->mRevisionObject
;
6072 if ( is_null( $this->mRevisionId
) ) {
6076 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
6077 return $this->mRevisionObject
;
6081 * Get the timestamp associated with the current revision, adjusted for
6082 * the default server-local timestamp
6085 public function getRevisionTimestamp() {
6086 if ( is_null( $this->mRevisionTimestamp
) ) {
6087 wfProfileIn( __METHOD__
);
6091 $revObject = $this->getRevisionObject();
6092 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
6094 # The cryptic '' timezone parameter tells to use the site-default
6095 # timezone offset instead of the user settings.
6097 # Since this value will be saved into the parser cache, served
6098 # to other users, and potentially even used inside links and such,
6099 # it needs to be consistent for all visitors.
6100 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
6102 wfProfileOut( __METHOD__
);
6104 return $this->mRevisionTimestamp
;
6108 * Get the name of the user that edited the last revision
6110 * @return string User name
6112 public function getRevisionUser() {
6113 if ( is_null( $this->mRevisionUser
) ) {
6114 $revObject = $this->getRevisionObject();
6116 # if this template is subst: the revision id will be blank,
6117 # so just use the current user's name
6119 $this->mRevisionUser
= $revObject->getUserText();
6120 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6121 $this->mRevisionUser
= $this->getUser()->getName();
6124 return $this->mRevisionUser
;
6128 * Get the size of the revision
6130 * @return int|null Revision size
6132 public function getRevisionSize() {
6133 if ( is_null( $this->mRevisionSize
) ) {
6134 $revObject = $this->getRevisionObject();
6136 # if this variable is subst: the revision id will be blank,
6137 # so just use the parser input size, because the own substituation
6138 # will change the size.
6140 $this->mRevisionSize
= $revObject->getSize();
6141 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6142 $this->mRevisionSize
= $this->mInputSize
;
6145 return $this->mRevisionSize
;
6149 * Mutator for $mDefaultSort
6151 * @param string $sort New value
6153 public function setDefaultSort( $sort ) {
6154 $this->mDefaultSort
= $sort;
6155 $this->mOutput
->setProperty( 'defaultsort', $sort );
6159 * Accessor for $mDefaultSort
6160 * Will use the empty string if none is set.
6162 * This value is treated as a prefix, so the
6163 * empty string is equivalent to sorting by
6168 public function getDefaultSort() {
6169 if ( $this->mDefaultSort
!== false ) {
6170 return $this->mDefaultSort
;
6177 * Accessor for $mDefaultSort
6178 * Unlike getDefaultSort(), will return false if none is set
6180 * @return string|bool
6182 public function getCustomDefaultSort() {
6183 return $this->mDefaultSort
;
6187 * Try to guess the section anchor name based on a wikitext fragment
6188 * presumably extracted from a heading, for example "Header" from
6191 * @param string $text
6195 public function guessSectionNameFromWikiText( $text ) {
6196 # Strip out wikitext links(they break the anchor)
6197 $text = $this->stripSectionName( $text );
6198 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6199 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
6203 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6204 * instead. For use in redirects, since IE6 interprets Redirect: headers
6205 * as something other than UTF-8 (apparently?), resulting in breakage.
6207 * @param string $text The section name
6208 * @return string An anchor
6210 public function guessLegacySectionNameFromWikiText( $text ) {
6211 # Strip out wikitext links(they break the anchor)
6212 $text = $this->stripSectionName( $text );
6213 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6214 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
6218 * Strips a text string of wikitext for use in a section anchor
6220 * Accepts a text string and then removes all wikitext from the
6221 * string and leaves only the resultant text (i.e. the result of
6222 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6223 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6224 * to create valid section anchors by mimicing the output of the
6225 * parser when headings are parsed.
6227 * @param string $text Text string to be stripped of wikitext
6228 * for use in a Section anchor
6229 * @return string Filtered text string
6231 public function stripSectionName( $text ) {
6232 # Strip internal link markup
6233 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6234 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6236 # Strip external link markup
6237 # @todo FIXME: Not tolerant to blank link text
6238 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6239 # on how many empty links there are on the page - need to figure that out.
6240 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6242 # Parse wikitext quotes (italics & bold)
6243 $text = $this->doQuotes( $text );
6246 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
6251 * strip/replaceVariables/unstrip for preprocessor regression testing
6253 * @param string $text
6254 * @param Title $title
6255 * @param ParserOptions $options
6256 * @param int $outputType
6260 public function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
6261 $magicScopeVariable = $this->lock();
6262 $this->startParse( $title, $options, $outputType, true );
6264 $text = $this->replaceVariables( $text );
6265 $text = $this->mStripState
->unstripBoth( $text );
6266 $text = Sanitizer
::removeHTMLtags( $text );
6271 * @param string $text
6272 * @param Title $title
6273 * @param ParserOptions $options
6276 public function testPst( $text, Title
$title, ParserOptions
$options ) {
6277 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6281 * @param string $text
6282 * @param Title $title
6283 * @param ParserOptions $options
6286 public function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
6287 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
6291 * Call a callback function on all regions of the given text that are not
6292 * inside strip markers, and replace those regions with the return value
6293 * of the callback. For example, with input:
6297 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6298 * two strings will be replaced with the value returned by the callback in
6302 * @param callable $callback
6306 public function markerSkipCallback( $s, $callback ) {
6309 while ( $i < strlen( $s ) ) {
6310 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
6311 if ( $markerStart === false ) {
6312 $out .= call_user_func( $callback, substr( $s, $i ) );
6315 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6316 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6317 if ( $markerEnd === false ) {
6318 $out .= substr( $s, $markerStart );
6321 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6322 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6331 * Remove any strip markers found in the given text.
6333 * @param string $text Input string
6336 public function killMarkers( $text ) {
6337 return $this->mStripState
->killMarkers( $text );
6341 * Save the parser state required to convert the given half-parsed text to
6342 * HTML. "Half-parsed" in this context means the output of
6343 * recursiveTagParse() or internalParse(). This output has strip markers
6344 * from replaceVariables (extensionSubstitution() etc.), and link
6345 * placeholders from replaceLinkHolders().
6347 * Returns an array which can be serialized and stored persistently. This
6348 * array can later be loaded into another parser instance with
6349 * unserializeHalfParsedText(). The text can then be safely incorporated into
6350 * the return value of a parser hook.
6352 * @param string $text
6356 public function serializeHalfParsedText( $text ) {
6357 wfProfileIn( __METHOD__
);
6360 'version' => self
::HALF_PARSED_VERSION
,
6361 'stripState' => $this->mStripState
->getSubState( $text ),
6362 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6364 wfProfileOut( __METHOD__
);
6369 * Load the parser state given in the $data array, which is assumed to
6370 * have been generated by serializeHalfParsedText(). The text contents is
6371 * extracted from the array, and its markers are transformed into markers
6372 * appropriate for the current Parser instance. This transformed text is
6373 * returned, and can be safely included in the return value of a parser
6376 * If the $data array has been stored persistently, the caller should first
6377 * check whether it is still valid, by calling isValidHalfParsedText().
6379 * @param array $data Serialized data
6380 * @throws MWException
6383 public function unserializeHalfParsedText( $data ) {
6384 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6385 throw new MWException( __METHOD__
. ': invalid version' );
6388 # First, extract the strip state.
6389 $texts = array( $data['text'] );
6390 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6392 # Now renumber links
6393 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6395 # Should be good to go.
6400 * Returns true if the given array, presumed to be generated by
6401 * serializeHalfParsedText(), is compatible with the current version of the
6404 * @param array $data
6408 public function isValidHalfParsedText( $data ) {
6409 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6413 * Parsed a width param of imagelink like 300px or 200x300px
6415 * @param string $value
6420 public function parseWidthParam( $value ) {
6421 $parsedWidthParam = array();
6422 if ( $value === '' ) {
6423 return $parsedWidthParam;
6426 # (bug 13500) In both cases (width/height and width only),
6427 # permit trailing "px" for backward compatibility.
6428 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6429 $width = intval( $m[1] );
6430 $height = intval( $m[2] );
6431 $parsedWidthParam['width'] = $width;
6432 $parsedWidthParam['height'] = $height;
6433 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6434 $width = intval( $value );
6435 $parsedWidthParam['width'] = $width;
6437 return $parsedWidthParam;
6441 * Lock the current instance of the parser.
6443 * This is meant to stop someone from calling the parser
6444 * recursively and messing up all the strip state.
6446 * @throws MWException If parser is in a parse
6447 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6449 protected function lock() {
6450 if ( $this->mInParse
) {
6451 throw new MWException( "Parser state cleared while parsing. "
6452 . "Did you call Parser::parse recursively?" );
6454 $this->mInParse
= true;
6457 $recursiveCheck = new ScopedCallback( function() use ( $that ) {
6458 $that->mInParse
= false;
6461 return $recursiveCheck;
6465 * Strip outer <p></p> tag from the HTML source of a single paragraph.
6467 * Returns original HTML if the <p/> tag has any attributes, if there's no wrapping <p/> tag,
6468 * or if there is more than one <p/> tag in the input HTML.
6470 * @param string $html
6474 public static function stripOuterParagraph( $html ) {
6476 if ( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $html, $m ) ) {
6477 if ( strpos( $m[1], '</p>' ) === false ) {
6486 * Return this parser if it is not doing anything, otherwise
6487 * get a fresh parser. You can use this method by doing
6488 * $myParser = $wgParser->getFreshParser(), or more simply
6489 * $wgParser->getFreshParser()->parse( ... );
6490 * if you're unsure if $wgParser is safe to use.
6493 * @return Parser A parser object that is not parsing anything
6495 public function getFreshParser() {
6496 global $wgParserConf;
6497 if ( $this->mInParse
) {
6498 return new $wgParserConf['class']( $wgParserConf );