3 * PHP parser that converts wiki markup to HTML.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * @defgroup Parser Parser
29 * PHP Parser - Processes wiki markup (which uses a more user-friendly
30 * syntax, such as "[[link]]" for making links), and provides a one-way
31 * transformation of that wiki markup it into (X)HTML output / markup
32 * (which in turn the browser understands, and can display).
34 * There are seven main entry points into the Parser class:
37 * produces HTML output
38 * - Parser::preSaveTransform().
39 * produces altered wiki markup.
40 * - Parser::preprocess()
41 * removes HTML comments and expands templates
42 * - Parser::cleanSig() and Parser::cleanSigInSig()
43 * Cleans a signature before saving it to preferences
44 * - Parser::getSection()
45 * Return the content of a section from an article for section editing
46 * - Parser::replaceSection()
47 * Replaces a section by number inside an article
48 * - Parser::getPreloadText()
49 * Removes <noinclude> sections, and <includeonly> tags.
54 * @warning $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
57 * $wgNamespacesWithSubpages
59 * @par Settings only within ParserOptions:
60 * $wgAllowExternalImages
61 * $wgAllowSpecialInclusion
69 * Update this version number when the ParserOutput format
70 * changes in an incompatible way, so the parser cache
71 * can automatically discard old data.
73 const VERSION
= '1.6.4';
76 * Update this version number when the output of serialiseHalfParsedText()
77 * changes in an incompatible way
79 const HALF_PARSED_VERSION
= 2;
81 # Flags for Parser::setFunctionHook
82 # Also available as global constants from Defines.php
83 const SFH_NO_HASH
= 1;
84 const SFH_OBJECT_ARGS
= 2;
86 # Constants needed for external link processing
87 # Everything except bracket, space, or control characters
88 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
89 # as well as U+3000 is IDEOGRAPHIC SPACE for bug 19052
90 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}]';
91 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F\p{Zs}]+)
92 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
94 # State constants for the definition list colon extraction
95 const COLON_STATE_TEXT
= 0;
96 const COLON_STATE_TAG
= 1;
97 const COLON_STATE_TAGSTART
= 2;
98 const COLON_STATE_CLOSETAG
= 3;
99 const COLON_STATE_TAGSLASH
= 4;
100 const COLON_STATE_COMMENT
= 5;
101 const COLON_STATE_COMMENTDASH
= 6;
102 const COLON_STATE_COMMENTDASHDASH
= 7;
104 # Flags for preprocessToDom
105 const PTD_FOR_INCLUSION
= 1;
107 # Allowed values for $this->mOutputType
108 # Parameter to startExternalParse().
109 const OT_HTML
= 1; # like parse()
110 const OT_WIKI
= 2; # like preSaveTransform()
111 const OT_PREPROCESS
= 3; # like preprocess()
113 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
115 # Marker Suffix needs to be accessible staticly.
116 const MARKER_SUFFIX
= "-QINU\x7f";
118 # Markers used for wrapping the table of contents
119 const TOC_START
= '<mw:toc>';
120 const TOC_END
= '</mw:toc>';
125 public $mTagHooks = array();
128 public $mTransparentTagHooks = array();
131 public $mFunctionHooks = array();
134 protected $mFunctionSynonyms = array( 0 => array(), 1 => array() );
137 protected $mFunctionTagHooks = array();
140 protected $mStripList = array();
146 private $mDefaultStripList = array();
149 protected $mVarCache = array();
152 protected $mImageParams = array();
155 protected $mImageParamsMagicArray = array();
158 public $mMarkerIndex = 0;
161 protected $mFirstCall = true;
163 # Initialised by initialiseVariables()
165 /** @var MagicWordArray */
168 /** @var MagicWordArray */
169 protected $mSubstWords;
171 # Initialised in constructor
177 public $mPreprocessor;
180 protected $mExtLinkBracketedRegex;
183 protected $mUrlProtocols;
185 # Cleared with clearState():
187 /** @var ParserOutput */
191 protected $mAutonumber;
196 /** @var StripState */
203 private $mIncludeCount;
212 protected $mLastSection;
217 /** @var LinkHolderArray */
218 protected $mLinkHolders;
224 protected $mIncludeSizes;
227 public $mPPNodeCount;
230 public $mGeneratedPPNodeCount;
233 public $mHighestExpansionDepth;
235 /** @var bool|string */
236 protected $mDefaultSort;
238 /** @var array Empty-frame expansion cache */
239 protected $mTplExpandCache;
242 protected $mTplRedirCache;
245 protected $mTplDomCache;
251 protected $mDoubleUnderscores;
253 /** @var int Number of expensive parser function calls */
254 protected $mExpensiveFunctionCount;
260 protected $mForceTocPosition;
262 /** @var User User object; only used when doing pre-save transform */
266 # These are variables reset at least once per parse regardless of $clearState
268 /** @var ParserOptions */
271 /** @var Title Title context, used for self-link rendering and similar things */
274 /** @var array Shortcut alias, see setOutputType() */
277 /** @var string The timestamp of the specified revision ID */
278 public $mRevisionTimestamp;
284 * @var boolean Recursive call protection.
285 * This variable should be treated as if it were private.
287 public $mInParse = false;
289 /** @var int Output type, one of the OT_xxx constants */
290 protected $mOutputType;
292 /** @var Revision The revision object of the specified revision ID */
293 protected $mRevisionObject;
295 /** @var int ID to display in {{REVISIONID}} tags */
296 protected $mRevisionId;
298 /** @var string User to display in {{REVISIONUSER}} tag */
299 protected $mRevisionUser;
301 /** @var int Size to display in {{REVISIONSIZE}} variable */
302 protected $mRevisionSize;
304 /** @var bool|int For {{PAGESIZE}} on current page. */
305 protected $mInputSize = false;
308 * @var array Array with the language name of each language link (i.e. the
309 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
310 * duplicate language links to the ParserOutput.
312 protected $mLangLinkLanguages;
315 * @var int The revision ID which was used to fetch the timestamp
318 private $mRevIdForTs;
323 public function __construct( $conf = array() ) {
324 $this->mConf
= $conf;
325 $this->mUrlProtocols
= wfUrlProtocols();
326 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')' .
327 self
::EXT_LINK_URL_CLASS
. '+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
328 if ( isset( $conf['preprocessorClass'] ) ) {
329 $this->mPreprocessorClass
= $conf['preprocessorClass'];
330 } elseif ( defined( 'HPHP_VERSION' ) ) {
331 # Preprocessor_Hash is much faster than Preprocessor_DOM under HipHop
332 $this->mPreprocessorClass
= 'Preprocessor_Hash';
333 } elseif ( extension_loaded( 'domxml' ) ) {
334 # PECL extension that conflicts with the core DOM extension (bug 13770)
335 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
336 $this->mPreprocessorClass
= 'Preprocessor_Hash';
337 } elseif ( extension_loaded( 'dom' ) ) {
338 $this->mPreprocessorClass
= 'Preprocessor_DOM';
340 $this->mPreprocessorClass
= 'Preprocessor_Hash';
342 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
346 * Reduce memory usage to reduce the impact of circular references
348 function __destruct() {
349 if ( isset( $this->mLinkHolders
) ) {
350 unset( $this->mLinkHolders
);
352 foreach ( $this as $name => $value ) {
353 unset( $this->$name );
358 * Allow extensions to clean up when the parser is cloned
361 $this->mInParse
= false;
362 wfRunHooks( 'ParserCloned', array( $this ) );
366 * Do various kinds of initialisation on the first call of the parser
368 function firstCallInit() {
369 if ( !$this->mFirstCall
) {
372 $this->mFirstCall
= false;
374 wfProfileIn( __METHOD__
);
376 CoreParserFunctions
::register( $this );
377 CoreTagHooks
::register( $this );
378 $this->initialiseVariables();
380 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
381 wfProfileOut( __METHOD__
);
389 function clearState() {
390 wfProfileIn( __METHOD__
);
391 if ( $this->mFirstCall
) {
392 $this->firstCallInit();
394 $this->mOutput
= new ParserOutput
;
395 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
396 $this->mAutonumber
= 0;
397 $this->mLastSection
= '';
398 $this->mDTopen
= false;
399 $this->mIncludeCount
= array();
400 $this->mArgStack
= false;
401 $this->mInPre
= false;
402 $this->mLinkHolders
= new LinkHolderArray( $this );
404 $this->mRevisionObject
= $this->mRevisionTimestamp
=
405 $this->mRevisionId
= $this->mRevisionUser
= $this->mRevisionSize
= null;
406 $this->mVarCache
= array();
408 $this->mLangLinkLanguages
= array();
411 * Prefix for temporary replacement strings for the multipass parser.
412 * \x07 should never appear in input as it's disallowed in XML.
413 * Using it at the front also gives us a little extra robustness
414 * since it shouldn't match when butted up against identifier-like
417 * Must not consist of all title characters, or else it will change
418 * the behavior of <nowiki> in a link.
420 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
421 $this->mStripState
= new StripState( $this->mUniqPrefix
);
423 # Clear these on every parse, bug 4549
424 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
426 $this->mShowToc
= true;
427 $this->mForceTocPosition
= false;
428 $this->mIncludeSizes
= array(
432 $this->mPPNodeCount
= 0;
433 $this->mGeneratedPPNodeCount
= 0;
434 $this->mHighestExpansionDepth
= 0;
435 $this->mDefaultSort
= false;
436 $this->mHeadings
= array();
437 $this->mDoubleUnderscores
= array();
438 $this->mExpensiveFunctionCount
= 0;
441 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
442 $this->mPreprocessor
= null;
445 wfRunHooks( 'ParserClearState', array( &$this ) );
446 wfProfileOut( __METHOD__
);
450 * Convert wikitext to HTML
451 * Do not call this function recursively.
453 * @param string $text text we want to parse
454 * @param Title $title
455 * @param ParserOptions $options
456 * @param bool $linestart
457 * @param bool $clearState
458 * @param int $revid Number to pass in {{REVISIONID}}
459 * @return ParserOutput A ParserOutput
461 public function parse( $text, Title
$title, ParserOptions
$options,
462 $linestart = true, $clearState = true, $revid = null
465 * First pass--just handle <nowiki> sections, pass the rest off
466 * to internalParse() which does all the real work.
469 global $wgUseTidy, $wgAlwaysUseTidy, $wgShowHostnames;
470 $fname = __METHOD__
. '-' . wfGetCaller();
471 wfProfileIn( __METHOD__
);
472 wfProfileIn( $fname );
475 $magicScopeVariable = $this->lock();
478 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
480 $this->mInputSize
= strlen( $text );
481 if ( $this->mOptions
->getEnableLimitReport() ) {
482 $this->mOutput
->resetParseStartTime();
485 # Remove the strip marker tag prefix from the input, if present.
487 $text = str_replace( $this->mUniqPrefix
, '', $text );
490 $oldRevisionId = $this->mRevisionId
;
491 $oldRevisionObject = $this->mRevisionObject
;
492 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
493 $oldRevisionUser = $this->mRevisionUser
;
494 $oldRevisionSize = $this->mRevisionSize
;
495 if ( $revid !== null ) {
496 $this->mRevisionId
= $revid;
497 $this->mRevisionObject
= null;
498 $this->mRevisionTimestamp
= null;
499 $this->mRevisionUser
= null;
500 $this->mRevisionSize
= null;
503 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
505 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
506 $text = $this->internalParse( $text );
507 wfRunHooks( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
509 $text = $this->mStripState
->unstripGeneral( $text );
511 # Clean up special characters, only run once, next-to-last before doBlockLevels
513 # french spaces, last one Guillemet-left
514 # only if there is something before the space
515 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
516 # french spaces, Guillemet-right
517 '/(\\302\\253) /' => '\\1 ',
518 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
520 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
522 $text = $this->doBlockLevels( $text, $linestart );
524 $this->replaceLinkHolders( $text );
527 * The input doesn't get language converted if
529 * b) Content isn't converted
530 * c) It's a conversion table
531 * d) it is an interface message (which is in the user language)
533 if ( !( $options->getDisableContentConversion()
534 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) )
536 if ( !$this->mOptions
->getInterfaceMessage() ) {
537 # The position of the convert() call should not be changed. it
538 # assumes that the links are all replaced and the only thing left
539 # is the <nowiki> mark.
540 $text = $this->getConverterLanguage()->convert( $text );
545 * A converted title will be provided in the output object if title and
546 * content conversion are enabled, the article text does not contain
547 * a conversion-suppressing double-underscore tag, and no
548 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
549 * automatic link conversion.
551 if ( !( $options->getDisableTitleConversion()
552 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
553 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
554 ||
$this->mOutput
->getDisplayTitle() !== false )
556 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
557 if ( $convruletitle ) {
558 $this->mOutput
->setTitleText( $convruletitle );
560 $titleText = $this->getConverterLanguage()->convertTitle( $title );
561 $this->mOutput
->setTitleText( $titleText );
565 $text = $this->mStripState
->unstripNoWiki( $text );
567 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
569 $text = $this->replaceTransparentTags( $text );
570 $text = $this->mStripState
->unstripGeneral( $text );
572 $text = Sanitizer
::normalizeCharReferences( $text );
574 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
575 $text = MWTidy
::tidy( $text );
577 # attempt to sanitize at least some nesting problems
578 # (bug #2702 and quite a few others)
580 # ''Something [http://www.cool.com cool''] -->
581 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
582 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
583 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
584 # fix up an anchor inside another anchor, only
585 # at least for a single single nested link (bug 3695)
586 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
587 '\\1\\2</a>\\3</a>\\1\\4</a>',
588 # fix div inside inline elements- doBlockLevels won't wrap a line which
589 # contains a div, so fix it up here; replace
590 # div with escaped text
591 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
592 '\\1\\3<div\\5>\\6</div>\\8\\9',
593 # remove empty italic or bold tag pairs, some
594 # introduced by rules above
595 '/<([bi])><\/\\1>/' => '',
598 $text = preg_replace(
599 array_keys( $tidyregs ),
600 array_values( $tidyregs ),
604 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
605 $this->limitationWarn( 'expensive-parserfunction',
606 $this->mExpensiveFunctionCount
,
607 $this->mOptions
->getExpensiveParserFunctionLimit()
611 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
613 # Information on include size limits, for the benefit of users who try to skirt them
614 if ( $this->mOptions
->getEnableLimitReport() ) {
615 $max = $this->mOptions
->getMaxIncludeSize();
617 $cpuTime = $this->mOutput
->getTimeSinceStart( 'cpu' );
618 if ( $cpuTime !== null ) {
619 $this->mOutput
->setLimitReportData( 'limitreport-cputime',
620 sprintf( "%.3f", $cpuTime )
624 $wallTime = $this->mOutput
->getTimeSinceStart( 'wall' );
625 $this->mOutput
->setLimitReportData( 'limitreport-walltime',
626 sprintf( "%.3f", $wallTime )
629 $this->mOutput
->setLimitReportData( 'limitreport-ppvisitednodes',
630 array( $this->mPPNodeCount
, $this->mOptions
->getMaxPPNodeCount() )
632 $this->mOutput
->setLimitReportData( 'limitreport-ppgeneratednodes',
633 array( $this->mGeneratedPPNodeCount
, $this->mOptions
->getMaxGeneratedPPNodeCount() )
635 $this->mOutput
->setLimitReportData( 'limitreport-postexpandincludesize',
636 array( $this->mIncludeSizes
['post-expand'], $max )
638 $this->mOutput
->setLimitReportData( 'limitreport-templateargumentsize',
639 array( $this->mIncludeSizes
['arg'], $max )
641 $this->mOutput
->setLimitReportData( 'limitreport-expansiondepth',
642 array( $this->mHighestExpansionDepth
, $this->mOptions
->getMaxPPExpandDepth() )
644 $this->mOutput
->setLimitReportData( 'limitreport-expensivefunctioncount',
645 array( $this->mExpensiveFunctionCount
, $this->mOptions
->getExpensiveParserFunctionLimit() )
647 wfRunHooks( 'ParserLimitReportPrepare', array( $this, $this->mOutput
) );
649 $limitReport = "NewPP limit report\n";
650 if ( $wgShowHostnames ) {
651 $limitReport .= 'Parsed by ' . wfHostname() . "\n";
653 foreach ( $this->mOutput
->getLimitReportData() as $key => $value ) {
654 if ( wfRunHooks( 'ParserLimitReportFormat',
655 array( $key, &$value, &$limitReport, false, false )
657 $keyMsg = wfMessage( $key )->inLanguage( 'en' )->useDatabase( false );
658 $valueMsg = wfMessage( array( "$key-value-text", "$key-value" ) )
659 ->inLanguage( 'en' )->useDatabase( false );
660 if ( !$valueMsg->exists() ) {
661 $valueMsg = new RawMessage( '$1' );
663 if ( !$keyMsg->isDisabled() && !$valueMsg->isDisabled() ) {
664 $valueMsg->params( $value );
665 $limitReport .= "{$keyMsg->text()}: {$valueMsg->text()}\n";
669 // Since we're not really outputting HTML, decode the entities and
670 // then re-encode the things that need hiding inside HTML comments.
671 $limitReport = htmlspecialchars_decode( $limitReport );
672 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
674 // Sanitize for comment. Note '‐' in the replacement is U+2010,
675 // which looks much like the problematic '-'.
676 $limitReport = str_replace( array( '-', '&' ), array( '‐', '&' ), $limitReport );
677 $text .= "\n<!-- \n$limitReport-->\n";
679 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
680 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
681 $this->mTitle
->getPrefixedDBkey() );
684 $this->mOutput
->setText( $text );
686 $this->mRevisionId
= $oldRevisionId;
687 $this->mRevisionObject
= $oldRevisionObject;
688 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
689 $this->mRevisionUser
= $oldRevisionUser;
690 $this->mRevisionSize
= $oldRevisionSize;
691 $this->mInputSize
= false;
692 wfProfileOut( $fname );
693 wfProfileOut( __METHOD__
);
695 return $this->mOutput
;
699 * Recursive parser entry point that can be called from an extension tag
702 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
704 * @param string $text Text extension wants to have parsed
705 * @param bool|PPFrame $frame The frame to use for expanding any template variables
709 function recursiveTagParse( $text, $frame = false ) {
710 wfProfileIn( __METHOD__
);
711 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
712 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
713 $text = $this->internalParse( $text, false, $frame );
714 wfProfileOut( __METHOD__
);
719 * Expand templates and variables in the text, producing valid, static wikitext.
720 * Also removes comments.
721 * @param string $text
722 * @param Title $title
723 * @param ParserOptions $options
724 * @param int|null $revid
725 * @return mixed|string
727 function preprocess( $text, Title
$title = null, ParserOptions
$options, $revid = null ) {
728 wfProfileIn( __METHOD__
);
729 $magicScopeVariable = $this->lock();
730 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
731 if ( $revid !== null ) {
732 $this->mRevisionId
= $revid;
734 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
735 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
736 $text = $this->replaceVariables( $text );
737 $text = $this->mStripState
->unstripBoth( $text );
738 wfProfileOut( __METHOD__
);
743 * Recursive parser entry point that can be called from an extension tag
746 * @param string $text Text to be expanded
747 * @param bool|PPFrame $frame The frame to use for expanding any template variables
751 public function recursivePreprocess( $text, $frame = false ) {
752 wfProfileIn( __METHOD__
);
753 $text = $this->replaceVariables( $text, $frame );
754 $text = $this->mStripState
->unstripBoth( $text );
755 wfProfileOut( __METHOD__
);
760 * Process the wikitext for the "?preload=" feature. (bug 5210)
762 * "<noinclude>", "<includeonly>" etc. are parsed as for template
763 * transclusion, comments, templates, arguments, tags hooks and parser
764 * functions are untouched.
766 * @param string $text
767 * @param Title $title
768 * @param ParserOptions $options
769 * @param array $params
772 public function getPreloadText( $text, Title
$title, ParserOptions
$options, $params = array() ) {
773 $msg = new RawMessage( $text );
774 $text = $msg->params( $params )->plain();
776 # Parser (re)initialisation
777 $magicScopeVariable = $this->lock();
778 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
780 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
781 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
782 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
783 $text = $this->mStripState
->unstripBoth( $text );
788 * Get a random string
792 public static function getRandomString() {
793 return wfRandomString( 16 );
797 * Set the current user.
798 * Should only be used when doing pre-save transform.
800 * @param User|null $user User object or null (to reset)
802 function setUser( $user ) {
803 $this->mUser
= $user;
807 * Accessor for mUniqPrefix.
811 public function uniqPrefix() {
812 if ( !isset( $this->mUniqPrefix
) ) {
813 # @todo FIXME: This is probably *horribly wrong*
814 # LanguageConverter seems to want $wgParser's uniqPrefix, however
815 # if this is called for a parser cache hit, the parser may not
816 # have ever been initialized in the first place.
817 # Not really sure what the heck is supposed to be going on here.
819 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
821 return $this->mUniqPrefix
;
825 * Set the context title
829 function setTitle( $t ) {
831 $t = Title
::newFromText( 'NO TITLE' );
834 if ( $t->hasFragment() ) {
835 # Strip the fragment to avoid various odd effects
836 $this->mTitle
= clone $t;
837 $this->mTitle
->setFragment( '' );
844 * Accessor for the Title object
848 function getTitle() {
849 return $this->mTitle
;
853 * Accessor/mutator for the Title object
855 * @param Title $x Title object or null to just get the current one
858 function Title( $x = null ) {
859 return wfSetVar( $this->mTitle
, $x );
863 * Set the output type
865 * @param int $ot New value
867 function setOutputType( $ot ) {
868 $this->mOutputType
= $ot;
871 'html' => $ot == self
::OT_HTML
,
872 'wiki' => $ot == self
::OT_WIKI
,
873 'pre' => $ot == self
::OT_PREPROCESS
,
874 'plain' => $ot == self
::OT_PLAIN
,
879 * Accessor/mutator for the output type
881 * @param int|null $x New value or null to just get the current one
884 function OutputType( $x = null ) {
885 return wfSetVar( $this->mOutputType
, $x );
889 * Get the ParserOutput object
891 * @return ParserOutput
893 function getOutput() {
894 return $this->mOutput
;
898 * Get the ParserOptions object
900 * @return ParserOptions object
902 function getOptions() {
903 return $this->mOptions
;
907 * Accessor/mutator for the ParserOptions object
909 * @param ParserOptions $x New value or null to just get the current one
910 * @return ParserOptions Current ParserOptions object
912 function Options( $x = null ) {
913 return wfSetVar( $this->mOptions
, $x );
919 function nextLinkID() {
920 return $this->mLinkID++
;
926 function setLinkID( $id ) {
927 $this->mLinkID
= $id;
931 * Get a language object for use in parser functions such as {{FORMATNUM:}}
934 function getFunctionLang() {
935 return $this->getTargetLanguage();
939 * Get the target language for the content being parsed. This is usually the
940 * language that the content is in.
944 * @throws MWException
945 * @return Language|null
947 public function getTargetLanguage() {
948 $target = $this->mOptions
->getTargetLanguage();
950 if ( $target !== null ) {
952 } elseif ( $this->mOptions
->getInterfaceMessage() ) {
953 return $this->mOptions
->getUserLangObj();
954 } elseif ( is_null( $this->mTitle
) ) {
955 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
958 return $this->mTitle
->getPageLanguage();
962 * Get the language object for language conversion
963 * @return Language|null
965 function getConverterLanguage() {
966 return $this->getTargetLanguage();
970 * Get a User object either from $this->mUser, if set, or from the
971 * ParserOptions object otherwise
976 if ( !is_null( $this->mUser
) ) {
979 return $this->mOptions
->getUser();
983 * Get a preprocessor object
985 * @return Preprocessor
987 function getPreprocessor() {
988 if ( !isset( $this->mPreprocessor
) ) {
989 $class = $this->mPreprocessorClass
;
990 $this->mPreprocessor
= new $class( $this );
992 return $this->mPreprocessor
;
996 * Replaces all occurrences of HTML-style comments and the given tags
997 * in the text with a random marker and returns the next text. The output
998 * parameter $matches will be an associative array filled with data in
1002 * 'UNIQ-xxxxx' => array(
1005 * array( 'param' => 'x' ),
1006 * '<element param="x">tag content</element>' ) )
1009 * @param array $elements List of element names. Comments are always extracted.
1010 * @param string $text Source text string.
1011 * @param array $matches Out parameter, Array: extracted tags
1012 * @param string $uniq_prefix
1013 * @return string Stripped text
1015 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
1020 $taglist = implode( '|', $elements );
1021 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
1023 while ( $text != '' ) {
1024 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
1026 if ( count( $p ) < 5 ) {
1029 if ( count( $p ) > 5 ) {
1038 $attributes = $p[2];
1043 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
1044 $stripped .= $marker;
1046 if ( $close === '/>' ) {
1047 # Empty element tag, <tag />
1052 if ( $element === '!--' ) {
1055 $end = "/(<\\/$element\\s*>)/i";
1057 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
1059 if ( count( $q ) < 3 ) {
1060 # No end tag -- let it run out to the end of the text.
1069 $matches[$marker] = array( $element,
1071 Sanitizer
::decodeTagAttributes( $attributes ),
1072 "<$element$attributes$close$content$tail" );
1078 * Get a list of strippable XML-like elements
1082 function getStripList() {
1083 return $this->mStripList
;
1087 * Add an item to the strip state
1088 * Returns the unique tag which must be inserted into the stripped text
1089 * The tag will be replaced with the original text in unstrip()
1091 * @param string $text
1095 function insertStripItem( $text ) {
1096 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
1097 $this->mMarkerIndex++
;
1098 $this->mStripState
->addGeneral( $rnd, $text );
1103 * parse the wiki syntax used to render tables
1106 * @param string $text
1109 function doTableStuff( $text ) {
1110 wfProfileIn( __METHOD__
);
1112 $lines = StringUtils
::explode( "\n", $text );
1114 $td_history = array(); # Is currently a td tag open?
1115 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
1116 $tr_history = array(); # Is currently a tr tag open?
1117 $tr_attributes = array(); # history of tr attributes
1118 $has_opened_tr = array(); # Did this table open a <tr> element?
1119 $indent_level = 0; # indent level of the table
1121 foreach ( $lines as $outLine ) {
1122 $line = trim( $outLine );
1124 if ( $line === '' ) { # empty line, go to next line
1125 $out .= $outLine . "\n";
1129 $first_character = $line[0];
1132 if ( preg_match( '/^(:*)\{\|(.*)$/', $line, $matches ) ) {
1133 # First check if we are starting a new table
1134 $indent_level = strlen( $matches[1] );
1136 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
1137 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'table' );
1139 $outLine = str_repeat( '<dl><dd>', $indent_level ) . "<table{$attributes}>";
1140 array_push( $td_history, false );
1141 array_push( $last_tag_history, '' );
1142 array_push( $tr_history, false );
1143 array_push( $tr_attributes, '' );
1144 array_push( $has_opened_tr, false );
1145 } elseif ( count( $td_history ) == 0 ) {
1146 # Don't do any of the following
1147 $out .= $outLine . "\n";
1149 } elseif ( substr( $line, 0, 2 ) === '|}' ) {
1150 # We are ending a table
1151 $line = '</table>' . substr( $line, 2 );
1152 $last_tag = array_pop( $last_tag_history );
1154 if ( !array_pop( $has_opened_tr ) ) {
1155 $line = "<tr><td></td></tr>{$line}";
1158 if ( array_pop( $tr_history ) ) {
1159 $line = "</tr>{$line}";
1162 if ( array_pop( $td_history ) ) {
1163 $line = "</{$last_tag}>{$line}";
1165 array_pop( $tr_attributes );
1166 $outLine = $line . str_repeat( '</dd></dl>', $indent_level );
1167 } elseif ( substr( $line, 0, 2 ) === '|-' ) {
1168 # Now we have a table row
1169 $line = preg_replace( '#^\|-+#', '', $line );
1171 # Whats after the tag is now only attributes
1172 $attributes = $this->mStripState
->unstripBoth( $line );
1173 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
1174 array_pop( $tr_attributes );
1175 array_push( $tr_attributes, $attributes );
1178 $last_tag = array_pop( $last_tag_history );
1179 array_pop( $has_opened_tr );
1180 array_push( $has_opened_tr, true );
1182 if ( array_pop( $tr_history ) ) {
1186 if ( array_pop( $td_history ) ) {
1187 $line = "</{$last_tag}>{$line}";
1191 array_push( $tr_history, false );
1192 array_push( $td_history, false );
1193 array_push( $last_tag_history, '' );
1194 } elseif ( $first_character === '|'
1195 ||
$first_character === '!'
1196 ||
substr( $line, 0, 2 ) === '|+'
1198 # This might be cell elements, td, th or captions
1199 if ( substr( $line, 0, 2 ) === '|+' ) {
1200 $first_character = '+';
1201 $line = substr( $line, 1 );
1204 $line = substr( $line, 1 );
1206 if ( $first_character === '!' ) {
1207 $line = str_replace( '!!', '||', $line );
1210 # Split up multiple cells on the same line.
1211 # FIXME : This can result in improper nesting of tags processed
1212 # by earlier parser steps, but should avoid splitting up eg
1213 # attribute values containing literal "||".
1214 $cells = StringUtils
::explodeMarkup( '||', $line );
1218 # Loop through each table cell
1219 foreach ( $cells as $cell ) {
1221 if ( $first_character !== '+' ) {
1222 $tr_after = array_pop( $tr_attributes );
1223 if ( !array_pop( $tr_history ) ) {
1224 $previous = "<tr{$tr_after}>\n";
1226 array_push( $tr_history, true );
1227 array_push( $tr_attributes, '' );
1228 array_pop( $has_opened_tr );
1229 array_push( $has_opened_tr, true );
1232 $last_tag = array_pop( $last_tag_history );
1234 if ( array_pop( $td_history ) ) {
1235 $previous = "</{$last_tag}>\n{$previous}";
1238 if ( $first_character === '|' ) {
1240 } elseif ( $first_character === '!' ) {
1242 } elseif ( $first_character === '+' ) {
1243 $last_tag = 'caption';
1248 array_push( $last_tag_history, $last_tag );
1250 # A cell could contain both parameters and data
1251 $cell_data = explode( '|', $cell, 2 );
1253 # Bug 553: Note that a '|' inside an invalid link should not
1254 # be mistaken as delimiting cell parameters
1255 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1256 $cell = "{$previous}<{$last_tag}>{$cell}";
1257 } elseif ( count( $cell_data ) == 1 ) {
1258 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1260 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1261 $attributes = Sanitizer
::fixTagAttributes( $attributes, $last_tag );
1262 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1266 array_push( $td_history, true );
1269 $out .= $outLine . "\n";
1272 # Closing open td, tr && table
1273 while ( count( $td_history ) > 0 ) {
1274 if ( array_pop( $td_history ) ) {
1277 if ( array_pop( $tr_history ) ) {
1280 if ( !array_pop( $has_opened_tr ) ) {
1281 $out .= "<tr><td></td></tr>\n";
1284 $out .= "</table>\n";
1287 # Remove trailing line-ending (b/c)
1288 if ( substr( $out, -1 ) === "\n" ) {
1289 $out = substr( $out, 0, -1 );
1292 # special case: don't return empty table
1293 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1297 wfProfileOut( __METHOD__
);
1303 * Helper function for parse() that transforms wiki markup into
1304 * HTML. Only called for $mOutputType == self::OT_HTML.
1308 * @param string $text
1309 * @param bool $isMain
1310 * @param bool $frame
1314 function internalParse( $text, $isMain = true, $frame = false ) {
1315 wfProfileIn( __METHOD__
);
1319 # Hook to suspend the parser in this state
1320 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1321 wfProfileOut( __METHOD__
);
1325 # if $frame is provided, then use $frame for replacing any variables
1327 # use frame depth to infer how include/noinclude tags should be handled
1328 # depth=0 means this is the top-level document; otherwise it's an included document
1329 if ( !$frame->depth
) {
1332 $flag = Parser
::PTD_FOR_INCLUSION
;
1334 $dom = $this->preprocessToDom( $text, $flag );
1335 $text = $frame->expand( $dom );
1337 # if $frame is not provided, then use old-style replaceVariables
1338 $text = $this->replaceVariables( $text );
1341 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1342 $text = Sanitizer
::removeHTMLtags(
1344 array( &$this, 'attributeStripCallback' ),
1346 array_keys( $this->mTransparentTagHooks
)
1348 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1350 # Tables need to come after variable replacement for things to work
1351 # properly; putting them before other transformations should keep
1352 # exciting things like link expansions from showing up in surprising
1354 $text = $this->doTableStuff( $text );
1356 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1358 $text = $this->doDoubleUnderscore( $text );
1360 $text = $this->doHeadings( $text );
1361 $text = $this->replaceInternalLinks( $text );
1362 $text = $this->doAllQuotes( $text );
1363 $text = $this->replaceExternalLinks( $text );
1365 # replaceInternalLinks may sometimes leave behind
1366 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1367 $text = str_replace( $this->mUniqPrefix
. 'NOPARSE', '', $text );
1369 $text = $this->doMagicLinks( $text );
1370 $text = $this->formatHeadings( $text, $origText, $isMain );
1372 wfProfileOut( __METHOD__
);
1377 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1378 * magic external links.
1383 * @param string $text
1387 function doMagicLinks( $text ) {
1388 wfProfileIn( __METHOD__
);
1389 $prots = wfUrlProtocolsWithoutProtRel();
1390 $urlChar = self
::EXT_LINK_URL_CLASS
;
1391 $text = preg_replace_callback(
1393 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1394 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1395 (\\b(?i:$prots)$urlChar+) | # m[3]: Free external links" . '
1396 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1397 ISBN\s+(\b # m[5]: ISBN, capture number
1398 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1399 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1400 [0-9Xx] # check digit
1402 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1403 wfProfileOut( __METHOD__
);
1408 * @throws MWException
1410 * @return HTML|string
1412 function magicLinkCallback( $m ) {
1413 if ( isset( $m[1] ) && $m[1] !== '' ) {
1416 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1419 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1420 # Free external link
1421 return $this->makeFreeExternalLink( $m[0] );
1422 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1424 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1427 $cssClass = 'mw-magiclink-rfc';
1429 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1431 $urlmsg = 'pubmedurl';
1432 $cssClass = 'mw-magiclink-pmid';
1435 throw new MWException( __METHOD__
. ': unrecognised match type "' .
1436 substr( $m[0], 0, 20 ) . '"' );
1438 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1439 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $cssClass );
1440 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1443 $num = strtr( $isbn, array(
1448 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1449 return '<a href="' .
1450 htmlspecialchars( $titleObj->getLocalURL() ) .
1451 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1458 * Make a free external link, given a user-supplied URL
1460 * @param string $url
1462 * @return string HTML
1465 function makeFreeExternalLink( $url ) {
1466 wfProfileIn( __METHOD__
);
1470 # The characters '<' and '>' (which were escaped by
1471 # removeHTMLtags()) should not be included in
1472 # URLs, per RFC 2396.
1474 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1475 $trail = substr( $url, $m2[0][1] ) . $trail;
1476 $url = substr( $url, 0, $m2[0][1] );
1479 # Move trailing punctuation to $trail
1481 # If there is no left bracket, then consider right brackets fair game too
1482 if ( strpos( $url, '(' ) === false ) {
1486 $numSepChars = strspn( strrev( $url ), $sep );
1487 if ( $numSepChars ) {
1488 $trail = substr( $url, -$numSepChars ) . $trail;
1489 $url = substr( $url, 0, -$numSepChars );
1492 $url = Sanitizer
::cleanUrl( $url );
1494 # Is this an external image?
1495 $text = $this->maybeMakeExternalImage( $url );
1496 if ( $text === false ) {
1497 # Not an image, make a link
1498 $text = Linker
::makeExternalLink( $url,
1499 $this->getConverterLanguage()->markNoConversion( $url, true ),
1501 $this->getExternalLinkAttribs( $url ) );
1502 # Register it in the output object...
1503 # Replace unnecessary URL escape codes with their equivalent characters
1504 $pasteurized = self
::replaceUnusualEscapes( $url );
1505 $this->mOutput
->addExternalLink( $pasteurized );
1507 wfProfileOut( __METHOD__
);
1508 return $text . $trail;
1512 * Parse headers and return html
1516 * @param string $text
1520 function doHeadings( $text ) {
1521 wfProfileIn( __METHOD__
);
1522 for ( $i = 6; $i >= 1; --$i ) {
1523 $h = str_repeat( '=', $i );
1524 $text = preg_replace( "/^$h(.+)$h\\s*$/m", "<h$i>\\1</h$i>", $text );
1526 wfProfileOut( __METHOD__
);
1531 * Replace single quotes with HTML markup
1534 * @param string $text
1536 * @return string the altered text
1538 function doAllQuotes( $text ) {
1539 wfProfileIn( __METHOD__
);
1541 $lines = StringUtils
::explode( "\n", $text );
1542 foreach ( $lines as $line ) {
1543 $outtext .= $this->doQuotes( $line ) . "\n";
1545 $outtext = substr( $outtext, 0, -1 );
1546 wfProfileOut( __METHOD__
);
1551 * Helper function for doAllQuotes()
1553 * @param string $text
1557 public function doQuotes( $text ) {
1558 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1559 $countarr = count( $arr );
1560 if ( $countarr == 1 ) {
1564 // First, do some preliminary work. This may shift some apostrophes from
1565 // being mark-up to being text. It also counts the number of occurrences
1566 // of bold and italics mark-ups.
1569 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1570 $thislen = strlen( $arr[$i] );
1571 // If there are ever four apostrophes, assume the first is supposed to
1572 // be text, and the remaining three constitute mark-up for bold text.
1573 // (bug 13227: ''''foo'''' turns into ' ''' foo ' ''')
1574 if ( $thislen == 4 ) {
1575 $arr[$i - 1] .= "'";
1578 } elseif ( $thislen > 5 ) {
1579 // If there are more than 5 apostrophes in a row, assume they're all
1580 // text except for the last 5.
1581 // (bug 13227: ''''''foo'''''' turns into ' ''''' foo ' ''''')
1582 $arr[$i - 1] .= str_repeat( "'", $thislen - 5 );
1586 // Count the number of occurrences of bold and italics mark-ups.
1587 if ( $thislen == 2 ) {
1589 } elseif ( $thislen == 3 ) {
1591 } elseif ( $thislen == 5 ) {
1597 // If there is an odd number of both bold and italics, it is likely
1598 // that one of the bold ones was meant to be an apostrophe followed
1599 // by italics. Which one we cannot know for certain, but it is more
1600 // likely to be one that has a single-letter word before it.
1601 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1602 $firstsingleletterword = -1;
1603 $firstmultiletterword = -1;
1605 for ( $i = 1; $i < $countarr; $i +
= 2 ) {
1606 if ( strlen( $arr[$i] ) == 3 ) {
1607 $x1 = substr( $arr[$i - 1], -1 );
1608 $x2 = substr( $arr[$i - 1], -2, 1 );
1609 if ( $x1 === ' ' ) {
1610 if ( $firstspace == -1 ) {
1613 } elseif ( $x2 === ' ' ) {
1614 if ( $firstsingleletterword == -1 ) {
1615 $firstsingleletterword = $i;
1616 // if $firstsingleletterword is set, we don't
1617 // look at the other options, so we can bail early.
1621 if ( $firstmultiletterword == -1 ) {
1622 $firstmultiletterword = $i;
1628 // If there is a single-letter word, use it!
1629 if ( $firstsingleletterword > -1 ) {
1630 $arr[$firstsingleletterword] = "''";
1631 $arr[$firstsingleletterword - 1] .= "'";
1632 } elseif ( $firstmultiletterword > -1 ) {
1633 // If not, but there's a multi-letter word, use that one.
1634 $arr[$firstmultiletterword] = "''";
1635 $arr[$firstmultiletterword - 1] .= "'";
1636 } elseif ( $firstspace > -1 ) {
1637 // ... otherwise use the first one that has neither.
1638 // (notice that it is possible for all three to be -1 if, for example,
1639 // there is only one pentuple-apostrophe in the line)
1640 $arr[$firstspace] = "''";
1641 $arr[$firstspace - 1] .= "'";
1645 // Now let's actually convert our apostrophic mush to HTML!
1650 foreach ( $arr as $r ) {
1651 if ( ( $i %
2 ) == 0 ) {
1652 if ( $state === 'both' ) {
1658 $thislen = strlen( $r );
1659 if ( $thislen == 2 ) {
1660 if ( $state === 'i' ) {
1663 } elseif ( $state === 'bi' ) {
1666 } elseif ( $state === 'ib' ) {
1667 $output .= '</b></i><b>';
1669 } elseif ( $state === 'both' ) {
1670 $output .= '<b><i>' . $buffer . '</i>';
1672 } else { // $state can be 'b' or ''
1676 } elseif ( $thislen == 3 ) {
1677 if ( $state === 'b' ) {
1680 } elseif ( $state === 'bi' ) {
1681 $output .= '</i></b><i>';
1683 } elseif ( $state === 'ib' ) {
1686 } elseif ( $state === 'both' ) {
1687 $output .= '<i><b>' . $buffer . '</b>';
1689 } else { // $state can be 'i' or ''
1693 } elseif ( $thislen == 5 ) {
1694 if ( $state === 'b' ) {
1695 $output .= '</b><i>';
1697 } elseif ( $state === 'i' ) {
1698 $output .= '</i><b>';
1700 } elseif ( $state === 'bi' ) {
1701 $output .= '</i></b>';
1703 } elseif ( $state === 'ib' ) {
1704 $output .= '</b></i>';
1706 } elseif ( $state === 'both' ) {
1707 $output .= '<i><b>' . $buffer . '</b></i>';
1709 } else { // ($state == '')
1717 // Now close all remaining tags. Notice that the order is important.
1718 if ( $state === 'b' ||
$state === 'ib' ) {
1721 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1724 if ( $state === 'bi' ) {
1727 // There might be lonely ''''', so make sure we have a buffer
1728 if ( $state === 'both' && $buffer ) {
1729 $output .= '<b><i>' . $buffer . '</i></b>';
1735 * Replace external links (REL)
1737 * Note: this is all very hackish and the order of execution matters a lot.
1738 * Make sure to run tests/parserTests.php if you change this code.
1742 * @param string $text
1744 * @throws MWException
1747 function replaceExternalLinks( $text ) {
1748 wfProfileIn( __METHOD__
);
1750 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1751 if ( $bits === false ) {
1752 wfProfileOut( __METHOD__
);
1753 throw new MWException( "PCRE needs to be compiled with "
1754 . "--enable-unicode-properties in order for MediaWiki to function" );
1756 $s = array_shift( $bits );
1759 while ( $i < count( $bits ) ) {
1762 $text = $bits[$i++
];
1763 $trail = $bits[$i++
];
1765 # The characters '<' and '>' (which were escaped by
1766 # removeHTMLtags()) should not be included in
1767 # URLs, per RFC 2396.
1769 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1770 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1771 $url = substr( $url, 0, $m2[0][1] );
1774 # If the link text is an image URL, replace it with an <img> tag
1775 # This happened by accident in the original parser, but some people used it extensively
1776 $img = $this->maybeMakeExternalImage( $text );
1777 if ( $img !== false ) {
1783 # Set linktype for CSS - if URL==text, link is essentially free
1784 $linktype = ( $text === $url ) ?
'free' : 'text';
1786 # No link text, e.g. [http://domain.tld/some.link]
1787 if ( $text == '' ) {
1789 $langObj = $this->getTargetLanguage();
1790 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1791 $linktype = 'autonumber';
1793 # Have link text, e.g. [http://domain.tld/some.link text]s
1795 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1798 $text = $this->getConverterLanguage()->markNoConversion( $text );
1800 $url = Sanitizer
::cleanUrl( $url );
1802 # Use the encoded URL
1803 # This means that users can paste URLs directly into the text
1804 # Funny characters like ö aren't valid in URLs anyway
1805 # This was changed in August 2004
1806 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1807 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1809 # Register link in the output object.
1810 # Replace unnecessary URL escape codes with the referenced character
1811 # This prevents spammers from hiding links from the filters
1812 $pasteurized = self
::replaceUnusualEscapes( $url );
1813 $this->mOutput
->addExternalLink( $pasteurized );
1816 wfProfileOut( __METHOD__
);
1821 * Get the rel attribute for a particular external link.
1824 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1825 * nofollow if appropriate
1826 * @param Title $title Optional Title, for wgNoFollowNsExceptions lookups
1827 * @return string|null Rel attribute for $url
1829 public static function getExternalLinkRel( $url = false, $title = null ) {
1830 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1831 $ns = $title ?
$title->getNamespace() : false;
1832 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions )
1833 && !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions )
1841 * Get an associative array of additional HTML attributes appropriate for a
1842 * particular external link. This currently may include rel => nofollow
1843 * (depending on configuration, namespace, and the URL's domain) and/or a
1844 * target attribute (depending on configuration).
1846 * @param string|bool $url Optional URL, to extract the domain from for rel =>
1847 * nofollow if appropriate
1848 * @return array Associative array of HTML attributes
1850 function getExternalLinkAttribs( $url = false ) {
1852 $attribs['rel'] = self
::getExternalLinkRel( $url, $this->mTitle
);
1854 if ( $this->mOptions
->getExternalLinkTarget() ) {
1855 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1861 * Replace unusual URL escape codes with their equivalent characters
1863 * @param string $url
1866 * @todo This can merge genuinely required bits in the path or query string,
1867 * breaking legit URLs. A proper fix would treat the various parts of
1868 * the URL differently; as a workaround, just use the output for
1869 * statistical records, not for actual linking/output.
1871 static function replaceUnusualEscapes( $url ) {
1872 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1873 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1877 * Callback function used in replaceUnusualEscapes().
1878 * Replaces unusual URL escape codes with their equivalent character
1880 * @param array $matches
1884 private static function replaceUnusualEscapesCallback( $matches ) {
1885 $char = urldecode( $matches[0] );
1886 $ord = ord( $char );
1887 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1888 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1889 # No, shouldn't be escaped
1892 # Yes, leave it escaped
1898 * make an image if it's allowed, either through the global
1899 * option, through the exception, or through the on-wiki whitelist
1902 * $param string $url
1906 function maybeMakeExternalImage( $url ) {
1907 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1908 $imagesexception = !empty( $imagesfrom );
1910 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1911 if ( $imagesexception && is_array( $imagesfrom ) ) {
1912 $imagematch = false;
1913 foreach ( $imagesfrom as $match ) {
1914 if ( strpos( $url, $match ) === 0 ) {
1919 } elseif ( $imagesexception ) {
1920 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1922 $imagematch = false;
1925 if ( $this->mOptions
->getAllowExternalImages()
1926 ||
( $imagesexception && $imagematch )
1928 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1930 $text = Linker
::makeExternalImage( $url );
1933 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1934 && preg_match( self
::EXT_IMAGE_REGEX
, $url )
1936 $whitelist = explode(
1938 wfMessage( 'external_image_whitelist' )->inContentLanguage()->text()
1941 foreach ( $whitelist as $entry ) {
1942 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1943 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1946 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1947 # Image matches a whitelist entry
1948 $text = Linker
::makeExternalImage( $url );
1957 * Process [[ ]] wikilinks
1961 * @return string Processed text
1965 function replaceInternalLinks( $s ) {
1966 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1971 * Process [[ ]] wikilinks (RIL)
1973 * @throws MWException
1974 * @return LinkHolderArray
1978 function replaceInternalLinks2( &$s ) {
1979 wfProfileIn( __METHOD__
);
1981 wfProfileIn( __METHOD__
. '-setup' );
1982 static $tc = false, $e1, $e1_img;
1983 # the % is needed to support urlencoded titles as well
1985 $tc = Title
::legalChars() . '#%';
1986 # Match a link having the form [[namespace:link|alternate]]trail
1987 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1988 # Match cases where there is no "]]", which might still be images
1989 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1992 $holders = new LinkHolderArray( $this );
1994 # split the entire text string on occurrences of [[
1995 $a = StringUtils
::explode( '[[', ' ' . $s );
1996 # get the first element (all text up to first [[), and remove the space we added
1999 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
2000 $s = substr( $s, 1 );
2002 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
2004 if ( $useLinkPrefixExtension ) {
2005 # Match the end of a line for a word that's not followed by whitespace,
2006 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
2008 $charset = $wgContLang->linkPrefixCharset();
2009 $e2 = "/^((?>.*[^$charset]|))(.+)$/sDu";
2012 if ( is_null( $this->mTitle
) ) {
2013 wfProfileOut( __METHOD__
. '-setup' );
2014 wfProfileOut( __METHOD__
);
2015 throw new MWException( __METHOD__
. ": \$this->mTitle is null\n" );
2017 $nottalk = !$this->mTitle
->isTalkPage();
2019 if ( $useLinkPrefixExtension ) {
2021 if ( preg_match( $e2, $s, $m ) ) {
2022 $first_prefix = $m[2];
2024 $first_prefix = false;
2030 $useSubpages = $this->areSubpagesAllowed();
2031 wfProfileOut( __METHOD__
. '-setup' );
2033 // @codingStandardsIgnoreStart Squiz.WhiteSpace.SemicolonSpacing.Incorrect
2034 # Loop for each link
2035 for ( ; $line !== false && $line !== null; $a->next(), $line = $a->current() ) {
2036 // @codingStandardsIgnoreStart
2038 # Check for excessive memory usage
2039 if ( $holders->isBig() ) {
2041 # Do the existence check, replace the link holders and clear the array
2042 $holders->replace( $s );
2046 if ( $useLinkPrefixExtension ) {
2047 wfProfileIn( __METHOD__
. '-prefixhandling' );
2048 if ( preg_match( $e2, $s, $m ) ) {
2055 if ( $first_prefix ) {
2056 $prefix = $first_prefix;
2057 $first_prefix = false;
2059 wfProfileOut( __METHOD__
. '-prefixhandling' );
2062 $might_be_img = false;
2064 wfProfileIn( __METHOD__
. "-e1" );
2065 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
2067 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
2068 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
2069 # the real problem is with the $e1 regex
2072 # Still some problems for cases where the ] is meant to be outside punctuation,
2073 # and no image is in sight. See bug 2095.
2076 && substr( $m[3], 0, 1 ) === ']'
2077 && strpos( $text, '[' ) !== false
2079 $text .= ']'; # so that replaceExternalLinks($text) works later
2080 $m[3] = substr( $m[3], 1 );
2082 # fix up urlencoded title texts
2083 if ( strpos( $m[1], '%' ) !== false ) {
2084 # Should anchors '#' also be rejected?
2085 $m[1] = str_replace( array( '<', '>' ), array( '<', '>' ), rawurldecode( $m[1] ) );
2088 } elseif ( preg_match( $e1_img, $line, $m ) ) {
2089 # Invalid, but might be an image with a link in its caption
2090 $might_be_img = true;
2092 if ( strpos( $m[1], '%' ) !== false ) {
2093 $m[1] = rawurldecode( $m[1] );
2096 } else { # Invalid form; output directly
2097 $s .= $prefix . '[[' . $line;
2098 wfProfileOut( __METHOD__
. "-e1" );
2101 wfProfileOut( __METHOD__
. "-e1" );
2102 wfProfileIn( __METHOD__
. "-misc" );
2104 # Don't allow internal links to pages containing
2105 # PROTO: where PROTO is a valid URL protocol; these
2106 # should be external links.
2107 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $m[1] ) ) {
2108 $s .= $prefix . '[[' . $line;
2109 wfProfileOut( __METHOD__
. "-misc" );
2113 # Make subpage if necessary
2114 if ( $useSubpages ) {
2115 $link = $this->maybeDoSubpageLink( $m[1], $text );
2120 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
2122 # Strip off leading ':'
2123 $link = substr( $link, 1 );
2126 wfProfileOut( __METHOD__
. "-misc" );
2127 wfProfileIn( __METHOD__
. "-title" );
2128 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
2129 if ( $nt === null ) {
2130 $s .= $prefix . '[[' . $line;
2131 wfProfileOut( __METHOD__
. "-title" );
2135 $ns = $nt->getNamespace();
2136 $iw = $nt->getInterwiki();
2137 wfProfileOut( __METHOD__
. "-title" );
2139 if ( $might_be_img ) { # if this is actually an invalid link
2140 wfProfileIn( __METHOD__
. "-might_be_img" );
2141 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
2144 # look at the next 'line' to see if we can close it there
2146 $next_line = $a->current();
2147 if ( $next_line === false ||
$next_line === null ) {
2150 $m = explode( ']]', $next_line, 3 );
2151 if ( count( $m ) == 3 ) {
2152 # the first ]] closes the inner link, the second the image
2154 $text .= "[[{$m[0]}]]{$m[1]}";
2157 } elseif ( count( $m ) == 2 ) {
2158 # if there's exactly one ]] that's fine, we'll keep looking
2159 $text .= "[[{$m[0]}]]{$m[1]}";
2161 # if $next_line is invalid too, we need look no further
2162 $text .= '[[' . $next_line;
2167 # we couldn't find the end of this imageLink, so output it raw
2168 # but don't ignore what might be perfectly normal links in the text we've examined
2169 $holders->merge( $this->replaceInternalLinks2( $text ) );
2170 $s .= "{$prefix}[[$link|$text";
2171 # note: no $trail, because without an end, there *is* no trail
2172 wfProfileOut( __METHOD__
. "-might_be_img" );
2175 } else { # it's not an image, so output it raw
2176 $s .= "{$prefix}[[$link|$text";
2177 # note: no $trail, because without an end, there *is* no trail
2178 wfProfileOut( __METHOD__
. "-might_be_img" );
2181 wfProfileOut( __METHOD__
. "-might_be_img" );
2184 $wasblank = ( $text == '' );
2188 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
2189 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
2190 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
2191 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
2192 $text = $this->doQuotes( $text );
2195 # Link not escaped by : , create the various objects
2198 wfProfileIn( __METHOD__
. "-interwiki" );
2199 if ( $iw && $this->mOptions
->getInterwikiMagic()
2200 && $nottalk && Language
::fetchLanguageName( $iw, null, 'mw' )
2202 // XXX: the above check prevents links to sites with identifiers that are not language codes
2204 # Bug 24502: filter duplicates
2205 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
2206 $this->mLangLinkLanguages
[$iw] = true;
2207 $this->mOutput
->addLanguageLink( $nt->getFullText() );
2210 $s = rtrim( $s . $prefix );
2211 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
2212 wfProfileOut( __METHOD__
. "-interwiki" );
2215 wfProfileOut( __METHOD__
. "-interwiki" );
2217 if ( $ns == NS_FILE
) {
2218 wfProfileIn( __METHOD__
. "-image" );
2219 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
2221 # if no parameters were passed, $text
2222 # becomes something like "File:Foo.png",
2223 # which we don't want to pass on to the
2227 # recursively parse links inside the image caption
2228 # actually, this will parse them in any other parameters, too,
2229 # but it might be hard to fix that, and it doesn't matter ATM
2230 $text = $this->replaceExternalLinks( $text );
2231 $holders->merge( $this->replaceInternalLinks2( $text ) );
2233 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
2234 $s .= $prefix . $this->armorLinks(
2235 $this->makeImage( $nt, $text, $holders ) ) . $trail;
2237 $s .= $prefix . $trail;
2239 wfProfileOut( __METHOD__
. "-image" );
2243 if ( $ns == NS_CATEGORY
) {
2244 wfProfileIn( __METHOD__
. "-category" );
2245 $s = rtrim( $s . "\n" ); # bug 87
2248 $sortkey = $this->getDefaultSort();
2252 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2253 $sortkey = str_replace( "\n", '', $sortkey );
2254 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2255 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2258 * Strip the whitespace Category links produce, see bug 87
2260 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2262 wfProfileOut( __METHOD__
. "-category" );
2267 # Self-link checking. For some languages, variants of the title are checked in
2268 # LinkHolderArray::doVariants() to allow batching the existence checks necessary
2269 # for linking to a different variant.
2270 if ( $ns != NS_SPECIAL
&& $nt->equals( $this->mTitle
) && !$nt->hasFragment() ) {
2271 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2275 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2276 # @todo FIXME: Should do batch file existence checks, see comment below
2277 if ( $ns == NS_MEDIA
) {
2278 wfProfileIn( __METHOD__
. "-media" );
2279 # Give extensions a chance to select the file revision for us
2282 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2283 array( $this, $nt, &$options, &$descQuery ) );
2284 # Fetch and register the file (file title may be different via hooks)
2285 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2286 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2287 $s .= $prefix . $this->armorLinks(
2288 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2289 wfProfileOut( __METHOD__
. "-media" );
2293 wfProfileIn( __METHOD__
. "-always_known" );
2294 # Some titles, such as valid special pages or files in foreign repos, should
2295 # be shown as bluelinks even though they're not included in the page table
2297 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2298 # batch file existence checks for NS_FILE and NS_MEDIA
2299 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2300 $this->mOutput
->addLink( $nt );
2301 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2303 # Links will be added to the output link list after checking
2304 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2306 wfProfileOut( __METHOD__
. "-always_known" );
2308 wfProfileOut( __METHOD__
);
2313 * Render a forced-blue link inline; protect against double expansion of
2314 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2315 * Since this little disaster has to split off the trail text to avoid
2316 * breaking URLs in the following text without breaking trails on the
2317 * wiki links, it's been made into a horrible function.
2320 * @param string $text
2321 * @param array|string $query
2322 * @param string $trail
2323 * @param string $prefix
2324 * @return string HTML-wikitext mix oh yuck
2326 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2327 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2329 if ( is_string( $query ) ) {
2330 $query = wfCgiToArray( $query );
2332 if ( $text == '' ) {
2333 $text = htmlspecialchars( $nt->getPrefixedText() );
2336 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2338 return $this->armorLinks( $link ) . $trail;
2342 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2343 * going to go through further parsing steps before inline URL expansion.
2345 * Not needed quite as much as it used to be since free links are a bit
2346 * more sensible these days. But bracketed links are still an issue.
2348 * @param string $text More-or-less HTML
2349 * @return string Less-or-more HTML with NOPARSE bits
2351 function armorLinks( $text ) {
2352 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2353 "{$this->mUniqPrefix}NOPARSE$1", $text );
2357 * Return true if subpage links should be expanded on this page.
2360 function areSubpagesAllowed() {
2361 # Some namespaces don't allow subpages
2362 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2366 * Handle link to subpage if necessary
2368 * @param string $target The source of the link
2369 * @param string &$text The link text, modified as necessary
2370 * @return string The full name of the link
2373 function maybeDoSubpageLink( $target, &$text ) {
2374 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2378 * Used by doBlockLevels()
2383 function closeParagraph() {
2385 if ( $this->mLastSection
!= '' ) {
2386 $result = '</' . $this->mLastSection
. ">\n";
2388 $this->mInPre
= false;
2389 $this->mLastSection
= '';
2394 * getCommon() returns the length of the longest common substring
2395 * of both arguments, starting at the beginning of both.
2398 * @param string $st1
2399 * @param string $st2
2403 function getCommon( $st1, $st2 ) {
2404 $fl = strlen( $st1 );
2405 $shorter = strlen( $st2 );
2406 if ( $fl < $shorter ) {
2410 for ( $i = 0; $i < $shorter; ++
$i ) {
2411 if ( $st1[$i] != $st2[$i] ) {
2419 * These next three functions open, continue, and close the list
2420 * element appropriate to the prefix character passed into them.
2423 * @param string $char
2427 function openList( $char ) {
2428 $result = $this->closeParagraph();
2430 if ( '*' === $char ) {
2431 $result .= "<ul>\n<li>";
2432 } elseif ( '#' === $char ) {
2433 $result .= "<ol>\n<li>";
2434 } elseif ( ':' === $char ) {
2435 $result .= "<dl>\n<dd>";
2436 } elseif ( ';' === $char ) {
2437 $result .= "<dl>\n<dt>";
2438 $this->mDTopen
= true;
2440 $result = '<!-- ERR 1 -->';
2448 * @param string $char
2453 function nextItem( $char ) {
2454 if ( '*' === $char ||
'#' === $char ) {
2455 return "</li>\n<li>";
2456 } elseif ( ':' === $char ||
';' === $char ) {
2458 if ( $this->mDTopen
) {
2461 if ( ';' === $char ) {
2462 $this->mDTopen
= true;
2463 return $close . '<dt>';
2465 $this->mDTopen
= false;
2466 return $close . '<dd>';
2469 return '<!-- ERR 2 -->';
2474 * @param string $char
2479 function closeList( $char ) {
2480 if ( '*' === $char ) {
2481 $text = "</li>\n</ul>";
2482 } elseif ( '#' === $char ) {
2483 $text = "</li>\n</ol>";
2484 } elseif ( ':' === $char ) {
2485 if ( $this->mDTopen
) {
2486 $this->mDTopen
= false;
2487 $text = "</dt>\n</dl>";
2489 $text = "</dd>\n</dl>";
2492 return '<!-- ERR 3 -->';
2494 return $text . "\n";
2499 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2501 * @param string $text
2502 * @param bool $linestart Whether or not this is at the start of a line.
2504 * @return string The lists rendered as HTML
2506 function doBlockLevels( $text, $linestart ) {
2507 wfProfileIn( __METHOD__
);
2509 # Parsing through the text line by line. The main thing
2510 # happening here is handling of block-level elements p, pre,
2511 # and making lists from lines starting with * # : etc.
2513 $textLines = StringUtils
::explode( "\n", $text );
2515 $lastPrefix = $output = '';
2516 $this->mDTopen
= $inBlockElem = false;
2518 $paragraphStack = false;
2519 $inBlockquote = false;
2521 foreach ( $textLines as $oLine ) {
2523 if ( !$linestart ) {
2533 $lastPrefixLength = strlen( $lastPrefix );
2534 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2535 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2536 # If not in a <pre> element, scan for and figure out what prefixes are there.
2537 if ( !$this->mInPre
) {
2538 # Multiple prefixes may abut each other for nested lists.
2539 $prefixLength = strspn( $oLine, '*#:;' );
2540 $prefix = substr( $oLine, 0, $prefixLength );
2543 # ; and : are both from definition-lists, so they're equivalent
2544 # for the purposes of determining whether or not we need to open/close
2546 $prefix2 = str_replace( ';', ':', $prefix );
2547 $t = substr( $oLine, $prefixLength );
2548 $this->mInPre
= (bool)$preOpenMatch;
2550 # Don't interpret any other prefixes in preformatted text
2552 $prefix = $prefix2 = '';
2557 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2558 # Same as the last item, so no need to deal with nesting or opening stuff
2559 $output .= $this->nextItem( substr( $prefix, -1 ) );
2560 $paragraphStack = false;
2562 if ( substr( $prefix, -1 ) === ';' ) {
2563 # The one nasty exception: definition lists work like this:
2564 # ; title : definition text
2565 # So we check for : in the remainder text to split up the
2566 # title and definition, without b0rking links.
2568 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2570 $output .= $term . $this->nextItem( ':' );
2573 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2574 # We need to open or close prefixes, or both.
2576 # Either open or close a level...
2577 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2578 $paragraphStack = false;
2580 # Close all the prefixes which aren't shared.
2581 while ( $commonPrefixLength < $lastPrefixLength ) {
2582 $output .= $this->closeList( $lastPrefix[$lastPrefixLength - 1] );
2583 --$lastPrefixLength;
2586 # Continue the current prefix if appropriate.
2587 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2588 $output .= $this->nextItem( $prefix[$commonPrefixLength - 1] );
2591 # Open prefixes where appropriate.
2592 while ( $prefixLength > $commonPrefixLength ) {
2593 $char = substr( $prefix, $commonPrefixLength, 1 );
2594 $output .= $this->openList( $char );
2596 if ( ';' === $char ) {
2597 # @todo FIXME: This is dupe of code above
2598 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2600 $output .= $term . $this->nextItem( ':' );
2603 ++
$commonPrefixLength;
2605 $lastPrefix = $prefix2;
2608 # If we have no prefixes, go to paragraph mode.
2609 if ( 0 == $prefixLength ) {
2610 wfProfileIn( __METHOD__
. "-paragraph" );
2611 # No prefix (not in list)--go to paragraph mode
2612 # XXX: use a stack for nestable elements like span, table and div
2613 $openmatch = preg_match(
2614 '/(?:<table|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|'
2615 . '<p|<ul|<ol|<dl|<li|<\\/tr|<\\/td|<\\/th)/iS',
2618 $closematch = preg_match(
2619 '/(?:<\\/table|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'
2620 . '<td|<th|<\\/?blockquote|<\\/?div|<hr|<\\/pre|<\\/p|<\\/mw:|'
2621 . $this->mUniqPrefix
2622 . '-pre|<\\/li|<\\/ul|<\\/ol|<\\/dl|<\\/?center)/iS',
2626 if ( $openmatch or $closematch ) {
2627 $paragraphStack = false;
2628 # @todo bug 5718: paragraph closed
2629 $output .= $this->closeParagraph();
2630 if ( $preOpenMatch and !$preCloseMatch ) {
2631 $this->mInPre
= true;
2634 while ( preg_match( '/<(\\/?)blockquote[\s>]/i', $t, $bqMatch, PREG_OFFSET_CAPTURE
, $bqOffset ) ) {
2635 $inBlockquote = !$bqMatch[1][0]; // is this a close tag?
2636 $bqOffset = $bqMatch[0][1] +
strlen( $bqMatch[0][0] );
2638 $inBlockElem = !$closematch;
2639 } elseif ( !$inBlockElem && !$this->mInPre
) {
2640 if ( ' ' == substr( $t, 0, 1 )
2641 && ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' )
2645 if ( $this->mLastSection
!== 'pre' ) {
2646 $paragraphStack = false;
2647 $output .= $this->closeParagraph() . '<pre>';
2648 $this->mLastSection
= 'pre';
2650 $t = substr( $t, 1 );
2653 if ( trim( $t ) === '' ) {
2654 if ( $paragraphStack ) {
2655 $output .= $paragraphStack . '<br />';
2656 $paragraphStack = false;
2657 $this->mLastSection
= 'p';
2659 if ( $this->mLastSection
!== 'p' ) {
2660 $output .= $this->closeParagraph();
2661 $this->mLastSection
= '';
2662 $paragraphStack = '<p>';
2664 $paragraphStack = '</p><p>';
2668 if ( $paragraphStack ) {
2669 $output .= $paragraphStack;
2670 $paragraphStack = false;
2671 $this->mLastSection
= 'p';
2672 } elseif ( $this->mLastSection
!== 'p' ) {
2673 $output .= $this->closeParagraph() . '<p>';
2674 $this->mLastSection
= 'p';
2679 wfProfileOut( __METHOD__
. "-paragraph" );
2681 # somewhere above we forget to get out of pre block (bug 785)
2682 if ( $preCloseMatch && $this->mInPre
) {
2683 $this->mInPre
= false;
2685 if ( $paragraphStack === false ) {
2686 $output .= $t . "\n";
2689 while ( $prefixLength ) {
2690 $output .= $this->closeList( $prefix2[$prefixLength - 1] );
2693 if ( $this->mLastSection
!= '' ) {
2694 $output .= '</' . $this->mLastSection
. '>';
2695 $this->mLastSection
= '';
2698 wfProfileOut( __METHOD__
);
2703 * Split up a string on ':', ignoring any occurrences inside tags
2704 * to prevent illegal overlapping.
2706 * @param string $str The string to split
2707 * @param string &$before Set to everything before the ':'
2708 * @param string &$after Set to everything after the ':'
2709 * @throws MWException
2710 * @return string The position of the ':', or false if none found
2712 function findColonNoLinks( $str, &$before, &$after ) {
2713 wfProfileIn( __METHOD__
);
2715 $pos = strpos( $str, ':' );
2716 if ( $pos === false ) {
2718 wfProfileOut( __METHOD__
);
2722 $lt = strpos( $str, '<' );
2723 if ( $lt === false ||
$lt > $pos ) {
2724 # Easy; no tag nesting to worry about
2725 $before = substr( $str, 0, $pos );
2726 $after = substr( $str, $pos +
1 );
2727 wfProfileOut( __METHOD__
);
2731 # Ugly state machine to walk through avoiding tags.
2732 $state = self
::COLON_STATE_TEXT
;
2734 $len = strlen( $str );
2735 for ( $i = 0; $i < $len; $i++
) {
2739 # (Using the number is a performance hack for common cases)
2740 case 0: # self::COLON_STATE_TEXT:
2743 # Could be either a <start> tag or an </end> tag
2744 $state = self
::COLON_STATE_TAGSTART
;
2747 if ( $stack == 0 ) {
2749 $before = substr( $str, 0, $i );
2750 $after = substr( $str, $i +
1 );
2751 wfProfileOut( __METHOD__
);
2754 # Embedded in a tag; don't break it.
2757 # Skip ahead looking for something interesting
2758 $colon = strpos( $str, ':', $i );
2759 if ( $colon === false ) {
2760 # Nothing else interesting
2761 wfProfileOut( __METHOD__
);
2764 $lt = strpos( $str, '<', $i );
2765 if ( $stack === 0 ) {
2766 if ( $lt === false ||
$colon < $lt ) {
2768 $before = substr( $str, 0, $colon );
2769 $after = substr( $str, $colon +
1 );
2770 wfProfileOut( __METHOD__
);
2774 if ( $lt === false ) {
2775 # Nothing else interesting to find; abort!
2776 # We're nested, but there's no close tags left. Abort!
2779 # Skip ahead to next tag start
2781 $state = self
::COLON_STATE_TAGSTART
;
2784 case 1: # self::COLON_STATE_TAG:
2789 $state = self
::COLON_STATE_TEXT
;
2792 # Slash may be followed by >?
2793 $state = self
::COLON_STATE_TAGSLASH
;
2799 case 2: # self::COLON_STATE_TAGSTART:
2802 $state = self
::COLON_STATE_CLOSETAG
;
2805 $state = self
::COLON_STATE_COMMENT
;
2808 # Illegal early close? This shouldn't happen D:
2809 $state = self
::COLON_STATE_TEXT
;
2812 $state = self
::COLON_STATE_TAG
;
2815 case 3: # self::COLON_STATE_CLOSETAG:
2820 wfDebug( __METHOD__
. ": Invalid input; too many close tags\n" );
2821 wfProfileOut( __METHOD__
);
2824 $state = self
::COLON_STATE_TEXT
;
2827 case self
::COLON_STATE_TAGSLASH
:
2829 # Yes, a self-closed tag <blah/>
2830 $state = self
::COLON_STATE_TEXT
;
2832 # Probably we're jumping the gun, and this is an attribute
2833 $state = self
::COLON_STATE_TAG
;
2836 case 5: # self::COLON_STATE_COMMENT:
2838 $state = self
::COLON_STATE_COMMENTDASH
;
2841 case self
::COLON_STATE_COMMENTDASH
:
2843 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2845 $state = self
::COLON_STATE_COMMENT
;
2848 case self
::COLON_STATE_COMMENTDASHDASH
:
2850 $state = self
::COLON_STATE_TEXT
;
2852 $state = self
::COLON_STATE_COMMENT
;
2856 wfProfileOut( __METHOD__
);
2857 throw new MWException( "State machine error in " . __METHOD__
);
2861 wfDebug( __METHOD__
. ": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2862 wfProfileOut( __METHOD__
);
2865 wfProfileOut( __METHOD__
);
2870 * Return value of a magic variable (like PAGENAME)
2875 * @param bool|PPFrame $frame
2877 * @throws MWException
2880 function getVariableValue( $index, $frame = false ) {
2881 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2882 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2884 if ( is_null( $this->mTitle
) ) {
2885 // If no title set, bad things are going to happen
2886 // later. Title should always be set since this
2887 // should only be called in the middle of a parse
2888 // operation (but the unit-tests do funky stuff)
2889 throw new MWException( __METHOD__
. ' Should only be '
2890 . ' called while parsing (no title set)' );
2894 * Some of these require message or data lookups and can be
2895 * expensive to check many times.
2897 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2898 if ( isset( $this->mVarCache
[$index] ) ) {
2899 return $this->mVarCache
[$index];
2903 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2904 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2906 $pageLang = $this->getFunctionLang();
2909 case 'currentmonth':
2910 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'm' ) );
2912 case 'currentmonth1':
2913 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2915 case 'currentmonthname':
2916 $value = $pageLang->getMonthName( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2918 case 'currentmonthnamegen':
2919 $value = $pageLang->getMonthNameGen( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2921 case 'currentmonthabbrev':
2922 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getInstance( $ts )->format( 'n' ) );
2925 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'j' ) );
2928 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'd' ) );
2931 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'm' ) );
2934 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2936 case 'localmonthname':
2937 $value = $pageLang->getMonthName( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2939 case 'localmonthnamegen':
2940 $value = $pageLang->getMonthNameGen( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2942 case 'localmonthabbrev':
2943 $value = $pageLang->getMonthAbbreviation( MWTimestamp
::getLocalInstance( $ts )->format( 'n' ) );
2946 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'j' ) );
2949 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'd' ) );
2952 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2955 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2957 case 'fullpagename':
2958 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2960 case 'fullpagenamee':
2961 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2964 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2966 case 'subpagenamee':
2967 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2969 case 'rootpagename':
2970 $value = wfEscapeWikiText( $this->mTitle
->getRootText() );
2972 case 'rootpagenamee':
2973 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
2976 $this->mTitle
->getRootText()
2979 case 'basepagename':
2980 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2982 case 'basepagenamee':
2983 $value = wfEscapeWikiText( wfUrlEncode( str_replace(
2986 $this->mTitle
->getBaseText()
2989 case 'talkpagename':
2990 if ( $this->mTitle
->canTalk() ) {
2991 $talkPage = $this->mTitle
->getTalkPage();
2992 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2997 case 'talkpagenamee':
2998 if ( $this->mTitle
->canTalk() ) {
2999 $talkPage = $this->mTitle
->getTalkPage();
3000 $value = wfEscapeWikiText( $talkPage->getPrefixedURL() );
3005 case 'subjectpagename':
3006 $subjPage = $this->mTitle
->getSubjectPage();
3007 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
3009 case 'subjectpagenamee':
3010 $subjPage = $this->mTitle
->getSubjectPage();
3011 $value = wfEscapeWikiText( $subjPage->getPrefixedURL() );
3013 case 'pageid': // requested in bug 23427
3014 $pageid = $this->getTitle()->getArticleID();
3015 if ( $pageid == 0 ) {
3016 # 0 means the page doesn't exist in the database,
3017 # which means the user is previewing a new page.
3018 # The vary-revision flag must be set, because the magic word
3019 # will have a different value once the page is saved.
3020 $this->mOutput
->setFlag( 'vary-revision' );
3021 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
3023 $value = $pageid ?
$pageid : null;
3026 # Let the edit saving system know we should parse the page
3027 # *after* a revision ID has been assigned.
3028 $this->mOutput
->setFlag( 'vary-revision' );
3029 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
3030 $value = $this->mRevisionId
;
3033 # Let the edit saving system know we should parse the page
3034 # *after* a revision ID has been assigned. This is for null edits.
3035 $this->mOutput
->setFlag( 'vary-revision' );
3036 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
3037 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
3039 case 'revisionday2':
3040 # Let the edit saving system know we should parse the page
3041 # *after* a revision ID has been assigned. This is for null edits.
3042 $this->mOutput
->setFlag( 'vary-revision' );
3043 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
3044 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
3046 case 'revisionmonth':
3047 # Let the edit saving system know we should parse the page
3048 # *after* a revision ID has been assigned. This is for null edits.
3049 $this->mOutput
->setFlag( 'vary-revision' );
3050 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
3051 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
3053 case 'revisionmonth1':
3054 # Let the edit saving system know we should parse the page
3055 # *after* a revision ID has been assigned. This is for null edits.
3056 $this->mOutput
->setFlag( 'vary-revision' );
3057 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
3058 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
3060 case 'revisionyear':
3061 # Let the edit saving system know we should parse the page
3062 # *after* a revision ID has been assigned. This is for null edits.
3063 $this->mOutput
->setFlag( 'vary-revision' );
3064 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
3065 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
3067 case 'revisiontimestamp':
3068 # Let the edit saving system know we should parse the page
3069 # *after* a revision ID has been assigned. This is for null edits.
3070 $this->mOutput
->setFlag( 'vary-revision' );
3071 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
3072 $value = $this->getRevisionTimestamp();
3074 case 'revisionuser':
3075 # Let the edit saving system know we should parse the page
3076 # *after* a revision ID has been assigned. This is for null edits.
3077 $this->mOutput
->setFlag( 'vary-revision' );
3078 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
3079 $value = $this->getRevisionUser();
3081 case 'revisionsize':
3082 # Let the edit saving system know we should parse the page
3083 # *after* a revision ID has been assigned. This is for null edits.
3084 $this->mOutput
->setFlag( 'vary-revision' );
3085 wfDebug( __METHOD__
. ": {{REVISIONSIZE}} used, setting vary-revision...\n" );
3086 $value = $this->getRevisionSize();
3089 $value = str_replace( '_', ' ', $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3092 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
3094 case 'namespacenumber':
3095 $value = $this->mTitle
->getNamespace();
3098 $value = $this->mTitle
->canTalk()
3099 ?
str_replace( '_', ' ', $this->mTitle
->getTalkNsText() )
3103 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
3105 case 'subjectspace':
3106 $value = str_replace( '_', ' ', $this->mTitle
->getSubjectNsText() );
3108 case 'subjectspacee':
3109 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
3111 case 'currentdayname':
3112 $value = $pageLang->getWeekdayName( (int)MWTimestamp
::getInstance( $ts )->format( 'w' ) +
1 );
3115 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'Y' ), true );
3118 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
3121 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'H' ), true );
3124 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3125 # int to remove the padding
3126 $value = $pageLang->formatNum( (int)MWTimestamp
::getInstance( $ts )->format( 'W' ) );
3129 $value = $pageLang->formatNum( MWTimestamp
::getInstance( $ts )->format( 'w' ) );
3131 case 'localdayname':
3132 $value = $pageLang->getWeekdayName(
3133 (int)MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) +
1
3137 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'Y' ), true );
3140 $value = $pageLang->time(
3141 MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' ),
3147 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'H' ), true );
3150 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
3151 # int to remove the padding
3152 $value = $pageLang->formatNum( (int)MWTimestamp
::getLocalInstance( $ts )->format( 'W' ) );
3155 $value = $pageLang->formatNum( MWTimestamp
::getLocalInstance( $ts )->format( 'w' ) );
3157 case 'numberofarticles':
3158 $value = $pageLang->formatNum( SiteStats
::articles() );
3160 case 'numberoffiles':
3161 $value = $pageLang->formatNum( SiteStats
::images() );
3163 case 'numberofusers':
3164 $value = $pageLang->formatNum( SiteStats
::users() );
3166 case 'numberofactiveusers':
3167 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
3169 case 'numberofpages':
3170 $value = $pageLang->formatNum( SiteStats
::pages() );
3172 case 'numberofadmins':
3173 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
3175 case 'numberofedits':
3176 $value = $pageLang->formatNum( SiteStats
::edits() );
3178 case 'numberofviews':
3179 global $wgDisableCounters;
3180 $value = !$wgDisableCounters ?
$pageLang->formatNum( SiteStats
::views() ) : '';
3182 case 'currenttimestamp':
3183 $value = wfTimestamp( TS_MW
, $ts );
3185 case 'localtimestamp':
3186 $value = MWTimestamp
::getLocalInstance( $ts )->format( 'YmdHis' );
3188 case 'currentversion':
3189 $value = SpecialVersion
::getVersion();
3192 return $wgArticlePath;
3198 return $wgServerName;
3200 return $wgScriptPath;
3202 return $wgStylePath;
3203 case 'directionmark':
3204 return $pageLang->getDirMark();
3205 case 'contentlanguage':
3206 global $wgLanguageCode;
3207 return $wgLanguageCode;
3208 case 'cascadingsources':
3209 $value = CoreParserFunctions
::cascadingsources( $this );
3214 'ParserGetVariableValueSwitch',
3215 array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame )
3222 $this->mVarCache
[$index] = $value;
3229 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
3233 function initialiseVariables() {
3234 wfProfileIn( __METHOD__
);
3235 $variableIDs = MagicWord
::getVariableIDs();
3236 $substIDs = MagicWord
::getSubstIDs();
3238 $this->mVariables
= new MagicWordArray( $variableIDs );
3239 $this->mSubstWords
= new MagicWordArray( $substIDs );
3240 wfProfileOut( __METHOD__
);
3244 * Preprocess some wikitext and return the document tree.
3245 * This is the ghost of replace_variables().
3247 * @param string $text The text to parse
3248 * @param int $flags Bitwise combination of:
3249 * - self::PTD_FOR_INCLUSION: Handle "<noinclude>" and "<includeonly>" as if the text is being
3250 * included. Default is to assume a direct page view.
3252 * The generated DOM tree must depend only on the input text and the flags.
3253 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
3255 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
3256 * change in the DOM tree for a given text, must be passed through the section identifier
3257 * in the section edit link and thus back to extractSections().
3259 * The output of this function is currently only cached in process memory, but a persistent
3260 * cache may be implemented at a later date which takes further advantage of these strict
3261 * dependency requirements.
3265 function preprocessToDom( $text, $flags = 0 ) {
3266 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3271 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3277 public static function splitWhitespace( $s ) {
3278 $ltrimmed = ltrim( $s );
3279 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3280 $trimmed = rtrim( $ltrimmed );
3281 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3283 $w2 = substr( $ltrimmed, -$diff );
3287 return array( $w1, $trimmed, $w2 );
3291 * Replace magic variables, templates, and template arguments
3292 * with the appropriate text. Templates are substituted recursively,
3293 * taking care to avoid infinite loops.
3295 * Note that the substitution depends on value of $mOutputType:
3296 * self::OT_WIKI: only {{subst:}} templates
3297 * self::OT_PREPROCESS: templates but not extension tags
3298 * self::OT_HTML: all templates and extension tags
3300 * @param string $text The text to transform
3301 * @param PPFrame $frame Object describing the arguments passed to the template.
3302 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
3303 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
3304 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
3309 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3310 # Is there any text? Also, Prevent too big inclusions!
3311 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3314 wfProfileIn( __METHOD__
);
3316 if ( $frame === false ) {
3317 $frame = $this->getPreprocessor()->newFrame();
3318 } elseif ( !( $frame instanceof PPFrame
) ) {
3319 wfDebug( __METHOD__
. " called using plain parameters instead of "
3320 . "a PPFrame instance. Creating custom frame.\n" );
3321 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3324 $dom = $this->preprocessToDom( $text );
3325 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3326 $text = $frame->expand( $dom, $flags );
3328 wfProfileOut( __METHOD__
);
3333 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3335 * @param array $args
3339 static function createAssocArgs( $args ) {
3340 $assocArgs = array();
3342 foreach ( $args as $arg ) {
3343 $eqpos = strpos( $arg, '=' );
3344 if ( $eqpos === false ) {
3345 $assocArgs[$index++
] = $arg;
3347 $name = trim( substr( $arg, 0, $eqpos ) );
3348 $value = trim( substr( $arg, $eqpos +
1 ) );
3349 if ( $value === false ) {
3352 if ( $name !== false ) {
3353 $assocArgs[$name] = $value;
3362 * Warn the user when a parser limitation is reached
3363 * Will warn at most once the user per limitation type
3365 * @param string $limitationType Should be one of:
3366 * 'expensive-parserfunction' (corresponding messages:
3367 * 'expensive-parserfunction-warning',
3368 * 'expensive-parserfunction-category')
3369 * 'post-expand-template-argument' (corresponding messages:
3370 * 'post-expand-template-argument-warning',
3371 * 'post-expand-template-argument-category')
3372 * 'post-expand-template-inclusion' (corresponding messages:
3373 * 'post-expand-template-inclusion-warning',
3374 * 'post-expand-template-inclusion-category')
3375 * 'node-count-exceeded' (corresponding messages:
3376 * 'node-count-exceeded-warning',
3377 * 'node-count-exceeded-category')
3378 * 'expansion-depth-exceeded' (corresponding messages:
3379 * 'expansion-depth-exceeded-warning',
3380 * 'expansion-depth-exceeded-category')
3381 * @param string|int|null $current Current value
3382 * @param string|int|null $max Maximum allowed, when an explicit limit has been
3383 * exceeded, provide the values (optional)
3385 function limitationWarn( $limitationType, $current = '', $max = '' ) {
3386 # does no harm if $current and $max are present but are unnecessary for the message
3387 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3388 ->inLanguage( $this->mOptions
->getUserLangObj() )->text();
3389 $this->mOutput
->addWarning( $warning );
3390 $this->addTrackingCategory( "$limitationType-category" );
3394 * Return the text of a template, after recursively
3395 * replacing any variables or templates within the template.
3397 * @param array $piece The parts of the template
3398 * $piece['title']: the title, i.e. the part before the |
3399 * $piece['parts']: the parameter array
3400 * $piece['lineStart']: whether the brace was at the start of a line
3401 * @param PPFrame $frame The current frame, contains template arguments
3403 * @return string The text of the template
3406 function braceSubstitution( $piece, $frame ) {
3407 wfProfileIn( __METHOD__
);
3408 wfProfileIn( __METHOD__
. '-setup' );
3412 // $text has been filled
3414 // wiki markup in $text should be escaped
3416 // $text is HTML, armour it against wikitext transformation
3418 // Force interwiki transclusion to be done in raw mode not rendered
3419 $forceRawInterwiki = false;
3420 // $text is a DOM node needing expansion in a child frame
3421 $isChildObj = false;
3422 // $text is a DOM node needing expansion in the current frame
3423 $isLocalObj = false;
3425 # Title object, where $text came from
3428 # $part1 is the bit before the first |, and must contain only title characters.
3429 # Various prefixes will be stripped from it later.
3430 $titleWithSpaces = $frame->expand( $piece['title'] );
3431 $part1 = trim( $titleWithSpaces );
3434 # Original title text preserved for various purposes
3435 $originalTitle = $part1;
3437 # $args is a list of argument nodes, starting from index 0, not including $part1
3438 # @todo FIXME: If piece['parts'] is null then the call to getLength()
3439 # below won't work b/c this $args isn't an object
3440 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3441 wfProfileOut( __METHOD__
. '-setup' );
3443 $titleProfileIn = null; // profile templates
3446 wfProfileIn( __METHOD__
. '-modifiers' );
3449 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3451 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3452 # Decide whether to expand template or keep wikitext as-is.
3453 if ( $this->ot
['wiki'] ) {
3454 if ( $substMatch === false ) {
3455 $literal = true; # literal when in PST with no prefix
3457 $literal = false; # expand when in PST with subst: or safesubst:
3460 if ( $substMatch == 'subst' ) {
3461 $literal = true; # literal when not in PST with plain subst:
3463 $literal = false; # expand when not in PST with safesubst: or no prefix
3467 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3474 if ( !$found && $args->getLength() == 0 ) {
3475 $id = $this->mVariables
->matchStartToEnd( $part1 );
3476 if ( $id !== false ) {
3477 $text = $this->getVariableValue( $id, $frame );
3478 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3479 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3485 # MSG, MSGNW and RAW
3488 $mwMsgnw = MagicWord
::get( 'msgnw' );
3489 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3492 # Remove obsolete MSG:
3493 $mwMsg = MagicWord
::get( 'msg' );
3494 $mwMsg->matchStartAndRemove( $part1 );
3498 $mwRaw = MagicWord
::get( 'raw' );
3499 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3500 $forceRawInterwiki = true;
3503 wfProfileOut( __METHOD__
. '-modifiers' );
3507 wfProfileIn( __METHOD__
. '-pfunc' );
3509 $colonPos = strpos( $part1, ':' );
3510 if ( $colonPos !== false ) {
3511 $func = substr( $part1, 0, $colonPos );
3512 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3513 for ( $i = 0; $i < $args->getLength(); $i++
) {
3514 $funcArgs[] = $args->item( $i );
3517 $result = $this->callParserFunction( $frame, $func, $funcArgs );
3518 } catch ( Exception
$ex ) {
3519 wfProfileOut( __METHOD__
. '-pfunc' );
3520 wfProfileOut( __METHOD__
);
3524 # The interface for parser functions allows for extracting
3525 # flags into the local scope. Extract any forwarded flags
3529 wfProfileOut( __METHOD__
. '-pfunc' );
3532 # Finish mangling title and then check for loops.
3533 # Set $title to a Title object and $titleText to the PDBK
3536 # Split the title into page and subpage
3538 $relative = $this->maybeDoSubpageLink( $part1, $subpage );
3539 if ( $part1 !== $relative ) {
3541 $ns = $this->mTitle
->getNamespace();
3543 $title = Title
::newFromText( $part1, $ns );
3545 $titleText = $title->getPrefixedText();
3546 # Check for language variants if the template is not found
3547 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3548 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3550 # Do recursion depth check
3551 $limit = $this->mOptions
->getMaxTemplateDepth();
3552 if ( $frame->depth
>= $limit ) {
3554 $text = '<span class="error">'
3555 . wfMessage( 'parser-template-recursion-depth-warning' )
3556 ->numParams( $limit )->inContentLanguage()->text()
3562 # Load from database
3563 if ( !$found && $title ) {
3564 if ( !Profiler
::instance()->isPersistent() ) {
3565 # Too many unique items can kill profiling DBs/collectors
3566 $titleProfileIn = __METHOD__
. "-title-" . $title->getPrefixedDBkey();
3567 wfProfileIn( $titleProfileIn ); // template in
3569 wfProfileIn( __METHOD__
. '-loadtpl' );
3570 if ( !$title->isExternal() ) {
3571 if ( $title->isSpecialPage()
3572 && $this->mOptions
->getAllowSpecialInclusion()
3573 && $this->ot
['html']
3575 // Pass the template arguments as URL parameters.
3576 // "uselang" will have no effect since the Language object
3577 // is forced to the one defined in ParserOptions.
3578 $pageArgs = array();
3579 $argsLength = $args->getLength();
3580 for ( $i = 0; $i < $argsLength; $i++
) {
3581 $bits = $args->item( $i )->splitArg();
3582 if ( strval( $bits['index'] ) === '' ) {
3583 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3584 $value = trim( $frame->expand( $bits['value'] ) );
3585 $pageArgs[$name] = $value;
3589 // Create a new context to execute the special page
3590 $context = new RequestContext
;
3591 $context->setTitle( $title );
3592 $context->setRequest( new FauxRequest( $pageArgs ) );
3593 $context->setUser( $this->getUser() );
3594 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3595 $ret = SpecialPageFactory
::capturePath( $title, $context );
3597 $text = $context->getOutput()->getHTML();
3598 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3601 $this->disableCache();
3603 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3604 $found = false; # access denied
3605 wfDebug( __METHOD__
. ": template inclusion denied for " .
3606 $title->getPrefixedDBkey() . "\n" );
3608 list( $text, $title ) = $this->getTemplateDom( $title );
3609 if ( $text !== false ) {
3615 # If the title is valid but undisplayable, make a link to it
3616 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3617 $text = "[[:$titleText]]";
3620 } elseif ( $title->isTrans() ) {
3621 # Interwiki transclusion
3622 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3623 $text = $this->interwikiTransclude( $title, 'render' );
3626 $text = $this->interwikiTransclude( $title, 'raw' );
3627 # Preprocess it like a template
3628 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3634 # Do infinite loop check
3635 # This has to be done after redirect resolution to avoid infinite loops via redirects
3636 if ( !$frame->loopCheck( $title ) ) {
3638 $text = '<span class="error">'
3639 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3641 wfDebug( __METHOD__
. ": template loop broken at '$titleText'\n" );
3643 wfProfileOut( __METHOD__
. '-loadtpl' );
3646 # If we haven't found text to substitute by now, we're done
3647 # Recover the source wikitext and return it
3649 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3650 if ( $titleProfileIn ) {
3651 wfProfileOut( $titleProfileIn ); // template out
3653 wfProfileOut( __METHOD__
);
3654 return array( 'object' => $text );
3657 # Expand DOM-style return values in a child frame
3658 if ( $isChildObj ) {
3659 # Clean up argument array
3660 $newFrame = $frame->newChild( $args, $title );
3663 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3664 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3665 # Expansion is eligible for the empty-frame cache
3666 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3667 $text = $this->mTplExpandCache
[$titleText];
3669 $text = $newFrame->expand( $text );
3670 $this->mTplExpandCache
[$titleText] = $text;
3673 # Uncached expansion
3674 $text = $newFrame->expand( $text );
3677 if ( $isLocalObj && $nowiki ) {
3678 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3679 $isLocalObj = false;
3682 if ( $titleProfileIn ) {
3683 wfProfileOut( $titleProfileIn ); // template out
3686 # Replace raw HTML by a placeholder
3688 $text = $this->insertStripItem( $text );
3689 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3690 # Escape nowiki-style return values
3691 $text = wfEscapeWikiText( $text );
3692 } elseif ( is_string( $text )
3693 && !$piece['lineStart']
3694 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text )
3696 # Bug 529: if the template begins with a table or block-level
3697 # element, it should be treated as beginning a new line.
3698 # This behavior is somewhat controversial.
3699 $text = "\n" . $text;
3702 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3703 # Error, oversize inclusion
3704 if ( $titleText !== false ) {
3705 # Make a working, properly escaped link if possible (bug 23588)
3706 $text = "[[:$titleText]]";
3708 # This will probably not be a working link, but at least it may
3709 # provide some hint of where the problem is
3710 preg_replace( '/^:/', '', $originalTitle );
3711 $text = "[[:$originalTitle]]";
3713 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, '
3714 . 'post-expand include size too large -->' );
3715 $this->limitationWarn( 'post-expand-template-inclusion' );
3718 if ( $isLocalObj ) {
3719 $ret = array( 'object' => $text );
3721 $ret = array( 'text' => $text );
3724 wfProfileOut( __METHOD__
);
3729 * Call a parser function and return an array with text and flags.
3731 * The returned array will always contain a boolean 'found', indicating
3732 * whether the parser function was found or not. It may also contain the
3734 * text: string|object, resulting wikitext or PP DOM object
3735 * isHTML: bool, $text is HTML, armour it against wikitext transformation
3736 * isChildObj: bool, $text is a DOM node needing expansion in a child frame
3737 * isLocalObj: bool, $text is a DOM node needing expansion in the current frame
3738 * nowiki: bool, wiki markup in $text should be escaped
3741 * @param PPFrame $frame The current frame, contains template arguments
3742 * @param string $function Function name
3743 * @param array $args Arguments to the function
3744 * @throws MWException
3747 public function callParserFunction( $frame, $function, array $args = array() ) {
3750 wfProfileIn( __METHOD__
);
3752 # Case sensitive functions
3753 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3754 $function = $this->mFunctionSynonyms
[1][$function];
3756 # Case insensitive functions
3757 $function = $wgContLang->lc( $function );
3758 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3759 $function = $this->mFunctionSynonyms
[0][$function];
3761 wfProfileOut( __METHOD__
);
3762 return array( 'found' => false );
3766 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3767 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3769 # Workaround for PHP bug 35229 and similar
3770 if ( !is_callable( $callback ) ) {
3771 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3772 wfProfileOut( __METHOD__
);
3773 throw new MWException( "Tag hook for $function is not callable\n" );
3776 $allArgs = array( &$this );
3777 if ( $flags & SFH_OBJECT_ARGS
) {
3778 # Convert arguments to PPNodes and collect for appending to $allArgs
3779 $funcArgs = array();
3780 foreach ( $args as $k => $v ) {
3781 if ( $v instanceof PPNode ||
$k === 0 ) {
3784 $funcArgs[] = $this->mPreprocessor
->newPartNodeArray( array( $k => $v ) )->item( 0 );
3788 # Add a frame parameter, and pass the arguments as an array
3789 $allArgs[] = $frame;
3790 $allArgs[] = $funcArgs;
3792 # Convert arguments to plain text and append to $allArgs
3793 foreach ( $args as $k => $v ) {
3794 if ( $v instanceof PPNode
) {
3795 $allArgs[] = trim( $frame->expand( $v ) );
3796 } elseif ( is_int( $k ) && $k >= 0 ) {
3797 $allArgs[] = trim( $v );
3799 $allArgs[] = trim( "$k=$v" );
3804 $result = call_user_func_array( $callback, $allArgs );
3806 # The interface for function hooks allows them to return a wikitext
3807 # string or an array containing the string and any flags. This mungs
3808 # things around to match what this method should return.
3809 if ( !is_array( $result ) ) {
3815 if ( isset( $result[0] ) && !isset( $result['text'] ) ) {
3816 $result['text'] = $result[0];
3818 unset( $result[0] );
3825 $preprocessFlags = 0;
3826 if ( isset( $result['noparse'] ) ) {
3827 $noparse = $result['noparse'];
3829 if ( isset( $result['preprocessFlags'] ) ) {
3830 $preprocessFlags = $result['preprocessFlags'];
3834 $result['text'] = $this->preprocessToDom( $result['text'], $preprocessFlags );
3835 $result['isChildObj'] = true;
3837 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3838 wfProfileOut( __METHOD__
);
3844 * Get the semi-parsed DOM representation of a template with a given title,
3845 * and its redirect destination title. Cached.
3847 * @param Title $title
3851 function getTemplateDom( $title ) {
3852 $cacheTitle = $title;
3853 $titleText = $title->getPrefixedDBkey();
3855 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3856 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3857 $title = Title
::makeTitle( $ns, $dbk );
3858 $titleText = $title->getPrefixedDBkey();
3860 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3861 return array( $this->mTplDomCache
[$titleText], $title );
3864 # Cache miss, go to the database
3865 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3867 if ( $text === false ) {
3868 $this->mTplDomCache
[$titleText] = false;
3869 return array( false, $title );
3872 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3873 $this->mTplDomCache
[$titleText] = $dom;
3875 if ( !$title->equals( $cacheTitle ) ) {
3876 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3877 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3880 return array( $dom, $title );
3884 * Fetch the unparsed text of a template and register a reference to it.
3885 * @param Title $title
3886 * @return array ( string or false, Title )
3888 function fetchTemplateAndTitle( $title ) {
3889 // Defaults to Parser::statelessFetchTemplate()
3890 $templateCb = $this->mOptions
->getTemplateCallback();
3891 $stuff = call_user_func( $templateCb, $title, $this );
3892 $text = $stuff['text'];
3893 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3894 if ( isset( $stuff['deps'] ) ) {
3895 foreach ( $stuff['deps'] as $dep ) {
3896 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3897 if ( $dep['title']->equals( $this->getTitle() ) ) {
3898 // If we transclude ourselves, the final result
3899 // will change based on the new version of the page
3900 $this->mOutput
->setFlag( 'vary-revision' );
3904 return array( $text, $finalTitle );
3908 * Fetch the unparsed text of a template and register a reference to it.
3909 * @param Title $title
3910 * @return string|bool
3912 function fetchTemplate( $title ) {
3913 $rv = $this->fetchTemplateAndTitle( $title );
3918 * Static function to get a template
3919 * Can be overridden via ParserOptions::setTemplateCallback().
3921 * @param Title $title
3922 * @param bool|Parser $parser
3926 static function statelessFetchTemplate( $title, $parser = false ) {
3927 $text = $skip = false;
3928 $finalTitle = $title;
3931 # Loop to fetch the article, with up to 1 redirect
3932 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3933 # Give extensions a chance to select the revision instead
3934 $id = false; # Assume current
3935 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3936 array( $parser, $title, &$skip, &$id ) );
3942 'page_id' => $title->getArticleID(),
3949 ? Revision
::newFromId( $id )
3950 : Revision
::newFromTitle( $title, false, Revision
::READ_NORMAL
);
3951 $rev_id = $rev ?
$rev->getId() : 0;
3952 # If there is no current revision, there is no page
3953 if ( $id === false && !$rev ) {
3954 $linkCache = LinkCache
::singleton();
3955 $linkCache->addBadLinkObj( $title );
3960 'page_id' => $title->getArticleID(),
3961 'rev_id' => $rev_id );
3962 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3963 # We fetched a rev from a different title; register it too...
3965 'title' => $rev->getTitle(),
3966 'page_id' => $rev->getPage(),
3967 'rev_id' => $rev_id );
3971 $content = $rev->getContent();
3972 $text = $content ?
$content->getWikitextForTransclusion() : null;
3974 if ( $text === false ||
$text === null ) {
3978 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3980 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3981 if ( !$message->exists() ) {
3985 $content = $message->content();
3986 $text = $message->plain();
3994 $finalTitle = $title;
3995 $title = $content->getRedirectTarget();
3999 'finalTitle' => $finalTitle,
4004 * Fetch a file and its title and register a reference to it.
4005 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4006 * @param Title $title
4007 * @param array $options Array of options to RepoGroup::findFile
4010 function fetchFile( $title, $options = array() ) {
4011 $res = $this->fetchFileAndTitle( $title, $options );
4016 * Fetch a file and its title and register a reference to it.
4017 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
4018 * @param Title $title
4019 * @param array $options Array of options to RepoGroup::findFile
4020 * @return array ( File or false, Title of file )
4022 function fetchFileAndTitle( $title, $options = array() ) {
4023 $file = $this->fetchFileNoRegister( $title, $options );
4025 $time = $file ?
$file->getTimestamp() : false;
4026 $sha1 = $file ?
$file->getSha1() : false;
4027 # Register the file as a dependency...
4028 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4029 if ( $file && !$title->equals( $file->getTitle() ) ) {
4030 # Update fetched file title
4031 $title = $file->getTitle();
4032 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
4034 return array( $file, $title );
4038 * Helper function for fetchFileAndTitle.
4040 * Also useful if you need to fetch a file but not use it yet,
4041 * for example to get the file's handler.
4043 * @param Title $title
4044 * @param array $options Array of options to RepoGroup::findFile
4047 protected function fetchFileNoRegister( $title, $options = array() ) {
4048 if ( isset( $options['broken'] ) ) {
4049 $file = false; // broken thumbnail forced by hook
4050 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
4051 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
4052 } else { // get by (name,timestamp)
4053 $file = wfFindFile( $title, $options );
4059 * Transclude an interwiki link.
4061 * @param Title $title
4062 * @param string $action
4066 function interwikiTransclude( $title, $action ) {
4067 global $wgEnableScaryTranscluding;
4069 if ( !$wgEnableScaryTranscluding ) {
4070 return wfMessage( 'scarytranscludedisabled' )->inContentLanguage()->text();
4073 $url = $title->getFullURL( array( 'action' => $action ) );
4075 if ( strlen( $url ) > 255 ) {
4076 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
4078 return $this->fetchScaryTemplateMaybeFromCache( $url );
4082 * @param string $url
4083 * @return mixed|string
4085 function fetchScaryTemplateMaybeFromCache( $url ) {
4086 global $wgTranscludeCacheExpiry;
4087 $dbr = wfGetDB( DB_SLAVE
);
4088 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
4089 $obj = $dbr->selectRow( 'transcache', array( 'tc_time', 'tc_contents' ),
4090 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
4092 return $obj->tc_contents
;
4095 $req = MWHttpRequest
::factory( $url );
4096 $status = $req->execute(); // Status object
4097 if ( $status->isOK() ) {
4098 $text = $req->getContent();
4099 } elseif ( $req->getStatus() != 200 ) {
4100 // Though we failed to fetch the content, this status is useless.
4101 return wfMessage( 'scarytranscludefailed-httpstatus' )
4102 ->params( $url, $req->getStatus() /* HTTP status */ )->inContentLanguage()->text();
4104 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
4107 $dbw = wfGetDB( DB_MASTER
);
4108 $dbw->replace( 'transcache', array( 'tc_url' ), array(
4110 'tc_time' => $dbw->timestamp( time() ),
4111 'tc_contents' => $text
4117 * Triple brace replacement -- used for template arguments
4120 * @param array $piece
4121 * @param PPFrame $frame
4125 function argSubstitution( $piece, $frame ) {
4126 wfProfileIn( __METHOD__
);
4129 $parts = $piece['parts'];
4130 $nameWithSpaces = $frame->expand( $piece['title'] );
4131 $argName = trim( $nameWithSpaces );
4133 $text = $frame->getArgument( $argName );
4134 if ( $text === false && $parts->getLength() > 0
4135 && ( $this->ot
['html']
4137 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
4140 # No match in frame, use the supplied default
4141 $object = $parts->item( 0 )->getChildren();
4143 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
4144 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
4145 $this->limitationWarn( 'post-expand-template-argument' );
4148 if ( $text === false && $object === false ) {
4150 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
4152 if ( $error !== false ) {
4155 if ( $object !== false ) {
4156 $ret = array( 'object' => $object );
4158 $ret = array( 'text' => $text );
4161 wfProfileOut( __METHOD__
);
4166 * Return the text to be used for a given extension tag.
4167 * This is the ghost of strip().
4169 * @param array $params Associative array of parameters:
4170 * name PPNode for the tag name
4171 * attr PPNode for unparsed text where tag attributes are thought to be
4172 * attributes Optional associative array of parsed attributes
4173 * inner Contents of extension element
4174 * noClose Original text did not have a close tag
4175 * @param PPFrame $frame
4177 * @throws MWException
4180 function extensionSubstitution( $params, $frame ) {
4181 $name = $frame->expand( $params['name'] );
4182 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
4183 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
4184 $marker = "{$this->mUniqPrefix}-$name-"
4185 . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
4187 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower( $name )] ) &&
4188 ( $this->ot
['html'] ||
$this->ot
['pre'] );
4189 if ( $isFunctionTag ) {
4190 $markerType = 'none';
4192 $markerType = 'general';
4194 if ( $this->ot
['html'] ||
$isFunctionTag ) {
4195 $name = strtolower( $name );
4196 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
4197 if ( isset( $params['attributes'] ) ) {
4198 $attributes = $attributes +
$params['attributes'];
4201 if ( isset( $this->mTagHooks
[$name] ) ) {
4202 # Workaround for PHP bug 35229 and similar
4203 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
4204 throw new MWException( "Tag hook for $name is not callable\n" );
4206 $output = call_user_func_array( $this->mTagHooks
[$name],
4207 array( $content, $attributes, $this, $frame ) );
4208 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
4209 list( $callback, ) = $this->mFunctionTagHooks
[$name];
4210 if ( !is_callable( $callback ) ) {
4211 throw new MWException( "Tag hook for $name is not callable\n" );
4214 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
4216 $output = '<span class="error">Invalid tag extension name: ' .
4217 htmlspecialchars( $name ) . '</span>';
4220 if ( is_array( $output ) ) {
4221 # Extract flags to local scope (to override $markerType)
4223 $output = $flags[0];
4228 if ( is_null( $attrText ) ) {
4231 if ( isset( $params['attributes'] ) ) {
4232 foreach ( $params['attributes'] as $attrName => $attrValue ) {
4233 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
4234 htmlspecialchars( $attrValue ) . '"';
4237 if ( $content === null ) {
4238 $output = "<$name$attrText/>";
4240 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
4241 $output = "<$name$attrText>$content$close";
4245 if ( $markerType === 'none' ) {
4247 } elseif ( $markerType === 'nowiki' ) {
4248 $this->mStripState
->addNoWiki( $marker, $output );
4249 } elseif ( $markerType === 'general' ) {
4250 $this->mStripState
->addGeneral( $marker, $output );
4252 throw new MWException( __METHOD__
. ': invalid marker type' );
4258 * Increment an include size counter
4260 * @param string $type The type of expansion
4261 * @param int $size The size of the text
4262 * @return bool False if this inclusion would take it over the maximum, true otherwise
4264 function incrementIncludeSize( $type, $size ) {
4265 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
4268 $this->mIncludeSizes
[$type] +
= $size;
4274 * Increment the expensive function count
4276 * @return bool False if the limit has been exceeded
4278 function incrementExpensiveFunctionCount() {
4279 $this->mExpensiveFunctionCount++
;
4280 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
4284 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
4285 * Fills $this->mDoubleUnderscores, returns the modified text
4287 * @param string $text
4291 function doDoubleUnderscore( $text ) {
4292 wfProfileIn( __METHOD__
);
4294 # The position of __TOC__ needs to be recorded
4295 $mw = MagicWord
::get( 'toc' );
4296 if ( $mw->match( $text ) ) {
4297 $this->mShowToc
= true;
4298 $this->mForceTocPosition
= true;
4300 # Set a placeholder. At the end we'll fill it in with the TOC.
4301 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
4303 # Only keep the first one.
4304 $text = $mw->replace( '', $text );
4307 # Now match and remove the rest of them
4308 $mwa = MagicWord
::getDoubleUnderscoreArray();
4309 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
4311 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
4312 $this->mOutput
->mNoGallery
= true;
4314 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
4315 $this->mShowToc
= false;
4317 if ( isset( $this->mDoubleUnderscores
['hiddencat'] )
4318 && $this->mTitle
->getNamespace() == NS_CATEGORY
4320 $this->addTrackingCategory( 'hidden-category-category' );
4322 # (bug 8068) Allow control over whether robots index a page.
4324 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
4325 # is not desirable, the last one on the page should win.
4326 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
4327 $this->mOutput
->setIndexPolicy( 'noindex' );
4328 $this->addTrackingCategory( 'noindex-category' );
4330 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
4331 $this->mOutput
->setIndexPolicy( 'index' );
4332 $this->addTrackingCategory( 'index-category' );
4335 # Cache all double underscores in the database
4336 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
4337 $this->mOutput
->setProperty( $key, '' );
4340 wfProfileOut( __METHOD__
);
4345 * Add a tracking category, getting the title from a system message,
4346 * or print a debug message if the title is invalid.
4348 * Please add any message that you use with this function to
4349 * $wgTrackingCategories. That way they will be listed on
4350 * Special:TrackingCategories.
4352 * @param string $msg Message key
4353 * @return bool Whether the addition was successful
4355 public function addTrackingCategory( $msg ) {
4356 if ( $this->mTitle
->getNamespace() === NS_SPECIAL
) {
4357 wfDebug( __METHOD__
. ": Not adding tracking category $msg to special page!\n" );
4360 // Important to parse with correct title (bug 31469)
4361 $cat = wfMessage( $msg )
4362 ->title( $this->getTitle() )
4363 ->inContentLanguage()
4366 # Allow tracking categories to be disabled by setting them to "-"
4367 if ( $cat === '-' ) {
4371 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
4372 if ( $containerCategory ) {
4373 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
4376 wfDebug( __METHOD__
. ": [[MediaWiki:$msg]] is not a valid title!\n" );
4382 * This function accomplishes several tasks:
4383 * 1) Auto-number headings if that option is enabled
4384 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
4385 * 3) Add a Table of contents on the top for users who have enabled the option
4386 * 4) Auto-anchor headings
4388 * It loops through all headlines, collects the necessary data, then splits up the
4389 * string and re-inserts the newly formatted headlines.
4391 * @param string $text
4392 * @param string $origText Original, untouched wikitext
4393 * @param bool $isMain
4394 * @return mixed|string
4397 function formatHeadings( $text, $origText, $isMain = true ) {
4398 global $wgMaxTocLevel, $wgExperimentalHtmlIds;
4400 # Inhibit editsection links if requested in the page
4401 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4402 $maybeShowEditLink = $showEditLink = false;
4404 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4405 $showEditLink = $this->mOptions
->getEditSection();
4407 if ( $showEditLink ) {
4408 $this->mOutput
->setEditSectionTokens( true );
4411 # Get all headlines for numbering them and adding funky stuff like [edit]
4412 # links - this is for later, but we need the number of headlines right now
4414 $numMatches = preg_match_all(
4415 '/<H(?P<level>[1-6])(?P<attrib>.*?' . '>)\s*(?P<header>[\s\S]*?)\s*<\/H[1-6] *>/i',
4420 # if there are fewer than 4 headlines in the article, do not show TOC
4421 # unless it's been explicitly enabled.
4422 $enoughToc = $this->mShowToc
&&
4423 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4425 # Allow user to stipulate that a page should have a "new section"
4426 # link added via __NEWSECTIONLINK__
4427 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4428 $this->mOutput
->setNewSection( true );
4431 # Allow user to remove the "new section"
4432 # link via __NONEWSECTIONLINK__
4433 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4434 $this->mOutput
->hideNewSection( true );
4437 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4438 # override above conditions and always show TOC above first header
4439 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4440 $this->mShowToc
= true;
4448 # Ugh .. the TOC should have neat indentation levels which can be
4449 # passed to the skin functions. These are determined here
4453 $sublevelCount = array();
4454 $levelCount = array();
4459 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4460 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4461 $oldType = $this->mOutputType
;
4462 $this->setOutputType( self
::OT_WIKI
);
4463 $frame = $this->getPreprocessor()->newFrame();
4464 $root = $this->preprocessToDom( $origText );
4465 $node = $root->getFirstChild();
4470 foreach ( $matches[3] as $headline ) {
4471 $isTemplate = false;
4473 $sectionIndex = false;
4475 $markerMatches = array();
4476 if ( preg_match( "/^$markerRegex/", $headline, $markerMatches ) ) {
4477 $serial = $markerMatches[1];
4478 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4479 $isTemplate = ( $titleText != $baseTitleText );
4480 $headline = preg_replace( "/^$markerRegex\\s*/", "", $headline );
4484 $prevlevel = $level;
4486 $level = $matches[1][$headlineCount];
4488 if ( $level > $prevlevel ) {
4489 # Increase TOC level
4491 $sublevelCount[$toclevel] = 0;
4492 if ( $toclevel < $wgMaxTocLevel ) {
4493 $prevtoclevel = $toclevel;
4494 $toc .= Linker
::tocIndent();
4497 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4498 # Decrease TOC level, find level to jump to
4500 for ( $i = $toclevel; $i > 0; $i-- ) {
4501 if ( $levelCount[$i] == $level ) {
4502 # Found last matching level
4505 } elseif ( $levelCount[$i] < $level ) {
4506 # Found first matching level below current level
4514 if ( $toclevel < $wgMaxTocLevel ) {
4515 if ( $prevtoclevel < $wgMaxTocLevel ) {
4516 # Unindent only if the previous toc level was shown :p
4517 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4518 $prevtoclevel = $toclevel;
4520 $toc .= Linker
::tocLineEnd();
4524 # No change in level, end TOC line
4525 if ( $toclevel < $wgMaxTocLevel ) {
4526 $toc .= Linker
::tocLineEnd();
4530 $levelCount[$toclevel] = $level;
4532 # count number of headlines for each level
4533 $sublevelCount[$toclevel]++
;
4535 for ( $i = 1; $i <= $toclevel; $i++
) {
4536 if ( !empty( $sublevelCount[$i] ) ) {
4540 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4545 # The safe header is a version of the header text safe to use for links
4547 # Remove link placeholders by the link text.
4548 # <!--LINK number-->
4550 # link text with suffix
4551 # Do this before unstrip since link text can contain strip markers
4552 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4554 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4555 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4557 # Strip out HTML (first regex removes any tag not allowed)
4559 # * <sup> and <sub> (bug 8393)
4562 # * <span dir="rtl"> and <span dir="ltr"> (bug 35167)
4564 # We strip any parameter from accepted tags (second regex), except dir="rtl|ltr" from <span>,
4565 # to allow setting directionality in toc items.
4566 $tocline = preg_replace(
4568 '#<(?!/?(span|sup|sub|i|b)(?: [^>]*)?>).*?' . '>#',
4569 '#<(/?(?:span(?: dir="(?:rtl|ltr)")?|sup|sub|i|b))(?: .*?)?' . '>#'
4571 array( '', '<$1>' ),
4574 $tocline = trim( $tocline );
4576 # For the anchor, strip out HTML-y stuff period
4577 $safeHeadline = preg_replace( '/<.*?' . '>/', '', $safeHeadline );
4578 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4580 # Save headline for section edit hint before it's escaped
4581 $headlineHint = $safeHeadline;
4583 if ( $wgExperimentalHtmlIds ) {
4584 # For reverse compatibility, provide an id that's
4585 # HTML4-compatible, like we used to.
4587 # It may be worth noting, academically, that it's possible for
4588 # the legacy anchor to conflict with a non-legacy headline
4589 # anchor on the page. In this case likely the "correct" thing
4590 # would be to either drop the legacy anchors or make sure
4591 # they're numbered first. However, this would require people
4592 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4593 # manually, so let's not bother worrying about it.
4594 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4595 array( 'noninitial', 'legacy' ) );
4596 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4598 if ( $legacyHeadline == $safeHeadline ) {
4599 # No reason to have both (in fact, we can't)
4600 $legacyHeadline = false;
4603 $legacyHeadline = false;
4604 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4608 # HTML names must be case-insensitively unique (bug 10721).
4609 # This does not apply to Unicode characters per
4610 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4611 # @todo FIXME: We may be changing them depending on the current locale.
4612 $arrayKey = strtolower( $safeHeadline );
4613 if ( $legacyHeadline === false ) {
4614 $legacyArrayKey = false;
4616 $legacyArrayKey = strtolower( $legacyHeadline );
4619 # count how many in assoc. array so we can track dupes in anchors
4620 if ( isset( $refers[$arrayKey] ) ) {
4621 $refers[$arrayKey]++
;
4623 $refers[$arrayKey] = 1;
4625 if ( isset( $refers[$legacyArrayKey] ) ) {
4626 $refers[$legacyArrayKey]++
;
4628 $refers[$legacyArrayKey] = 1;
4631 # Don't number the heading if it is the only one (looks silly)
4632 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4633 # the two are different if the line contains a link
4634 $headline = Html
::element(
4636 array( 'class' => 'mw-headline-number' ),
4638 ) . ' ' . $headline;
4641 # Create the anchor for linking from the TOC to the section
4642 $anchor = $safeHeadline;
4643 $legacyAnchor = $legacyHeadline;
4644 if ( $refers[$arrayKey] > 1 ) {
4645 $anchor .= '_' . $refers[$arrayKey];
4647 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4648 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4650 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4651 $toc .= Linker
::tocLine( $anchor, $tocline,
4652 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4655 # Add the section to the section tree
4656 # Find the DOM node for this header
4657 $noOffset = ( $isTemplate ||
$sectionIndex === false );
4658 while ( $node && !$noOffset ) {
4659 if ( $node->getName() === 'h' ) {
4660 $bits = $node->splitHeading();
4661 if ( $bits['i'] == $sectionIndex ) {
4665 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4666 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4667 $node = $node->getNextSibling();
4670 'toclevel' => $toclevel,
4673 'number' => $numbering,
4674 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4675 'fromtitle' => $titleText,
4676 'byteoffset' => ( $noOffset ?
null : $byteOffset ),
4677 'anchor' => $anchor,
4680 # give headline the correct <h#> tag
4681 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4682 // Output edit section links as markers with styles that can be customized by skins
4683 if ( $isTemplate ) {
4684 # Put a T flag in the section identifier, to indicate to extractSections()
4685 # that sections inside <includeonly> should be counted.
4686 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4688 $editlinkArgs = array(
4689 $this->mTitle
->getPrefixedText(),
4694 // We use a bit of pesudo-xml for editsection markers. The
4695 // language converter is run later on. Using a UNIQ style marker
4696 // leads to the converter screwing up the tokens when it
4697 // converts stuff. And trying to insert strip tags fails too. At
4698 // this point all real inputted tags have already been escaped,
4699 // so we don't have to worry about a user trying to input one of
4700 // these markers directly. We use a page and section attribute
4701 // to stop the language converter from converting these
4702 // important bits of data, but put the headline hint inside a
4703 // content block because the language converter is supposed to
4704 // be able to convert that piece of data.
4705 $editlink = '<mw:editsection page="' . htmlspecialchars( $editlinkArgs[0] );
4706 $editlink .= '" section="' . htmlspecialchars( $editlinkArgs[1] ) . '"';
4707 if ( isset( $editlinkArgs[2] ) ) {
4708 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4715 $head[$headlineCount] = Linker
::makeHeadline( $level,
4716 $matches['attrib'][$headlineCount], $anchor, $headline,
4717 $editlink, $legacyAnchor );
4722 $this->setOutputType( $oldType );
4724 # Never ever show TOC if no headers
4725 if ( $numVisible < 1 ) {
4730 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4731 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4733 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4734 $this->mOutput
->setTOCHTML( $toc );
4735 $toc = self
::TOC_START
. $toc . self
::TOC_END
;
4736 $this->mOutput
->addModules( 'mediawiki.toc' );
4740 $this->mOutput
->setSections( $tocraw );
4743 # split up and insert constructed headlines
4744 $blocks = preg_split( '/<H[1-6].*?' . '>[\s\S]*?<\/H[1-6]>/i', $text );
4747 // build an array of document sections
4748 $sections = array();
4749 foreach ( $blocks as $block ) {
4750 // $head is zero-based, sections aren't.
4751 if ( empty( $head[$i - 1] ) ) {
4752 $sections[$i] = $block;
4754 $sections[$i] = $head[$i - 1] . $block;
4758 * Send a hook, one per section.
4759 * The idea here is to be able to make section-level DIVs, but to do so in a
4760 * lower-impact, more correct way than r50769
4763 * $section : the section number
4764 * &$sectionContent : ref to the content of the section
4765 * $showEditLinks : boolean describing whether this section has an edit link
4767 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4772 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4773 // append the TOC at the beginning
4774 // Top anchor now in skin
4775 $sections[0] = $sections[0] . $toc . "\n";
4778 $full .= join( '', $sections );
4780 if ( $this->mForceTocPosition
) {
4781 return str_replace( '<!--MWTOC-->', $toc, $full );
4788 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4789 * conversion, substitting signatures, {{subst:}} templates, etc.
4791 * @param string $text The text to transform
4792 * @param Title $title The Title object for the current article
4793 * @param User $user The User object describing the current user
4794 * @param ParserOptions $options Parsing options
4795 * @param bool $clearState Whether to clear the parser state first
4796 * @return string The altered wiki markup
4798 public function preSaveTransform( $text, Title
$title, User
$user,
4799 ParserOptions
$options, $clearState = true
4801 if ( $clearState ) {
4802 $magicScopeVariable = $this->lock();
4804 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4805 $this->setUser( $user );
4810 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4811 if ( $options->getPreSaveTransform() ) {
4812 $text = $this->pstPass2( $text, $user );
4814 $text = $this->mStripState
->unstripBoth( $text );
4816 $this->setUser( null ); #Reset
4822 * Pre-save transform helper function
4824 * @param string $text
4829 private function pstPass2( $text, $user ) {
4832 # Note: This is the timestamp saved as hardcoded wikitext to
4833 # the database, we use $wgContLang here in order to give
4834 # everyone the same signature and use the default one rather
4835 # than the one selected in each user's preferences.
4836 # (see also bug 12815)
4837 $ts = $this->mOptions
->getTimestamp();
4838 $timestamp = MWTimestamp
::getLocalInstance( $ts );
4839 $ts = $timestamp->format( 'YmdHis' );
4840 $tzMsg = $timestamp->format( 'T' ); # might vary on DST changeover!
4842 # Allow translation of timezones through wiki. format() can return
4843 # whatever crap the system uses, localised or not, so we cannot
4844 # ship premade translations.
4845 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4846 $msg = wfMessage( $key )->inContentLanguage();
4847 if ( $msg->exists() ) {
4848 $tzMsg = $msg->text();
4851 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4853 # Variable replacement
4854 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4855 $text = $this->replaceVariables( $text );
4857 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4858 # which may corrupt this parser instance via its wfMessage()->text() call-
4861 $sigText = $this->getUserSig( $user );
4862 $text = strtr( $text, array(
4864 '~~~~' => "$sigText $d",
4868 # Context links ("pipe tricks"): [[|name]] and [[name (context)|]]
4869 $tc = '[' . Title
::legalChars() . ']';
4870 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4872 // [[ns:page (context)|]]
4873 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/";
4874 // [[ns:page(context)|]] (double-width brackets, added in r40257)
4875 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/";
4876 // [[ns:page (context), context|]] (using either single or double-width comma)
4877 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/";
4878 // [[|page]] (reverse pipe trick: add context from page title)
4879 $p2 = "/\[\[\\|($tc+)]]/";
4881 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4882 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4883 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4884 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4886 $t = $this->mTitle
->getText();
4888 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4889 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4890 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4891 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4893 # if there's no context, don't bother duplicating the title
4894 $text = preg_replace( $p2, '[[\\1]]', $text );
4897 # Trim trailing whitespace
4898 $text = rtrim( $text );
4904 * Fetch the user's signature text, if any, and normalize to
4905 * validated, ready-to-insert wikitext.
4906 * If you have pre-fetched the nickname or the fancySig option, you can
4907 * specify them here to save a database query.
4908 * Do not reuse this parser instance after calling getUserSig(),
4909 * as it may have changed if it's the $wgParser.
4912 * @param string|bool $nickname Nickname to use or false to use user's default nickname
4913 * @param bool|null $fancySig whether the nicknname is the complete signature
4914 * or null to use default value
4917 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4918 global $wgMaxSigChars;
4920 $username = $user->getName();
4922 # If not given, retrieve from the user object.
4923 if ( $nickname === false ) {
4924 $nickname = $user->getOption( 'nickname' );
4927 if ( is_null( $fancySig ) ) {
4928 $fancySig = $user->getBoolOption( 'fancysig' );
4931 $nickname = $nickname == null ?
$username : $nickname;
4933 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4934 $nickname = $username;
4935 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4936 } elseif ( $fancySig !== false ) {
4937 # Sig. might contain markup; validate this
4938 if ( $this->validateSig( $nickname ) !== false ) {
4939 # Validated; clean up (if needed) and return it
4940 return $this->cleanSig( $nickname, true );
4942 # Failed to validate; fall back to the default
4943 $nickname = $username;
4944 wfDebug( __METHOD__
. ": $username has bad XML tags in signature.\n" );
4948 # Make sure nickname doesnt get a sig in a sig
4949 $nickname = self
::cleanSigInSig( $nickname );
4951 # If we're still here, make it a link to the user page
4952 $userText = wfEscapeWikiText( $username );
4953 $nickText = wfEscapeWikiText( $nickname );
4954 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4956 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()
4957 ->title( $this->getTitle() )->text();
4961 * Check that the user's signature contains no bad XML
4963 * @param string $text
4964 * @return string|bool An expanded string, or false if invalid.
4966 function validateSig( $text ) {
4967 return Xml
::isWellFormedXmlFragment( $text ) ?
$text : false;
4971 * Clean up signature text
4973 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4974 * 2) Substitute all transclusions
4976 * @param string $text
4977 * @param bool $parsing Whether we're cleaning (preferences save) or parsing
4978 * @return string Signature text
4980 public function cleanSig( $text, $parsing = false ) {
4983 $magicScopeVariable = $this->lock();
4984 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4987 # Option to disable this feature
4988 if ( !$this->mOptions
->getCleanSignatures() ) {
4992 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4993 # => Move this logic to braceSubstitution()
4994 $substWord = MagicWord
::get( 'subst' );
4995 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4996 $substText = '{{' . $substWord->getSynonym( 0 );
4998 $text = preg_replace( $substRegex, $substText, $text );
4999 $text = self
::cleanSigInSig( $text );
5000 $dom = $this->preprocessToDom( $text );
5001 $frame = $this->getPreprocessor()->newFrame();
5002 $text = $frame->expand( $dom );
5005 $text = $this->mStripState
->unstripBoth( $text );
5012 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
5014 * @param string $text
5015 * @return string Signature text with /~{3,5}/ removed
5017 public static function cleanSigInSig( $text ) {
5018 $text = preg_replace( '/~{3,5}/', '', $text );
5023 * Set up some variables which are usually set up in parse()
5024 * so that an external function can call some class members with confidence
5026 * @param Title|null $title
5027 * @param ParserOptions $options
5028 * @param int $outputType
5029 * @param bool $clearState
5031 public function startExternalParse( Title
$title = null, ParserOptions
$options,
5032 $outputType, $clearState = true
5034 $this->startParse( $title, $options, $outputType, $clearState );
5038 * @param Title|null $title
5039 * @param ParserOptions $options
5040 * @param int $outputType
5041 * @param bool $clearState
5043 private function startParse( Title
$title = null, ParserOptions
$options,
5044 $outputType, $clearState = true
5046 $this->setTitle( $title );
5047 $this->mOptions
= $options;
5048 $this->setOutputType( $outputType );
5049 if ( $clearState ) {
5050 $this->clearState();
5055 * Wrapper for preprocess()
5057 * @param string $text The text to preprocess
5058 * @param ParserOptions $options Options
5059 * @param Title|null $title Title object or null to use $wgTitle
5062 public function transformMsg( $text, $options, $title = null ) {
5063 static $executing = false;
5065 # Guard against infinite recursion
5071 wfProfileIn( __METHOD__
);
5077 $text = $this->preprocess( $text, $title, $options );
5080 wfProfileOut( __METHOD__
);
5085 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
5086 * The callback should have the following form:
5087 * function myParserHook( $text, $params, $parser, $frame ) { ... }
5089 * Transform and return $text. Use $parser for any required context, e.g. use
5090 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
5092 * Hooks may return extended information by returning an array, of which the
5093 * first numbered element (index 0) must be the return string, and all other
5094 * entries are extracted into local variables within an internal function
5095 * in the Parser class.
5097 * This interface (introduced r61913) appears to be undocumented, but
5098 * 'markerName' is used by some core tag hooks to override which strip
5099 * array their results are placed in. **Use great caution if attempting
5100 * this interface, as it is not documented and injudicious use could smash
5101 * private variables.**
5103 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5104 * @param mixed $callback The callback function (and object) to use for the tag
5105 * @throws MWException
5106 * @return mixed|null The old value of the mTagHooks array associated with the hook
5108 public function setHook( $tag, $callback ) {
5109 $tag = strtolower( $tag );
5110 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5111 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
5113 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
5114 $this->mTagHooks
[$tag] = $callback;
5115 if ( !in_array( $tag, $this->mStripList
) ) {
5116 $this->mStripList
[] = $tag;
5123 * As setHook(), but letting the contents be parsed.
5125 * Transparent tag hooks are like regular XML-style tag hooks, except they
5126 * operate late in the transformation sequence, on HTML instead of wikitext.
5128 * This is probably obsoleted by things dealing with parser frames?
5129 * The only extension currently using it is geoserver.
5132 * @todo better document or deprecate this
5134 * @param string $tag The tag to use, e.g. 'hook' for "<hook>"
5135 * @param mixed $callback The callback function (and object) to use for the tag
5136 * @throws MWException
5137 * @return mixed|null The old value of the mTagHooks array associated with the hook
5139 function setTransparentTagHook( $tag, $callback ) {
5140 $tag = strtolower( $tag );
5141 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5142 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
5144 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
5145 $this->mTransparentTagHooks
[$tag] = $callback;
5151 * Remove all tag hooks
5153 function clearTagHooks() {
5154 $this->mTagHooks
= array();
5155 $this->mFunctionTagHooks
= array();
5156 $this->mStripList
= $this->mDefaultStripList
;
5160 * Create a function, e.g. {{sum:1|2|3}}
5161 * The callback function should have the form:
5162 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
5164 * Or with SFH_OBJECT_ARGS:
5165 * function myParserFunction( $parser, $frame, $args ) { ... }
5167 * The callback may either return the text result of the function, or an array with the text
5168 * in element 0, and a number of flags in the other elements. The names of the flags are
5169 * specified in the keys. Valid flags are:
5170 * found The text returned is valid, stop processing the template. This
5172 * nowiki Wiki markup in the return value should be escaped
5173 * isHTML The returned text is HTML, armour it against wikitext transformation
5175 * @param string $id The magic word ID
5176 * @param mixed $callback The callback function (and object) to use
5177 * @param int $flags A combination of the following flags:
5178 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
5180 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
5181 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
5182 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
5183 * the arguments, and to control the way they are expanded.
5185 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
5186 * arguments, for instance:
5187 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
5189 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
5190 * future versions. Please call $frame->expand() on it anyway so that your code keeps
5191 * working if/when this is changed.
5193 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
5196 * Please read the documentation in includes/parser/Preprocessor.php for more information
5197 * about the methods available in PPFrame and PPNode.
5199 * @throws MWException
5200 * @return string|callable The old callback function for this name, if any
5202 public function setFunctionHook( $id, $callback, $flags = 0 ) {
5205 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
5206 $this->mFunctionHooks
[$id] = array( $callback, $flags );
5208 # Add to function cache
5209 $mw = MagicWord
::get( $id );
5211 throw new MWException( __METHOD__
. '() expecting a magic word identifier.' );
5214 $synonyms = $mw->getSynonyms();
5215 $sensitive = intval( $mw->isCaseSensitive() );
5217 foreach ( $synonyms as $syn ) {
5219 if ( !$sensitive ) {
5220 $syn = $wgContLang->lc( $syn );
5223 if ( !( $flags & SFH_NO_HASH
) ) {
5226 # Remove trailing colon
5227 if ( substr( $syn, -1, 1 ) === ':' ) {
5228 $syn = substr( $syn, 0, -1 );
5230 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
5236 * Get all registered function hook identifiers
5240 function getFunctionHooks() {
5241 return array_keys( $this->mFunctionHooks
);
5245 * Create a tag function, e.g. "<test>some stuff</test>".
5246 * Unlike tag hooks, tag functions are parsed at preprocessor level.
5247 * Unlike parser functions, their content is not preprocessed.
5248 * @param string $tag
5249 * @param callable $callback
5251 * @throws MWException
5254 function setFunctionTagHook( $tag, $callback, $flags ) {
5255 $tag = strtolower( $tag );
5256 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
5257 throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
5259 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
5260 $this->mFunctionTagHooks
[$tag] : null;
5261 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
5263 if ( !in_array( $tag, $this->mStripList
) ) {
5264 $this->mStripList
[] = $tag;
5271 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
5272 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
5273 * Placeholders created in Skin::makeLinkObj()
5275 * @param string $text
5276 * @param int $options
5278 * @return array Array of link CSS classes, indexed by PDBK.
5280 function replaceLinkHolders( &$text, $options = 0 ) {
5281 return $this->mLinkHolders
->replace( $text );
5285 * Replace "<!--LINK-->" link placeholders with plain text of links
5286 * (not HTML-formatted).
5288 * @param string $text
5291 function replaceLinkHoldersText( $text ) {
5292 return $this->mLinkHolders
->replaceText( $text );
5296 * Renders an image gallery from a text with one line per image.
5297 * text labels may be given by using |-style alternative text. E.g.
5298 * Image:one.jpg|The number "1"
5299 * Image:tree.jpg|A tree
5300 * given as text will return the HTML of a gallery with two images,
5301 * labeled 'The number "1"' and
5304 * @param string $text
5305 * @param array $params
5306 * @return string HTML
5308 function renderImageGallery( $text, $params ) {
5309 wfProfileIn( __METHOD__
);
5312 if ( isset( $params['mode'] ) ) {
5313 $mode = $params['mode'];
5317 $ig = ImageGalleryBase
::factory( $mode );
5318 } catch ( MWException
$e ) {
5319 // If invalid type set, fallback to default.
5320 $ig = ImageGalleryBase
::factory( false );
5323 $ig->setContextTitle( $this->mTitle
);
5324 $ig->setShowBytes( false );
5325 $ig->setShowFilename( false );
5326 $ig->setParser( $this );
5327 $ig->setHideBadImages();
5328 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
5330 if ( isset( $params['showfilename'] ) ) {
5331 $ig->setShowFilename( true );
5333 $ig->setShowFilename( false );
5335 if ( isset( $params['caption'] ) ) {
5336 $caption = $params['caption'];
5337 $caption = htmlspecialchars( $caption );
5338 $caption = $this->replaceInternalLinks( $caption );
5339 $ig->setCaptionHtml( $caption );
5341 if ( isset( $params['perrow'] ) ) {
5342 $ig->setPerRow( $params['perrow'] );
5344 if ( isset( $params['widths'] ) ) {
5345 $ig->setWidths( $params['widths'] );
5347 if ( isset( $params['heights'] ) ) {
5348 $ig->setHeights( $params['heights'] );
5350 $ig->setAdditionalOptions( $params );
5352 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
5354 $lines = StringUtils
::explode( "\n", $text );
5355 foreach ( $lines as $line ) {
5356 # match lines like these:
5357 # Image:someimage.jpg|This is some image
5359 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
5361 if ( count( $matches ) == 0 ) {
5365 if ( strpos( $matches[0], '%' ) !== false ) {
5366 $matches[1] = rawurldecode( $matches[1] );
5368 $title = Title
::newFromText( $matches[1], NS_FILE
);
5369 if ( is_null( $title ) ) {
5370 # Bogus title. Ignore these so we don't bomb out later.
5374 # We need to get what handler the file uses, to figure out parameters.
5375 # Note, a hook can overide the file name, and chose an entirely different
5376 # file (which potentially could be of a different type and have different handler).
5379 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5380 array( $this, $title, &$options, &$descQuery ) );
5381 # Don't register it now, as ImageGallery does that later.
5382 $file = $this->fetchFileNoRegister( $title, $options );
5383 $handler = $file ?
$file->getHandler() : false;
5385 wfProfileIn( __METHOD__
. '-getMagicWord' );
5387 'img_alt' => 'gallery-internal-alt',
5388 'img_link' => 'gallery-internal-link',
5391 $paramMap = $paramMap +
$handler->getParamMap();
5392 // We don't want people to specify per-image widths.
5393 // Additionally the width parameter would need special casing anyhow.
5394 unset( $paramMap['img_width'] );
5397 $mwArray = new MagicWordArray( array_keys( $paramMap ) );
5398 wfProfileOut( __METHOD__
. '-getMagicWord' );
5403 $handlerOptions = array();
5404 if ( isset( $matches[3] ) ) {
5405 // look for an |alt= definition while trying not to break existing
5406 // captions with multiple pipes (|) in it, until a more sensible grammar
5407 // is defined for images in galleries
5409 // FIXME: Doing recursiveTagParse at this stage, and the trim before
5410 // splitting on '|' is a bit odd, and different from makeImage.
5411 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
5412 $parameterMatches = StringUtils
::explode( '|', $matches[3] );
5414 foreach ( $parameterMatches as $parameterMatch ) {
5415 list( $magicName, $match ) = $mwArray->matchVariableStartToEnd( $parameterMatch );
5417 $paramName = $paramMap[$magicName];
5419 switch ( $paramName ) {
5420 case 'gallery-internal-alt':
5421 $alt = $this->stripAltText( $match, false );
5423 case 'gallery-internal-link':
5424 $linkValue = strip_tags( $this->replaceLinkHoldersText( $match ) );
5425 $chars = self
::EXT_LINK_URL_CLASS
;
5426 $prots = $this->mUrlProtocols
;
5427 //check to see if link matches an absolute url, if not then it must be a wiki link.
5428 if ( preg_match( "/^($prots)$chars+$/u", $linkValue ) ) {
5431 $localLinkTitle = Title
::newFromText( $linkValue );
5432 if ( $localLinkTitle !== null ) {
5433 $link = $localLinkTitle->getLocalURL();
5438 // Must be a handler specific parameter.
5439 if ( $handler->validateParam( $paramName, $match ) ) {
5440 $handlerOptions[$paramName] = $match;
5442 // Guess not. Append it to the caption.
5443 wfDebug( "$parameterMatch failed parameter validation\n" );
5444 $label .= '|' . $parameterMatch;
5449 // concatenate all other pipes
5450 $label .= '|' . $parameterMatch;
5453 // remove the first pipe
5454 $label = substr( $label, 1 );
5457 $ig->add( $title, $label, $alt, $link, $handlerOptions );
5459 $html = $ig->toHTML();
5460 wfProfileOut( __METHOD__
);
5465 * @param string $handler
5468 function getImageParams( $handler ) {
5470 $handlerClass = get_class( $handler );
5474 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
5475 # Initialise static lists
5476 static $internalParamNames = array(
5477 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
5478 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
5479 'bottom', 'text-bottom' ),
5480 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
5481 'upright', 'border', 'link', 'alt', 'class' ),
5483 static $internalParamMap;
5484 if ( !$internalParamMap ) {
5485 $internalParamMap = array();
5486 foreach ( $internalParamNames as $type => $names ) {
5487 foreach ( $names as $name ) {
5488 $magicName = str_replace( '-', '_', "img_$name" );
5489 $internalParamMap[$magicName] = array( $type, $name );
5494 # Add handler params
5495 $paramMap = $internalParamMap;
5497 $handlerParamMap = $handler->getParamMap();
5498 foreach ( $handlerParamMap as $magic => $paramName ) {
5499 $paramMap[$magic] = array( 'handler', $paramName );
5502 $this->mImageParams
[$handlerClass] = $paramMap;
5503 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5505 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5509 * Parse image options text and use it to make an image
5511 * @param Title $title
5512 * @param string $options
5513 * @param LinkHolderArray|bool $holders
5514 * @return string HTML
5516 function makeImage( $title, $options, $holders = false ) {
5517 # Check if the options text is of the form "options|alt text"
5519 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5520 # * left no resizing, just left align. label is used for alt= only
5521 # * right same, but right aligned
5522 # * none same, but not aligned
5523 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5524 # * center center the image
5525 # * frame Keep original image size, no magnify-button.
5526 # * framed Same as "frame"
5527 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5528 # * upright reduce width for upright images, rounded to full __0 px
5529 # * border draw a 1px border around the image
5530 # * alt Text for HTML alt attribute (defaults to empty)
5531 # * class Set a class for img node
5532 # * link Set the target of the image link. Can be external, interwiki, or local
5533 # vertical-align values (no % or length right now):
5543 $parts = StringUtils
::explode( "|", $options );
5545 # Give extensions a chance to select the file revision for us
5548 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5549 array( $this, $title, &$options, &$descQuery ) );
5550 # Fetch and register the file (file title may be different via hooks)
5551 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5554 $handler = $file ?
$file->getHandler() : false;
5556 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5559 $this->addTrackingCategory( 'broken-file-category' );
5562 # Process the input parameters
5564 $params = array( 'frame' => array(), 'handler' => array(),
5565 'horizAlign' => array(), 'vertAlign' => array() );
5566 $seenformat = false;
5567 foreach ( $parts as $part ) {
5568 $part = trim( $part );
5569 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5571 if ( isset( $paramMap[$magicName] ) ) {
5572 list( $type, $paramName ) = $paramMap[$magicName];
5574 # Special case; width and height come in one variable together
5575 if ( $type === 'handler' && $paramName === 'width' ) {
5576 $parsedWidthParam = $this->parseWidthParam( $value );
5577 if ( isset( $parsedWidthParam['width'] ) ) {
5578 $width = $parsedWidthParam['width'];
5579 if ( $handler->validateParam( 'width', $width ) ) {
5580 $params[$type]['width'] = $width;
5584 if ( isset( $parsedWidthParam['height'] ) ) {
5585 $height = $parsedWidthParam['height'];
5586 if ( $handler->validateParam( 'height', $height ) ) {
5587 $params[$type]['height'] = $height;
5591 # else no validation -- bug 13436
5593 if ( $type === 'handler' ) {
5594 # Validate handler parameter
5595 $validated = $handler->validateParam( $paramName, $value );
5597 # Validate internal parameters
5598 switch ( $paramName ) {
5602 # @todo FIXME: Possibly check validity here for
5603 # manualthumb? downstream behavior seems odd with
5604 # missing manual thumbs.
5606 $value = $this->stripAltText( $value, $holders );
5609 $chars = self
::EXT_LINK_URL_CLASS
;
5610 $prots = $this->mUrlProtocols
;
5611 if ( $value === '' ) {
5612 $paramName = 'no-link';
5615 } elseif ( preg_match( "/^(?i)$prots/", $value ) ) {
5616 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5617 $paramName = 'link-url';
5618 $this->mOutput
->addExternalLink( $value );
5619 if ( $this->mOptions
->getExternalLinkTarget() ) {
5620 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5625 $linkTitle = Title
::newFromText( $value );
5627 $paramName = 'link-title';
5628 $value = $linkTitle;
5629 $this->mOutput
->addLink( $linkTitle );
5637 // use first appearing option, discard others.
5638 $validated = ! $seenformat;
5642 # Most other things appear to be empty or numeric...
5643 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5648 $params[$type][$paramName] = $value;
5652 if ( !$validated ) {
5657 # Process alignment parameters
5658 if ( $params['horizAlign'] ) {
5659 $params['frame']['align'] = key( $params['horizAlign'] );
5661 if ( $params['vertAlign'] ) {
5662 $params['frame']['valign'] = key( $params['vertAlign'] );
5665 $params['frame']['caption'] = $caption;
5667 # Will the image be presented in a frame, with the caption below?
5668 $imageIsFramed = isset( $params['frame']['frame'] )
5669 ||
isset( $params['frame']['framed'] )
5670 ||
isset( $params['frame']['thumbnail'] )
5671 ||
isset( $params['frame']['manualthumb'] );
5673 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5674 # came to also set the caption, ordinary text after the image -- which
5675 # makes no sense, because that just repeats the text multiple times in
5676 # screen readers. It *also* came to set the title attribute.
5678 # Now that we have an alt attribute, we should not set the alt text to
5679 # equal the caption: that's worse than useless, it just repeats the
5680 # text. This is the framed/thumbnail case. If there's no caption, we
5681 # use the unnamed parameter for alt text as well, just for the time be-
5682 # ing, if the unnamed param is set and the alt param is not.
5684 # For the future, we need to figure out if we want to tweak this more,
5685 # e.g., introducing a title= parameter for the title; ignoring the un-
5686 # named parameter entirely for images without a caption; adding an ex-
5687 # plicit caption= parameter and preserving the old magic unnamed para-
5689 if ( $imageIsFramed ) { # Framed image
5690 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5691 # No caption or alt text, add the filename as the alt text so
5692 # that screen readers at least get some description of the image
5693 $params['frame']['alt'] = $title->getText();
5695 # Do not set $params['frame']['title'] because tooltips don't make sense
5697 } else { # Inline image
5698 if ( !isset( $params['frame']['alt'] ) ) {
5699 # No alt text, use the "caption" for the alt text
5700 if ( $caption !== '' ) {
5701 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5703 # No caption, fall back to using the filename for the
5705 $params['frame']['alt'] = $title->getText();
5708 # Use the "caption" for the tooltip text
5709 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5712 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5714 # Linker does the rest
5715 $time = isset( $options['time'] ) ?
$options['time'] : false;
5716 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5717 $time, $descQuery, $this->mOptions
->getThumbSize() );
5719 # Give the handler a chance to modify the parser object
5721 $handler->parserTransformHook( $this, $file );
5728 * @param string $caption
5729 * @param LinkHolderArray|bool $holders
5730 * @return mixed|string
5732 protected function stripAltText( $caption, $holders ) {
5733 # Strip bad stuff out of the title (tooltip). We can't just use
5734 # replaceLinkHoldersText() here, because if this function is called
5735 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5737 $tooltip = $holders->replaceText( $caption );
5739 $tooltip = $this->replaceLinkHoldersText( $caption );
5742 # make sure there are no placeholders in thumbnail attributes
5743 # that are later expanded to html- so expand them now and
5745 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5746 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5752 * Set a flag in the output object indicating that the content is dynamic and
5753 * shouldn't be cached.
5755 function disableCache() {
5756 wfDebug( "Parser output marked as uncacheable.\n" );
5757 if ( !$this->mOutput
) {
5758 throw new MWException( __METHOD__
.
5759 " can only be called when actually parsing something" );
5761 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5762 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5766 * Callback from the Sanitizer for expanding items found in HTML attribute
5767 * values, so they can be safely tested and escaped.
5769 * @param string $text
5770 * @param bool|PPFrame $frame
5773 function attributeStripCallback( &$text, $frame = false ) {
5774 $text = $this->replaceVariables( $text, $frame );
5775 $text = $this->mStripState
->unstripBoth( $text );
5784 function getTags() {
5786 array_keys( $this->mTransparentTagHooks
),
5787 array_keys( $this->mTagHooks
),
5788 array_keys( $this->mFunctionTagHooks
)
5793 * Replace transparent tags in $text with the values given by the callbacks.
5795 * Transparent tag hooks are like regular XML-style tag hooks, except they
5796 * operate late in the transformation sequence, on HTML instead of wikitext.
5798 * @param string $text
5802 function replaceTransparentTags( $text ) {
5804 $elements = array_keys( $this->mTransparentTagHooks
);
5805 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5806 $replacements = array();
5808 foreach ( $matches as $marker => $data ) {
5809 list( $element, $content, $params, $tag ) = $data;
5810 $tagName = strtolower( $element );
5811 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5812 $output = call_user_func_array(
5813 $this->mTransparentTagHooks
[$tagName],
5814 array( $content, $params, $this )
5819 $replacements[$marker] = $output;
5821 return strtr( $text, $replacements );
5825 * Break wikitext input into sections, and either pull or replace
5826 * some particular section's text.
5828 * External callers should use the getSection and replaceSection methods.
5830 * @param string $text Page wikitext
5831 * @param string $section A section identifier string of the form:
5832 * "<flag1> - <flag2> - ... - <section number>"
5834 * Currently the only recognised flag is "T", which means the target section number
5835 * was derived during a template inclusion parse, in other words this is a template
5836 * section edit link. If no flags are given, it was an ordinary section edit link.
5837 * This flag is required to avoid a section numbering mismatch when a section is
5838 * enclosed by "<includeonly>" (bug 6563).
5840 * The section number 0 pulls the text before the first heading; other numbers will
5841 * pull the given section along with its lower-level subsections. If the section is
5842 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5844 * Section 0 is always considered to exist, even if it only contains the empty
5845 * string. If $text is the empty string and section 0 is replaced, $newText is
5848 * @param string $mode One of "get" or "replace"
5849 * @param string $newText Replacement text for section data.
5850 * @return string For "get", the extracted section text.
5851 * for "replace", the whole page with the section replaced.
5853 private function extractSections( $text, $section, $mode, $newText = '' ) {
5854 global $wgTitle; # not generally used but removes an ugly failure mode
5856 $magicScopeVariable = $this->lock();
5857 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5859 $frame = $this->getPreprocessor()->newFrame();
5861 # Process section extraction flags
5863 $sectionParts = explode( '-', $section );
5864 $sectionIndex = array_pop( $sectionParts );
5865 foreach ( $sectionParts as $part ) {
5866 if ( $part === 'T' ) {
5867 $flags |
= self
::PTD_FOR_INCLUSION
;
5871 # Check for empty input
5872 if ( strval( $text ) === '' ) {
5873 # Only sections 0 and T-0 exist in an empty document
5874 if ( $sectionIndex == 0 ) {
5875 if ( $mode === 'get' ) {
5881 if ( $mode === 'get' ) {
5889 # Preprocess the text
5890 $root = $this->preprocessToDom( $text, $flags );
5892 # <h> nodes indicate section breaks
5893 # They can only occur at the top level, so we can find them by iterating the root's children
5894 $node = $root->getFirstChild();
5896 # Find the target section
5897 if ( $sectionIndex == 0 ) {
5898 # Section zero doesn't nest, level=big
5899 $targetLevel = 1000;
5902 if ( $node->getName() === 'h' ) {
5903 $bits = $node->splitHeading();
5904 if ( $bits['i'] == $sectionIndex ) {
5905 $targetLevel = $bits['level'];
5909 if ( $mode === 'replace' ) {
5910 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5912 $node = $node->getNextSibling();
5918 if ( $mode === 'get' ) {
5925 # Find the end of the section, including nested sections
5927 if ( $node->getName() === 'h' ) {
5928 $bits = $node->splitHeading();
5929 $curLevel = $bits['level'];
5930 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5934 if ( $mode === 'get' ) {
5935 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5937 $node = $node->getNextSibling();
5940 # Write out the remainder (in replace mode only)
5941 if ( $mode === 'replace' ) {
5942 # Output the replacement text
5943 # Add two newlines on -- trailing whitespace in $newText is conventionally
5944 # stripped by the editor, so we need both newlines to restore the paragraph gap
5945 # Only add trailing whitespace if there is newText
5946 if ( $newText != "" ) {
5947 $outText .= $newText . "\n\n";
5951 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5952 $node = $node->getNextSibling();
5956 if ( is_string( $outText ) ) {
5957 # Re-insert stripped tags
5958 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5965 * This function returns the text of a section, specified by a number ($section).
5966 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5967 * the first section before any such heading (section 0).
5969 * If a section contains subsections, these are also returned.
5971 * @param string $text Text to look in
5972 * @param string $section Section identifier
5973 * @param string $deftext Default to return if section is not found
5974 * @return string Text of the requested section
5976 public function getSection( $text, $section, $deftext = '' ) {
5977 return $this->extractSections( $text, $section, "get", $deftext );
5981 * This function returns $oldtext after the content of the section
5982 * specified by $section has been replaced with $text. If the target
5983 * section does not exist, $oldtext is returned unchanged.
5985 * @param string $oldtext Former text of the article
5986 * @param int $section Section identifier
5987 * @param string $text Replacing text
5988 * @return string Modified text
5990 public function replaceSection( $oldtext, $section, $text ) {
5991 return $this->extractSections( $oldtext, $section, "replace", $text );
5995 * Get the ID of the revision we are parsing
5999 function getRevisionId() {
6000 return $this->mRevisionId
;
6004 * Get the revision object for $this->mRevisionId
6006 * @return Revision|null Either a Revision object or null
6007 * @since 1.23 (public since 1.23)
6009 public function getRevisionObject() {
6010 if ( !is_null( $this->mRevisionObject
) ) {
6011 return $this->mRevisionObject
;
6013 if ( is_null( $this->mRevisionId
) ) {
6017 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
6018 return $this->mRevisionObject
;
6022 * Get the timestamp associated with the current revision, adjusted for
6023 * the default server-local timestamp
6026 function getRevisionTimestamp() {
6027 if ( is_null( $this->mRevisionTimestamp
) ) {
6028 wfProfileIn( __METHOD__
);
6032 $revObject = $this->getRevisionObject();
6033 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
6035 # The cryptic '' timezone parameter tells to use the site-default
6036 # timezone offset instead of the user settings.
6038 # Since this value will be saved into the parser cache, served
6039 # to other users, and potentially even used inside links and such,
6040 # it needs to be consistent for all visitors.
6041 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
6043 wfProfileOut( __METHOD__
);
6045 return $this->mRevisionTimestamp
;
6049 * Get the name of the user that edited the last revision
6051 * @return string User name
6053 function getRevisionUser() {
6054 if ( is_null( $this->mRevisionUser
) ) {
6055 $revObject = $this->getRevisionObject();
6057 # if this template is subst: the revision id will be blank,
6058 # so just use the current user's name
6060 $this->mRevisionUser
= $revObject->getUserText();
6061 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6062 $this->mRevisionUser
= $this->getUser()->getName();
6065 return $this->mRevisionUser
;
6069 * Get the size of the revision
6071 * @return int|null Revision size
6073 function getRevisionSize() {
6074 if ( is_null( $this->mRevisionSize
) ) {
6075 $revObject = $this->getRevisionObject();
6077 # if this variable is subst: the revision id will be blank,
6078 # so just use the parser input size, because the own substituation
6079 # will change the size.
6081 $this->mRevisionSize
= $revObject->getSize();
6082 } elseif ( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
6083 $this->mRevisionSize
= $this->mInputSize
;
6086 return $this->mRevisionSize
;
6090 * Mutator for $mDefaultSort
6092 * @param string $sort New value
6094 public function setDefaultSort( $sort ) {
6095 $this->mDefaultSort
= $sort;
6096 $this->mOutput
->setProperty( 'defaultsort', $sort );
6100 * Accessor for $mDefaultSort
6101 * Will use the empty string if none is set.
6103 * This value is treated as a prefix, so the
6104 * empty string is equivalent to sorting by
6109 public function getDefaultSort() {
6110 if ( $this->mDefaultSort
!== false ) {
6111 return $this->mDefaultSort
;
6118 * Accessor for $mDefaultSort
6119 * Unlike getDefaultSort(), will return false if none is set
6121 * @return string|bool
6123 public function getCustomDefaultSort() {
6124 return $this->mDefaultSort
;
6128 * Try to guess the section anchor name based on a wikitext fragment
6129 * presumably extracted from a heading, for example "Header" from
6132 * @param string $text
6136 public function guessSectionNameFromWikiText( $text ) {
6137 # Strip out wikitext links(they break the anchor)
6138 $text = $this->stripSectionName( $text );
6139 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6140 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
6144 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
6145 * instead. For use in redirects, since IE6 interprets Redirect: headers
6146 * as something other than UTF-8 (apparently?), resulting in breakage.
6148 * @param string $text The section name
6149 * @return string An anchor
6151 public function guessLegacySectionNameFromWikiText( $text ) {
6152 # Strip out wikitext links(they break the anchor)
6153 $text = $this->stripSectionName( $text );
6154 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
6155 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
6159 * Strips a text string of wikitext for use in a section anchor
6161 * Accepts a text string and then removes all wikitext from the
6162 * string and leaves only the resultant text (i.e. the result of
6163 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
6164 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
6165 * to create valid section anchors by mimicing the output of the
6166 * parser when headings are parsed.
6168 * @param string $text Text string to be stripped of wikitext
6169 * for use in a Section anchor
6170 * @return string Filtered text string
6172 public function stripSectionName( $text ) {
6173 # Strip internal link markup
6174 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
6175 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
6177 # Strip external link markup
6178 # @todo FIXME: Not tolerant to blank link text
6179 # I.E. [https://www.mediawiki.org] will render as [1] or something depending
6180 # on how many empty links there are on the page - need to figure that out.
6181 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
6183 # Parse wikitext quotes (italics & bold)
6184 $text = $this->doQuotes( $text );
6187 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
6192 * strip/replaceVariables/unstrip for preprocessor regression testing
6194 * @param string $text
6195 * @param Title $title
6196 * @param ParserOptions $options
6197 * @param int $outputType
6201 function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
6202 $magicScopeVariable = $this->lock();
6203 $this->startParse( $title, $options, $outputType, true );
6205 $text = $this->replaceVariables( $text );
6206 $text = $this->mStripState
->unstripBoth( $text );
6207 $text = Sanitizer
::removeHTMLtags( $text );
6212 * @param string $text
6213 * @param Title $title
6214 * @param ParserOptions $options
6217 function testPst( $text, Title
$title, ParserOptions
$options ) {
6218 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
6222 * @param string $text
6223 * @param Title $title
6224 * @param ParserOptions $options
6227 function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
6228 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
6232 * Call a callback function on all regions of the given text that are not
6233 * inside strip markers, and replace those regions with the return value
6234 * of the callback. For example, with input:
6238 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
6239 * two strings will be replaced with the value returned by the callback in
6243 * @param callable $callback
6247 function markerSkipCallback( $s, $callback ) {
6250 while ( $i < strlen( $s ) ) {
6251 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
6252 if ( $markerStart === false ) {
6253 $out .= call_user_func( $callback, substr( $s, $i ) );
6256 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
6257 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
6258 if ( $markerEnd === false ) {
6259 $out .= substr( $s, $markerStart );
6262 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
6263 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
6272 * Remove any strip markers found in the given text.
6274 * @param string $text Input string
6277 function killMarkers( $text ) {
6278 return $this->mStripState
->killMarkers( $text );
6282 * Save the parser state required to convert the given half-parsed text to
6283 * HTML. "Half-parsed" in this context means the output of
6284 * recursiveTagParse() or internalParse(). This output has strip markers
6285 * from replaceVariables (extensionSubstitution() etc.), and link
6286 * placeholders from replaceLinkHolders().
6288 * Returns an array which can be serialized and stored persistently. This
6289 * array can later be loaded into another parser instance with
6290 * unserializeHalfParsedText(). The text can then be safely incorporated into
6291 * the return value of a parser hook.
6293 * @param string $text
6297 function serializeHalfParsedText( $text ) {
6298 wfProfileIn( __METHOD__
);
6301 'version' => self
::HALF_PARSED_VERSION
,
6302 'stripState' => $this->mStripState
->getSubState( $text ),
6303 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
6305 wfProfileOut( __METHOD__
);
6310 * Load the parser state given in the $data array, which is assumed to
6311 * have been generated by serializeHalfParsedText(). The text contents is
6312 * extracted from the array, and its markers are transformed into markers
6313 * appropriate for the current Parser instance. This transformed text is
6314 * returned, and can be safely included in the return value of a parser
6317 * If the $data array has been stored persistently, the caller should first
6318 * check whether it is still valid, by calling isValidHalfParsedText().
6320 * @param array $data Serialized data
6321 * @throws MWException
6324 function unserializeHalfParsedText( $data ) {
6325 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
6326 throw new MWException( __METHOD__
. ': invalid version' );
6329 # First, extract the strip state.
6330 $texts = array( $data['text'] );
6331 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
6333 # Now renumber links
6334 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
6336 # Should be good to go.
6341 * Returns true if the given array, presumed to be generated by
6342 * serializeHalfParsedText(), is compatible with the current version of the
6345 * @param array $data
6349 function isValidHalfParsedText( $data ) {
6350 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
6354 * Parsed a width param of imagelink like 300px or 200x300px
6356 * @param string $value
6361 public function parseWidthParam( $value ) {
6362 $parsedWidthParam = array();
6363 if ( $value === '' ) {
6364 return $parsedWidthParam;
6367 # (bug 13500) In both cases (width/height and width only),
6368 # permit trailing "px" for backward compatibility.
6369 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
6370 $width = intval( $m[1] );
6371 $height = intval( $m[2] );
6372 $parsedWidthParam['width'] = $width;
6373 $parsedWidthParam['height'] = $height;
6374 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
6375 $width = intval( $value );
6376 $parsedWidthParam['width'] = $width;
6378 return $parsedWidthParam;
6382 * Lock the current instance of the parser.
6384 * This is meant to stop someone from calling the parser
6385 * recursively and messing up all the strip state.
6387 * @throws MWException If parser is in a parse
6388 * @return ScopedCallback The lock will be released once the return value goes out of scope.
6390 protected function lock() {
6391 if ( $this->mInParse
) {
6392 throw new MWException( "Parser state cleared while parsing. "
6393 . "Did you call Parser::parse recursively?" );
6395 $this->mInParse
= true;
6398 $recursiveCheck = new ScopedCallback( function() use ( $that ) {
6399 $that->mInParse
= false;
6402 return $recursiveCheck;