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 XHTML 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!
58 * $wgNamespacesWithSubpages
60 * @par Settings only within ParserOptions:
61 * $wgAllowExternalImages
62 * $wgAllowSpecialInclusion
71 * Update this version number when the ParserOutput format
72 * changes in an incompatible way, so the parser cache
73 * can automatically discard old data.
75 const VERSION
= '1.6.4';
78 * Update this version number when the output of serialiseHalfParsedText()
79 * changes in an incompatible way
81 const HALF_PARSED_VERSION
= 2;
83 # Flags for Parser::setFunctionHook
84 # Also available as global constants from Defines.php
85 const SFH_NO_HASH
= 1;
86 const SFH_OBJECT_ARGS
= 2;
88 # Constants needed for external link processing
89 # Everything except bracket, space, or control characters
90 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
91 # as well as U+3000 is IDEOGRAPHIC SPACE for bug 19052
92 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}]';
93 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F\p{Zs}]+)
94 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
96 # State constants for the definition list colon extraction
97 const COLON_STATE_TEXT
= 0;
98 const COLON_STATE_TAG
= 1;
99 const COLON_STATE_TAGSTART
= 2;
100 const COLON_STATE_CLOSETAG
= 3;
101 const COLON_STATE_TAGSLASH
= 4;
102 const COLON_STATE_COMMENT
= 5;
103 const COLON_STATE_COMMENTDASH
= 6;
104 const COLON_STATE_COMMENTDASHDASH
= 7;
106 # Flags for preprocessToDom
107 const PTD_FOR_INCLUSION
= 1;
109 # Allowed values for $this->mOutputType
110 # Parameter to startExternalParse().
111 const OT_HTML
= 1; # like parse()
112 const OT_WIKI
= 2; # like preSaveTransform()
113 const OT_PREPROCESS
= 3; # like preprocess()
115 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
117 # Marker Suffix needs to be accessible staticly.
118 const MARKER_SUFFIX
= "-QINU\x7f";
121 var $mTagHooks = array();
122 var $mTransparentTagHooks = array();
123 var $mFunctionHooks = array();
124 var $mFunctionSynonyms = array( 0 => array(), 1 => array() );
125 var $mFunctionTagHooks = array();
126 var $mStripList = array();
127 var $mDefaultStripList = array();
128 var $mVarCache = array();
129 var $mImageParams = array();
130 var $mImageParamsMagicArray = array();
131 var $mMarkerIndex = 0;
132 var $mFirstCall = true;
134 # Initialised by initialiseVariables()
137 * @var MagicWordArray
142 * @var MagicWordArray
145 var $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
147 # Cleared with clearState():
152 var $mAutonumber, $mDTopen;
159 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
161 * @var LinkHolderArray
166 var $mIncludeSizes, $mPPNodeCount, $mHighestExpansionDepth, $mDefaultSort;
167 var $mTplExpandCache; # empty-frame expansion cache
168 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
169 var $mExpensiveFunctionCount; # number of expensive parser function calls
170 var $mShowToc, $mForceTocPosition;
175 var $mUser; # User object; only used when doing pre-save transform
178 # These are variables reset at least once per parse regardless of $clearState
188 var $mTitle; # Title context, used for self-link rendering and similar things
189 var $mOutputType; # Output type, one of the OT_xxx constants
190 var $ot; # Shortcut alias, see setOutputType()
191 var $mRevisionObject; # The revision object of the specified revision ID
192 var $mRevisionId; # ID to display in {{REVISIONID}} tags
193 var $mRevisionTimestamp; # The timestamp of the specified revision ID
194 var $mRevisionUser; # User to display in {{REVISIONUSER}} tag
195 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp
207 public function __construct( $conf = array() ) {
208 $this->mConf
= $conf;
209 $this->mUrlProtocols
= wfUrlProtocols();
210 $this->mExtLinkBracketedRegex
= '/\[((' . $this->mUrlProtocols
. ')'.
211 self
::EXT_LINK_URL_CLASS
.'+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
212 if ( isset( $conf['preprocessorClass'] ) ) {
213 $this->mPreprocessorClass
= $conf['preprocessorClass'];
214 } elseif ( defined( 'MW_COMPILED' ) ) {
215 # Preprocessor_Hash is much faster than Preprocessor_DOM in compiled mode
216 $this->mPreprocessorClass
= 'Preprocessor_Hash';
217 } elseif ( extension_loaded( 'domxml' ) ) {
218 # PECL extension that conflicts with the core DOM extension (bug 13770)
219 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
220 $this->mPreprocessorClass
= 'Preprocessor_Hash';
221 } elseif ( extension_loaded( 'dom' ) ) {
222 $this->mPreprocessorClass
= 'Preprocessor_DOM';
224 $this->mPreprocessorClass
= 'Preprocessor_Hash';
226 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
230 * Reduce memory usage to reduce the impact of circular references
232 function __destruct() {
233 if ( isset( $this->mLinkHolders
) ) {
234 unset( $this->mLinkHolders
);
236 foreach ( $this as $name => $value ) {
237 unset( $this->$name );
242 * Do various kinds of initialisation on the first call of the parser
244 function firstCallInit() {
245 if ( !$this->mFirstCall
) {
248 $this->mFirstCall
= false;
250 wfProfileIn( __METHOD__
);
252 CoreParserFunctions
::register( $this );
253 CoreTagHooks
::register( $this );
254 $this->initialiseVariables();
256 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
257 wfProfileOut( __METHOD__
);
265 function clearState() {
266 wfProfileIn( __METHOD__
);
267 if ( $this->mFirstCall
) {
268 $this->firstCallInit();
270 $this->mOutput
= new ParserOutput
;
271 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
272 $this->mAutonumber
= 0;
273 $this->mLastSection
= '';
274 $this->mDTopen
= false;
275 $this->mIncludeCount
= array();
276 $this->mArgStack
= false;
277 $this->mInPre
= false;
278 $this->mLinkHolders
= new LinkHolderArray( $this );
280 $this->mRevisionObject
= $this->mRevisionTimestamp
=
281 $this->mRevisionId
= $this->mRevisionUser
= null;
282 $this->mVarCache
= array();
286 * Prefix for temporary replacement strings for the multipass parser.
287 * \x07 should never appear in input as it's disallowed in XML.
288 * Using it at the front also gives us a little extra robustness
289 * since it shouldn't match when butted up against identifier-like
292 * Must not consist of all title characters, or else it will change
293 * the behaviour of <nowiki> in a link.
295 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
296 $this->mStripState
= new StripState( $this->mUniqPrefix
);
299 # Clear these on every parse, bug 4549
300 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
302 $this->mShowToc
= true;
303 $this->mForceTocPosition
= false;
304 $this->mIncludeSizes
= array(
308 $this->mPPNodeCount
= 0;
309 $this->mHighestExpansionDepth
= 0;
310 $this->mDefaultSort
= false;
311 $this->mHeadings
= array();
312 $this->mDoubleUnderscores
= array();
313 $this->mExpensiveFunctionCount
= 0;
316 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
317 $this->mPreprocessor
= null;
320 wfRunHooks( 'ParserClearState', array( &$this ) );
321 wfProfileOut( __METHOD__
);
325 * Convert wikitext to HTML
326 * Do not call this function recursively.
328 * @param $text String: text we want to parse
329 * @param $title Title object
330 * @param $options ParserOptions
331 * @param $linestart boolean
332 * @param $clearState boolean
333 * @param $revid Int: number to pass in {{REVISIONID}}
334 * @return ParserOutput a ParserOutput
336 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
338 * First pass--just handle <nowiki> sections, pass the rest off
339 * to internalParse() which does all the real work.
342 global $wgUseTidy, $wgAlwaysUseTidy, $wgDisableLangConversion, $wgDisableTitleConversion;
343 $fname = __METHOD__
.'-' . wfGetCaller();
344 wfProfileIn( __METHOD__
);
345 wfProfileIn( $fname );
347 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
349 # Remove the strip marker tag prefix from the input, if present.
351 $text = str_replace( $this->mUniqPrefix
, '', $text );
354 $oldRevisionId = $this->mRevisionId
;
355 $oldRevisionObject = $this->mRevisionObject
;
356 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
357 $oldRevisionUser = $this->mRevisionUser
;
358 if ( $revid !== null ) {
359 $this->mRevisionId
= $revid;
360 $this->mRevisionObject
= null;
361 $this->mRevisionTimestamp
= null;
362 $this->mRevisionUser
= null;
365 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
367 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
368 $text = $this->internalParse( $text );
369 wfRunHooks( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
371 $text = $this->mStripState
->unstripGeneral( $text );
373 # Clean up special characters, only run once, next-to-last before doBlockLevels
375 # french spaces, last one Guillemet-left
376 # only if there is something before the space
377 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
378 # french spaces, Guillemet-right
379 '/(\\302\\253) /' => '\\1 ',
380 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
382 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
384 $text = $this->doBlockLevels( $text, $linestart );
386 $this->replaceLinkHolders( $text );
389 * The input doesn't get language converted if
391 * b) Content isn't converted
392 * c) It's a conversion table
393 * d) it is an interface message (which is in the user language)
395 if ( !( $wgDisableLangConversion
396 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
397 ||
$this->mTitle
->isConversionTable() ) )
399 # Run convert unconditionally in 1.18-compatible mode
400 global $wgBug34832TransitionalRollback;
401 if ( $wgBug34832TransitionalRollback ||
!$this->mOptions
->getInterfaceMessage() ) {
402 # The position of the convert() call should not be changed. it
403 # assumes that the links are all replaced and the only thing left
404 # is the <nowiki> mark.
405 $text = $this->getConverterLanguage()->convert( $text );
410 * A converted title will be provided in the output object if title and
411 * content conversion are enabled, the article text does not contain
412 * a conversion-suppressing double-underscore tag, and no
413 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
414 * automatic link conversion.
416 if ( !( $wgDisableLangConversion
417 ||
$wgDisableTitleConversion
418 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
419 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
420 ||
$this->mOutput
->getDisplayTitle() !== false ) )
422 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
423 if ( $convruletitle ) {
424 $this->mOutput
->setTitleText( $convruletitle );
426 $titleText = $this->getConverterLanguage()->convertTitle( $title );
427 $this->mOutput
->setTitleText( $titleText );
431 $text = $this->mStripState
->unstripNoWiki( $text );
433 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
435 $text = $this->replaceTransparentTags( $text );
436 $text = $this->mStripState
->unstripGeneral( $text );
438 $text = Sanitizer
::normalizeCharReferences( $text );
440 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
441 $text = MWTidy
::tidy( $text );
443 # attempt to sanitize at least some nesting problems
444 # (bug #2702 and quite a few others)
446 # ''Something [http://www.cool.com cool''] -->
447 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
448 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
449 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
450 # fix up an anchor inside another anchor, only
451 # at least for a single single nested link (bug 3695)
452 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
453 '\\1\\2</a>\\3</a>\\1\\4</a>',
454 # fix div inside inline elements- doBlockLevels won't wrap a line which
455 # contains a div, so fix it up here; replace
456 # div with escaped text
457 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
458 '\\1\\3<div\\5>\\6</div>\\8\\9',
459 # remove empty italic or bold tag pairs, some
460 # introduced by rules above
461 '/<([bi])><\/\\1>/' => '',
464 $text = preg_replace(
465 array_keys( $tidyregs ),
466 array_values( $tidyregs ),
470 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
471 $this->limitationWarn( 'expensive-parserfunction',
472 $this->mExpensiveFunctionCount
,
473 $this->mOptions
->getExpensiveParserFunctionLimit()
477 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
479 # Information on include size limits, for the benefit of users who try to skirt them
480 if ( $this->mOptions
->getEnableLimitReport() ) {
481 $max = $this->mOptions
->getMaxIncludeSize();
482 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/{$this->mOptions->getExpensiveParserFunctionLimit()}\n";
484 "NewPP limit report\n" .
485 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
486 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
487 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
488 "Highest expansion depth: {$this->mHighestExpansionDepth}/{$this->mOptions->getMaxPPExpandDepth()}\n".
490 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
491 $text .= "\n<!-- \n$limitReport-->\n";
493 $this->mOutput
->setText( $text );
495 $this->mRevisionId
= $oldRevisionId;
496 $this->mRevisionObject
= $oldRevisionObject;
497 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
498 $this->mRevisionUser
= $oldRevisionUser;
499 wfProfileOut( $fname );
500 wfProfileOut( __METHOD__
);
502 return $this->mOutput
;
506 * Recursive parser entry point that can be called from an extension tag
509 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
511 * @param $text String: text extension wants to have parsed
512 * @param $frame PPFrame: The frame to use for expanding any template variables
516 function recursiveTagParse( $text, $frame=false ) {
517 wfProfileIn( __METHOD__
);
518 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
519 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
520 $text = $this->internalParse( $text, false, $frame );
521 wfProfileOut( __METHOD__
);
526 * Expand templates and variables in the text, producing valid, static wikitext.
527 * Also removes comments.
528 * @return mixed|string
530 function preprocess( $text, Title
$title, ParserOptions
$options, $revid = null ) {
531 wfProfileIn( __METHOD__
);
532 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
533 if ( $revid !== null ) {
534 $this->mRevisionId
= $revid;
536 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
537 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
538 $text = $this->replaceVariables( $text );
539 $text = $this->mStripState
->unstripBoth( $text );
540 wfProfileOut( __METHOD__
);
545 * Recursive parser entry point that can be called from an extension tag
548 * @param $text String: text to be expanded
549 * @param $frame PPFrame: The frame to use for expanding any template variables
553 public function recursivePreprocess( $text, $frame = false ) {
554 wfProfileIn( __METHOD__
);
555 $text = $this->replaceVariables( $text, $frame );
556 $text = $this->mStripState
->unstripBoth( $text );
557 wfProfileOut( __METHOD__
);
562 * Process the wikitext for the "?preload=" feature. (bug 5210)
564 * "<noinclude>", "<includeonly>" etc. are parsed as for template
565 * transclusion, comments, templates, arguments, tags hooks and parser
566 * functions are untouched.
568 * @param $text String
569 * @param $title Title
570 * @param $options ParserOptions
573 public function getPreloadText( $text, Title
$title, ParserOptions
$options ) {
574 # Parser (re)initialisation
575 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
577 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
578 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
579 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
580 $text = $this->mStripState
->unstripBoth( $text );
585 * Get a random string
589 static public function getRandomString() {
590 return wfRandomString( 16 );
594 * Set the current user.
595 * Should only be used when doing pre-save transform.
597 * @param $user Mixed: User object or null (to reset)
599 function setUser( $user ) {
600 $this->mUser
= $user;
604 * Accessor for mUniqPrefix.
608 public function uniqPrefix() {
609 if ( !isset( $this->mUniqPrefix
) ) {
610 # @todo FIXME: This is probably *horribly wrong*
611 # LanguageConverter seems to want $wgParser's uniqPrefix, however
612 # if this is called for a parser cache hit, the parser may not
613 # have ever been initialized in the first place.
614 # Not really sure what the heck is supposed to be going on here.
616 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
618 return $this->mUniqPrefix
;
622 * Set the context title
626 function setTitle( $t ) {
627 if ( !$t ||
$t instanceof FakeTitle
) {
628 $t = Title
::newFromText( 'NO TITLE' );
631 if ( strval( $t->getFragment() ) !== '' ) {
632 # Strip the fragment to avoid various odd effects
633 $this->mTitle
= clone $t;
634 $this->mTitle
->setFragment( '' );
641 * Accessor for the Title object
643 * @return Title object
645 function getTitle() {
646 return $this->mTitle
;
650 * Accessor/mutator for the Title object
652 * @param $x Title object or null to just get the current one
653 * @return Title object
655 function Title( $x = null ) {
656 return wfSetVar( $this->mTitle
, $x );
660 * Set the output type
662 * @param $ot Integer: new value
664 function setOutputType( $ot ) {
665 $this->mOutputType
= $ot;
668 'html' => $ot == self
::OT_HTML
,
669 'wiki' => $ot == self
::OT_WIKI
,
670 'pre' => $ot == self
::OT_PREPROCESS
,
671 'plain' => $ot == self
::OT_PLAIN
,
676 * Accessor/mutator for the output type
678 * @param $x int|null New value or null to just get the current one
681 function OutputType( $x = null ) {
682 return wfSetVar( $this->mOutputType
, $x );
686 * Get the ParserOutput object
688 * @return ParserOutput object
690 function getOutput() {
691 return $this->mOutput
;
695 * Get the ParserOptions object
697 * @return ParserOptions object
699 function getOptions() {
700 return $this->mOptions
;
704 * Accessor/mutator for the ParserOptions object
706 * @param $x ParserOptions New value or null to just get the current one
707 * @return ParserOptions Current ParserOptions object
709 function Options( $x = null ) {
710 return wfSetVar( $this->mOptions
, $x );
716 function nextLinkID() {
717 return $this->mLinkID++
;
723 function setLinkID( $id ) {
724 $this->mLinkID
= $id;
728 * Get a language object for use in parser functions such as {{FORMATNUM:}}
731 function getFunctionLang() {
732 return $this->getTargetLanguage();
736 * Get the target language for the content being parsed. This is usually the
737 * language that the content is in.
739 function getTargetLanguage() {
740 $target = $this->mOptions
->getTargetLanguage();
741 if ( $target !== null ) {
743 } elseif( $this->mOptions
->getInterfaceMessage() ) {
744 return $this->mOptions
->getUserLangObj();
745 } elseif( is_null( $this->mTitle
) ) {
746 throw new MWException( __METHOD__
.': $this->mTitle is null' );
748 return $this->mTitle
->getPageLanguage();
752 * Get the language object for language conversion
754 function getConverterLanguage() {
755 global $wgBug34832TransitionalRollback, $wgContLang;
756 if ( $wgBug34832TransitionalRollback ) {
759 return $this->getTargetLanguage();
764 * Get a User object either from $this->mUser, if set, or from the
765 * ParserOptions object otherwise
767 * @return User object
770 if ( !is_null( $this->mUser
) ) {
773 return $this->mOptions
->getUser();
777 * Get a preprocessor object
779 * @return Preprocessor instance
781 function getPreprocessor() {
782 if ( !isset( $this->mPreprocessor
) ) {
783 $class = $this->mPreprocessorClass
;
784 $this->mPreprocessor
= new $class( $this );
786 return $this->mPreprocessor
;
790 * Replaces all occurrences of HTML-style comments and the given tags
791 * in the text with a random marker and returns the next text. The output
792 * parameter $matches will be an associative array filled with data in
796 * 'UNIQ-xxxxx' => array(
799 * array( 'param' => 'x' ),
800 * '<element param="x">tag content</element>' ) )
803 * @param $elements array list of element names. Comments are always extracted.
804 * @param $text string Source text string.
805 * @param $matches array Out parameter, Array: extracted tags
806 * @param $uniq_prefix string
807 * @return String: stripped text
809 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
814 $taglist = implode( '|', $elements );
815 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
817 while ( $text != '' ) {
818 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
820 if ( count( $p ) < 5 ) {
823 if ( count( $p ) > 5 ) {
837 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
838 $stripped .= $marker;
840 if ( $close === '/>' ) {
841 # Empty element tag, <tag />
846 if ( $element === '!--' ) {
849 $end = "/(<\\/$element\\s*>)/i";
851 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
853 if ( count( $q ) < 3 ) {
854 # No end tag -- let it run out to the end of the text.
863 $matches[$marker] = array( $element,
865 Sanitizer
::decodeTagAttributes( $attributes ),
866 "<$element$attributes$close$content$tail" );
872 * Get a list of strippable XML-like elements
876 function getStripList() {
877 return $this->mStripList
;
881 * Add an item to the strip state
882 * Returns the unique tag which must be inserted into the stripped text
883 * The tag will be replaced with the original text in unstrip()
885 * @param $text string
889 function insertStripItem( $text ) {
890 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
891 $this->mMarkerIndex++
;
892 $this->mStripState
->addGeneral( $rnd, $text );
897 * parse the wiki syntax used to render tables
902 function doTableStuff( $text ) {
903 wfProfileIn( __METHOD__
);
905 $lines = StringUtils
::explode( "\n", $text );
907 $td_history = array(); # Is currently a td tag open?
908 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
909 $tr_history = array(); # Is currently a tr tag open?
910 $tr_attributes = array(); # history of tr attributes
911 $has_opened_tr = array(); # Did this table open a <tr> element?
912 $indent_level = 0; # indent level of the table
914 foreach ( $lines as $outLine ) {
915 $line = trim( $outLine );
917 if ( $line === '' ) { # empty line, go to next line
918 $out .= $outLine."\n";
922 $first_character = $line[0];
925 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
926 # First check if we are starting a new table
927 $indent_level = strlen( $matches[1] );
929 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
930 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
932 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
933 array_push( $td_history , false );
934 array_push( $last_tag_history , '' );
935 array_push( $tr_history , false );
936 array_push( $tr_attributes , '' );
937 array_push( $has_opened_tr , false );
938 } elseif ( count( $td_history ) == 0 ) {
939 # Don't do any of the following
940 $out .= $outLine."\n";
942 } elseif ( substr( $line , 0 , 2 ) === '|}' ) {
943 # We are ending a table
944 $line = '</table>' . substr( $line , 2 );
945 $last_tag = array_pop( $last_tag_history );
947 if ( !array_pop( $has_opened_tr ) ) {
948 $line = "<tr><td></td></tr>{$line}";
951 if ( array_pop( $tr_history ) ) {
952 $line = "</tr>{$line}";
955 if ( array_pop( $td_history ) ) {
956 $line = "</{$last_tag}>{$line}";
958 array_pop( $tr_attributes );
959 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
960 } elseif ( substr( $line , 0 , 2 ) === '|-' ) {
961 # Now we have a table row
962 $line = preg_replace( '#^\|-+#', '', $line );
964 # Whats after the tag is now only attributes
965 $attributes = $this->mStripState
->unstripBoth( $line );
966 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
967 array_pop( $tr_attributes );
968 array_push( $tr_attributes, $attributes );
971 $last_tag = array_pop( $last_tag_history );
972 array_pop( $has_opened_tr );
973 array_push( $has_opened_tr , true );
975 if ( array_pop( $tr_history ) ) {
979 if ( array_pop( $td_history ) ) {
980 $line = "</{$last_tag}>{$line}";
984 array_push( $tr_history , false );
985 array_push( $td_history , false );
986 array_push( $last_tag_history , '' );
987 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line , 0 , 2 ) === '|+' ) {
988 # This might be cell elements, td, th or captions
989 if ( substr( $line , 0 , 2 ) === '|+' ) {
990 $first_character = '+';
991 $line = substr( $line , 1 );
994 $line = substr( $line , 1 );
996 if ( $first_character === '!' ) {
997 $line = str_replace( '!!' , '||' , $line );
1000 # Split up multiple cells on the same line.
1001 # FIXME : This can result in improper nesting of tags processed
1002 # by earlier parser steps, but should avoid splitting up eg
1003 # attribute values containing literal "||".
1004 $cells = StringUtils
::explodeMarkup( '||' , $line );
1008 # Loop through each table cell
1009 foreach ( $cells as $cell ) {
1011 if ( $first_character !== '+' ) {
1012 $tr_after = array_pop( $tr_attributes );
1013 if ( !array_pop( $tr_history ) ) {
1014 $previous = "<tr{$tr_after}>\n";
1016 array_push( $tr_history , true );
1017 array_push( $tr_attributes , '' );
1018 array_pop( $has_opened_tr );
1019 array_push( $has_opened_tr , true );
1022 $last_tag = array_pop( $last_tag_history );
1024 if ( array_pop( $td_history ) ) {
1025 $previous = "</{$last_tag}>\n{$previous}";
1028 if ( $first_character === '|' ) {
1030 } elseif ( $first_character === '!' ) {
1032 } elseif ( $first_character === '+' ) {
1033 $last_tag = 'caption';
1038 array_push( $last_tag_history , $last_tag );
1040 # A cell could contain both parameters and data
1041 $cell_data = explode( '|' , $cell , 2 );
1043 # Bug 553: Note that a '|' inside an invalid link should not
1044 # be mistaken as delimiting cell parameters
1045 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1046 $cell = "{$previous}<{$last_tag}>{$cell}";
1047 } elseif ( count( $cell_data ) == 1 ) {
1048 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1050 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1051 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
1052 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1056 array_push( $td_history , true );
1059 $out .= $outLine . "\n";
1062 # Closing open td, tr && table
1063 while ( count( $td_history ) > 0 ) {
1064 if ( array_pop( $td_history ) ) {
1067 if ( array_pop( $tr_history ) ) {
1070 if ( !array_pop( $has_opened_tr ) ) {
1071 $out .= "<tr><td></td></tr>\n" ;
1074 $out .= "</table>\n";
1077 # Remove trailing line-ending (b/c)
1078 if ( substr( $out, -1 ) === "\n" ) {
1079 $out = substr( $out, 0, -1 );
1082 # special case: don't return empty table
1083 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1087 wfProfileOut( __METHOD__
);
1093 * Helper function for parse() that transforms wiki markup into
1094 * HTML. Only called for $mOutputType == self::OT_HTML.
1098 * @param $text string
1099 * @param $isMain bool
1100 * @param $frame bool
1104 function internalParse( $text, $isMain = true, $frame = false ) {
1105 wfProfileIn( __METHOD__
);
1109 # Hook to suspend the parser in this state
1110 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1111 wfProfileOut( __METHOD__
);
1115 # if $frame is provided, then use $frame for replacing any variables
1117 # use frame depth to infer how include/noinclude tags should be handled
1118 # depth=0 means this is the top-level document; otherwise it's an included document
1119 if ( !$frame->depth
) {
1122 $flag = Parser
::PTD_FOR_INCLUSION
;
1124 $dom = $this->preprocessToDom( $text, $flag );
1125 $text = $frame->expand( $dom );
1127 # if $frame is not provided, then use old-style replaceVariables
1128 $text = $this->replaceVariables( $text );
1131 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1132 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1133 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1135 # Tables need to come after variable replacement for things to work
1136 # properly; putting them before other transformations should keep
1137 # exciting things like link expansions from showing up in surprising
1139 $text = $this->doTableStuff( $text );
1141 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1143 $text = $this->doDoubleUnderscore( $text );
1145 $text = $this->doHeadings( $text );
1146 if ( $this->mOptions
->getUseDynamicDates() ) {
1147 $df = DateFormatter
::getInstance();
1148 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1150 $text = $this->replaceInternalLinks( $text );
1151 $text = $this->doAllQuotes( $text );
1152 $text = $this->replaceExternalLinks( $text );
1154 # replaceInternalLinks may sometimes leave behind
1155 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1156 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
1158 $text = $this->doMagicLinks( $text );
1159 $text = $this->formatHeadings( $text, $origText, $isMain );
1161 wfProfileOut( __METHOD__
);
1166 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1167 * magic external links.
1172 * @param $text string
1176 function doMagicLinks( $text ) {
1177 wfProfileIn( __METHOD__
);
1178 $prots = wfUrlProtocolsWithoutProtRel();
1179 $urlChar = self
::EXT_LINK_URL_CLASS
;
1180 $text = preg_replace_callback(
1182 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1183 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1184 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1185 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1186 ISBN\s+(\b # m[5]: ISBN, capture number
1187 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1188 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1189 [0-9Xx] # check digit
1191 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1192 wfProfileOut( __METHOD__
);
1197 * @throws MWException
1199 * @return HTML|string
1201 function magicLinkCallback( $m ) {
1202 if ( isset( $m[1] ) && $m[1] !== '' ) {
1205 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1208 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1209 # Free external link
1210 return $this->makeFreeExternalLink( $m[0] );
1211 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1213 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1216 $CssClass = 'mw-magiclink-rfc';
1218 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1220 $urlmsg = 'pubmedurl';
1221 $CssClass = 'mw-magiclink-pmid';
1224 throw new MWException( __METHOD__
.': unrecognised match type "' .
1225 substr( $m[0], 0, 20 ) . '"' );
1227 $url = wfMsgForContent( $urlmsg, $id );
1228 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1229 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1232 $num = strtr( $isbn, array(
1237 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1239 htmlspecialchars( $titleObj->getLocalUrl() ) .
1240 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1247 * Make a free external link, given a user-supplied URL
1249 * @param $url string
1251 * @return string HTML
1254 function makeFreeExternalLink( $url ) {
1255 wfProfileIn( __METHOD__
);
1259 # The characters '<' and '>' (which were escaped by
1260 # removeHTMLtags()) should not be included in
1261 # URLs, per RFC 2396.
1263 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1264 $trail = substr( $url, $m2[0][1] ) . $trail;
1265 $url = substr( $url, 0, $m2[0][1] );
1268 # Move trailing punctuation to $trail
1270 # If there is no left bracket, then consider right brackets fair game too
1271 if ( strpos( $url, '(' ) === false ) {
1275 $numSepChars = strspn( strrev( $url ), $sep );
1276 if ( $numSepChars ) {
1277 $trail = substr( $url, -$numSepChars ) . $trail;
1278 $url = substr( $url, 0, -$numSepChars );
1281 $url = Sanitizer
::cleanUrl( $url );
1283 # Is this an external image?
1284 $text = $this->maybeMakeExternalImage( $url );
1285 if ( $text === false ) {
1286 # Not an image, make a link
1287 $text = Linker
::makeExternalLink( $url,
1288 $this->getConverterLanguage()->markNoConversion($url), true, 'free',
1289 $this->getExternalLinkAttribs( $url ) );
1290 # Register it in the output object...
1291 # Replace unnecessary URL escape codes with their equivalent characters
1292 $pasteurized = self
::replaceUnusualEscapes( $url );
1293 $this->mOutput
->addExternalLink( $pasteurized );
1295 wfProfileOut( __METHOD__
);
1296 return $text . $trail;
1301 * Parse headers and return html
1305 * @param $text string
1309 function doHeadings( $text ) {
1310 wfProfileIn( __METHOD__
);
1311 for ( $i = 6; $i >= 1; --$i ) {
1312 $h = str_repeat( '=', $i );
1313 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1314 "<h$i>\\1</h$i>", $text );
1316 wfProfileOut( __METHOD__
);
1321 * Replace single quotes with HTML markup
1324 * @param $text string
1326 * @return string the altered text
1328 function doAllQuotes( $text ) {
1329 wfProfileIn( __METHOD__
);
1331 $lines = StringUtils
::explode( "\n", $text );
1332 foreach ( $lines as $line ) {
1333 $outtext .= $this->doQuotes( $line ) . "\n";
1335 $outtext = substr( $outtext, 0,-1 );
1336 wfProfileOut( __METHOD__
);
1341 * Helper function for doAllQuotes()
1343 * @param $text string
1347 public function doQuotes( $text ) {
1348 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1349 if ( count( $arr ) == 1 ) {
1352 # First, do some preliminary work. This may shift some apostrophes from
1353 # being mark-up to being text. It also counts the number of occurrences
1354 # of bold and italics mark-ups.
1357 for ( $i = 0; $i < count( $arr ); $i++
) {
1358 if ( ( $i %
2 ) == 1 ) {
1359 # If there are ever four apostrophes, assume the first is supposed to
1360 # be text, and the remaining three constitute mark-up for bold text.
1361 if ( strlen( $arr[$i] ) == 4 ) {
1364 } elseif ( strlen( $arr[$i] ) > 5 ) {
1365 # If there are more than 5 apostrophes in a row, assume they're all
1366 # text except for the last 5.
1367 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1370 # Count the number of occurrences of bold and italics mark-ups.
1371 # We are not counting sequences of five apostrophes.
1372 if ( strlen( $arr[$i] ) == 2 ) {
1374 } elseif ( strlen( $arr[$i] ) == 3 ) {
1376 } elseif ( strlen( $arr[$i] ) == 5 ) {
1383 # If there is an odd number of both bold and italics, it is likely
1384 # that one of the bold ones was meant to be an apostrophe followed
1385 # by italics. Which one we cannot know for certain, but it is more
1386 # likely to be one that has a single-letter word before it.
1387 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1389 $firstsingleletterword = -1;
1390 $firstmultiletterword = -1;
1392 foreach ( $arr as $r ) {
1393 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1394 $x1 = substr( $arr[$i-1], -1 );
1395 $x2 = substr( $arr[$i-1], -2, 1 );
1396 if ( $x1 === ' ' ) {
1397 if ( $firstspace == -1 ) {
1400 } elseif ( $x2 === ' ') {
1401 if ( $firstsingleletterword == -1 ) {
1402 $firstsingleletterword = $i;
1405 if ( $firstmultiletterword == -1 ) {
1406 $firstmultiletterword = $i;
1413 # If there is a single-letter word, use it!
1414 if ( $firstsingleletterword > -1 ) {
1415 $arr[$firstsingleletterword] = "''";
1416 $arr[$firstsingleletterword-1] .= "'";
1417 } elseif ( $firstmultiletterword > -1 ) {
1418 # If not, but there's a multi-letter word, use that one.
1419 $arr[$firstmultiletterword] = "''";
1420 $arr[$firstmultiletterword-1] .= "'";
1421 } elseif ( $firstspace > -1 ) {
1422 # ... otherwise use the first one that has neither.
1423 # (notice that it is possible for all three to be -1 if, for example,
1424 # there is only one pentuple-apostrophe in the line)
1425 $arr[$firstspace] = "''";
1426 $arr[$firstspace-1] .= "'";
1430 # Now let's actually convert our apostrophic mush to HTML!
1435 foreach ( $arr as $r ) {
1436 if ( ( $i %
2 ) == 0 ) {
1437 if ( $state === 'both' ) {
1443 if ( strlen( $r ) == 2 ) {
1444 if ( $state === 'i' ) {
1445 $output .= '</i>'; $state = '';
1446 } elseif ( $state === 'bi' ) {
1447 $output .= '</i>'; $state = 'b';
1448 } elseif ( $state === 'ib' ) {
1449 $output .= '</b></i><b>'; $state = 'b';
1450 } elseif ( $state === 'both' ) {
1451 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1452 } else { # $state can be 'b' or ''
1453 $output .= '<i>'; $state .= 'i';
1455 } elseif ( strlen( $r ) == 3 ) {
1456 if ( $state === 'b' ) {
1457 $output .= '</b>'; $state = '';
1458 } elseif ( $state === 'bi' ) {
1459 $output .= '</i></b><i>'; $state = 'i';
1460 } elseif ( $state === 'ib' ) {
1461 $output .= '</b>'; $state = 'i';
1462 } elseif ( $state === 'both' ) {
1463 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1464 } else { # $state can be 'i' or ''
1465 $output .= '<b>'; $state .= 'b';
1467 } elseif ( strlen( $r ) == 5 ) {
1468 if ( $state === 'b' ) {
1469 $output .= '</b><i>'; $state = 'i';
1470 } elseif ( $state === 'i' ) {
1471 $output .= '</i><b>'; $state = 'b';
1472 } elseif ( $state === 'bi' ) {
1473 $output .= '</i></b>'; $state = '';
1474 } elseif ( $state === 'ib' ) {
1475 $output .= '</b></i>'; $state = '';
1476 } elseif ( $state === 'both' ) {
1477 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1478 } else { # ($state == '')
1479 $buffer = ''; $state = 'both';
1485 # Now close all remaining tags. Notice that the order is important.
1486 if ( $state === 'b' ||
$state === 'ib' ) {
1489 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1492 if ( $state === 'bi' ) {
1495 # There might be lonely ''''', so make sure we have a buffer
1496 if ( $state === 'both' && $buffer ) {
1497 $output .= '<b><i>'.$buffer.'</i></b>';
1504 * Replace external links (REL)
1506 * Note: this is all very hackish and the order of execution matters a lot.
1507 * Make sure to run maintenance/parserTests.php if you change this code.
1511 * @param $text string
1515 function replaceExternalLinks( $text ) {
1516 wfProfileIn( __METHOD__
);
1518 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1519 $s = array_shift( $bits );
1522 while ( $i<count( $bits ) ) {
1524 $protocol = $bits[$i++
];
1525 $text = $bits[$i++
];
1526 $trail = $bits[$i++
];
1528 # The characters '<' and '>' (which were escaped by
1529 # removeHTMLtags()) should not be included in
1530 # URLs, per RFC 2396.
1532 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1533 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1534 $url = substr( $url, 0, $m2[0][1] );
1537 # If the link text is an image URL, replace it with an <img> tag
1538 # This happened by accident in the original parser, but some people used it extensively
1539 $img = $this->maybeMakeExternalImage( $text );
1540 if ( $img !== false ) {
1546 # Set linktype for CSS - if URL==text, link is essentially free
1547 $linktype = ( $text === $url ) ?
'free' : 'text';
1549 # No link text, e.g. [http://domain.tld/some.link]
1550 if ( $text == '' ) {
1552 $langObj = $this->getTargetLanguage();
1553 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1554 $linktype = 'autonumber';
1556 # Have link text, e.g. [http://domain.tld/some.link text]s
1558 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1561 $text = $this->getConverterLanguage()->markNoConversion( $text );
1563 $url = Sanitizer
::cleanUrl( $url );
1565 # Use the encoded URL
1566 # This means that users can paste URLs directly into the text
1567 # Funny characters like ö aren't valid in URLs anyway
1568 # This was changed in August 2004
1569 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1570 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1572 # Register link in the output object.
1573 # Replace unnecessary URL escape codes with the referenced character
1574 # This prevents spammers from hiding links from the filters
1575 $pasteurized = self
::replaceUnusualEscapes( $url );
1576 $this->mOutput
->addExternalLink( $pasteurized );
1579 wfProfileOut( __METHOD__
);
1584 * Get an associative array of additional HTML attributes appropriate for a
1585 * particular external link. This currently may include rel => nofollow
1586 * (depending on configuration, namespace, and the URL's domain) and/or a
1587 * target attribute (depending on configuration).
1589 * @param $url String|bool optional URL, to extract the domain from for rel =>
1590 * nofollow if appropriate
1591 * @return Array associative array of HTML attributes
1593 function getExternalLinkAttribs( $url = false ) {
1595 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1596 $ns = $this->mTitle
->getNamespace();
1597 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) &&
1598 !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions ) )
1600 $attribs['rel'] = 'nofollow';
1602 if ( $this->mOptions
->getExternalLinkTarget() ) {
1603 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1609 * Replace unusual URL escape codes with their equivalent characters
1611 * @param $url String
1614 * @todo This can merge genuinely required bits in the path or query string,
1615 * breaking legit URLs. A proper fix would treat the various parts of
1616 * the URL differently; as a workaround, just use the output for
1617 * statistical records, not for actual linking/output.
1619 static function replaceUnusualEscapes( $url ) {
1620 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1621 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1625 * Callback function used in replaceUnusualEscapes().
1626 * Replaces unusual URL escape codes with their equivalent character
1628 * @param $matches array
1632 private static function replaceUnusualEscapesCallback( $matches ) {
1633 $char = urldecode( $matches[0] );
1634 $ord = ord( $char );
1635 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1636 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1637 # No, shouldn't be escaped
1640 # Yes, leave it escaped
1646 * make an image if it's allowed, either through the global
1647 * option, through the exception, or through the on-wiki whitelist
1650 * $param $url string
1654 function maybeMakeExternalImage( $url ) {
1655 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1656 $imagesexception = !empty( $imagesfrom );
1658 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1659 if ( $imagesexception && is_array( $imagesfrom ) ) {
1660 $imagematch = false;
1661 foreach ( $imagesfrom as $match ) {
1662 if ( strpos( $url, $match ) === 0 ) {
1667 } elseif ( $imagesexception ) {
1668 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1670 $imagematch = false;
1672 if ( $this->mOptions
->getAllowExternalImages()
1673 ||
( $imagesexception && $imagematch ) ) {
1674 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1676 $text = Linker
::makeExternalImage( $url );
1679 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1680 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1681 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1682 foreach ( $whitelist as $entry ) {
1683 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1684 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1687 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1688 # Image matches a whitelist entry
1689 $text = Linker
::makeExternalImage( $url );
1698 * Process [[ ]] wikilinks
1702 * @return String: processed text
1706 function replaceInternalLinks( $s ) {
1707 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1712 * Process [[ ]] wikilinks (RIL)
1713 * @return LinkHolderArray
1717 function replaceInternalLinks2( &$s ) {
1718 wfProfileIn( __METHOD__
);
1720 wfProfileIn( __METHOD__
.'-setup' );
1721 static $tc = FALSE, $e1, $e1_img;
1722 # the % is needed to support urlencoded titles as well
1724 $tc = Title
::legalChars() . '#%';
1725 # Match a link having the form [[namespace:link|alternate]]trail
1726 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1727 # Match cases where there is no "]]", which might still be images
1728 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1731 $holders = new LinkHolderArray( $this );
1733 # split the entire text string on occurrences of [[
1734 $a = StringUtils
::explode( '[[', ' ' . $s );
1735 # get the first element (all text up to first [[), and remove the space we added
1738 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1739 $s = substr( $s, 1 );
1741 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1743 if ( $useLinkPrefixExtension ) {
1744 # Match the end of a line for a word that's not followed by whitespace,
1745 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1746 $e2 = wfMsgForContent( 'linkprefix' );
1749 if ( is_null( $this->mTitle
) ) {
1750 wfProfileOut( __METHOD__
.'-setup' );
1751 wfProfileOut( __METHOD__
);
1752 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1754 $nottalk = !$this->mTitle
->isTalkPage();
1756 if ( $useLinkPrefixExtension ) {
1758 if ( preg_match( $e2, $s, $m ) ) {
1759 $first_prefix = $m[2];
1761 $first_prefix = false;
1767 if ( $this->getConverterLanguage()->hasVariants() ) {
1768 $selflink = $this->getConverterLanguage()->autoConvertToAllVariants(
1769 $this->mTitle
->getPrefixedText() );
1771 $selflink = array( $this->mTitle
->getPrefixedText() );
1773 $useSubpages = $this->areSubpagesAllowed();
1774 wfProfileOut( __METHOD__
.'-setup' );
1776 # Loop for each link
1777 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1778 # Check for excessive memory usage
1779 if ( $holders->isBig() ) {
1781 # Do the existence check, replace the link holders and clear the array
1782 $holders->replace( $s );
1786 if ( $useLinkPrefixExtension ) {
1787 wfProfileIn( __METHOD__
.'-prefixhandling' );
1788 if ( preg_match( $e2, $s, $m ) ) {
1795 if ( $first_prefix ) {
1796 $prefix = $first_prefix;
1797 $first_prefix = false;
1799 wfProfileOut( __METHOD__
.'-prefixhandling' );
1802 $might_be_img = false;
1804 wfProfileIn( __METHOD__
."-e1" );
1805 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1807 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1808 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1809 # the real problem is with the $e1 regex
1812 # Still some problems for cases where the ] is meant to be outside punctuation,
1813 # and no image is in sight. See bug 2095.
1815 if ( $text !== '' &&
1816 substr( $m[3], 0, 1 ) === ']' &&
1817 strpos( $text, '[' ) !== false
1820 $text .= ']'; # so that replaceExternalLinks($text) works later
1821 $m[3] = substr( $m[3], 1 );
1823 # fix up urlencoded title texts
1824 if ( strpos( $m[1], '%' ) !== false ) {
1825 # Should anchors '#' also be rejected?
1826 $m[1] = str_replace( array('<', '>'), array('<', '>'), rawurldecode( $m[1] ) );
1829 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1830 $might_be_img = true;
1832 if ( strpos( $m[1], '%' ) !== false ) {
1833 $m[1] = rawurldecode( $m[1] );
1836 } else { # Invalid form; output directly
1837 $s .= $prefix . '[[' . $line ;
1838 wfProfileOut( __METHOD__
."-e1" );
1841 wfProfileOut( __METHOD__
."-e1" );
1842 wfProfileIn( __METHOD__
."-misc" );
1844 # Don't allow internal links to pages containing
1845 # PROTO: where PROTO is a valid URL protocol; these
1846 # should be external links.
1847 if ( preg_match( '/^(?:' . $this->mUrlProtocols
. ')/', $m[1] ) ) {
1848 $s .= $prefix . '[[' . $line ;
1849 wfProfileOut( __METHOD__
."-misc" );
1853 # Make subpage if necessary
1854 if ( $useSubpages ) {
1855 $link = $this->maybeDoSubpageLink( $m[1], $text );
1860 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1862 # Strip off leading ':'
1863 $link = substr( $link, 1 );
1866 wfProfileOut( __METHOD__
."-misc" );
1867 wfProfileIn( __METHOD__
."-title" );
1868 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1869 if ( $nt === null ) {
1870 $s .= $prefix . '[[' . $line;
1871 wfProfileOut( __METHOD__
."-title" );
1875 $ns = $nt->getNamespace();
1876 $iw = $nt->getInterWiki();
1877 wfProfileOut( __METHOD__
."-title" );
1879 if ( $might_be_img ) { # if this is actually an invalid link
1880 wfProfileIn( __METHOD__
."-might_be_img" );
1881 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1884 # look at the next 'line' to see if we can close it there
1886 $next_line = $a->current();
1887 if ( $next_line === false ||
$next_line === null ) {
1890 $m = explode( ']]', $next_line, 3 );
1891 if ( count( $m ) == 3 ) {
1892 # the first ]] closes the inner link, the second the image
1894 $text .= "[[{$m[0]}]]{$m[1]}";
1897 } elseif ( count( $m ) == 2 ) {
1898 # if there's exactly one ]] that's fine, we'll keep looking
1899 $text .= "[[{$m[0]}]]{$m[1]}";
1901 # if $next_line is invalid too, we need look no further
1902 $text .= '[[' . $next_line;
1907 # we couldn't find the end of this imageLink, so output it raw
1908 # but don't ignore what might be perfectly normal links in the text we've examined
1909 $holders->merge( $this->replaceInternalLinks2( $text ) );
1910 $s .= "{$prefix}[[$link|$text";
1911 # note: no $trail, because without an end, there *is* no trail
1912 wfProfileOut( __METHOD__
."-might_be_img" );
1915 } else { # it's not an image, so output it raw
1916 $s .= "{$prefix}[[$link|$text";
1917 # note: no $trail, because without an end, there *is* no trail
1918 wfProfileOut( __METHOD__
."-might_be_img" );
1921 wfProfileOut( __METHOD__
."-might_be_img" );
1924 $wasblank = ( $text == '' );
1928 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1929 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1930 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1931 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1932 $text = $this->doQuotes( $text );
1935 # Link not escaped by : , create the various objects
1938 wfProfileIn( __METHOD__
."-interwiki" );
1939 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && Language
::fetchLanguageName( $iw, null, 'mw' ) ) {
1940 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1941 $s = rtrim( $s . $prefix );
1942 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1943 wfProfileOut( __METHOD__
."-interwiki" );
1946 wfProfileOut( __METHOD__
."-interwiki" );
1948 if ( $ns == NS_FILE
) {
1949 wfProfileIn( __METHOD__
."-image" );
1950 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1952 # if no parameters were passed, $text
1953 # becomes something like "File:Foo.png",
1954 # which we don't want to pass on to the
1958 # recursively parse links inside the image caption
1959 # actually, this will parse them in any other parameters, too,
1960 # but it might be hard to fix that, and it doesn't matter ATM
1961 $text = $this->replaceExternalLinks( $text );
1962 $holders->merge( $this->replaceInternalLinks2( $text ) );
1964 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1965 $s .= $prefix . $this->armorLinks(
1966 $this->makeImage( $nt, $text, $holders ) ) . $trail;
1968 $s .= $prefix . $trail;
1970 wfProfileOut( __METHOD__
."-image" );
1974 if ( $ns == NS_CATEGORY
) {
1975 wfProfileIn( __METHOD__
."-category" );
1976 $s = rtrim( $s . "\n" ); # bug 87
1979 $sortkey = $this->getDefaultSort();
1983 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1984 $sortkey = str_replace( "\n", '', $sortkey );
1985 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
1986 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1989 * Strip the whitespace Category links produce, see bug 87
1990 * @todo We might want to use trim($tmp, "\n") here.
1992 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
1994 wfProfileOut( __METHOD__
."-category" );
1999 # Self-link checking
2000 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
2001 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
2002 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2007 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2008 # @todo FIXME: Should do batch file existence checks, see comment below
2009 if ( $ns == NS_MEDIA
) {
2010 wfProfileIn( __METHOD__
."-media" );
2011 # Give extensions a chance to select the file revision for us
2014 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2015 array( $this, $nt, &$options, &$descQuery ) );
2016 # Fetch and register the file (file title may be different via hooks)
2017 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2018 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2019 $s .= $prefix . $this->armorLinks(
2020 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2021 wfProfileOut( __METHOD__
."-media" );
2025 wfProfileIn( __METHOD__
."-always_known" );
2026 # Some titles, such as valid special pages or files in foreign repos, should
2027 # be shown as bluelinks even though they're not included in the page table
2029 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2030 # batch file existence checks for NS_FILE and NS_MEDIA
2031 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2032 $this->mOutput
->addLink( $nt );
2033 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2035 # Links will be added to the output link list after checking
2036 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2038 wfProfileOut( __METHOD__
."-always_known" );
2040 wfProfileOut( __METHOD__
);
2045 * Render a forced-blue link inline; protect against double expansion of
2046 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2047 * Since this little disaster has to split off the trail text to avoid
2048 * breaking URLs in the following text without breaking trails on the
2049 * wiki links, it's been made into a horrible function.
2052 * @param $text String
2053 * @param $query Array or String
2054 * @param $trail String
2055 * @param $prefix String
2056 * @return String: HTML-wikitext mix oh yuck
2058 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2059 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2061 if ( is_string( $query ) ) {
2062 $query = wfCgiToArray( $query );
2064 if ( $text == '' ) {
2065 $text = htmlspecialchars( $nt->getPrefixedText() );
2068 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2070 return $this->armorLinks( $link ) . $trail;
2074 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2075 * going to go through further parsing steps before inline URL expansion.
2077 * Not needed quite as much as it used to be since free links are a bit
2078 * more sensible these days. But bracketed links are still an issue.
2080 * @param $text String: more-or-less HTML
2081 * @return String: less-or-more HTML with NOPARSE bits
2083 function armorLinks( $text ) {
2084 return preg_replace( '/\b(' . $this->mUrlProtocols
. ')/',
2085 "{$this->mUniqPrefix}NOPARSE$1", $text );
2089 * Return true if subpage links should be expanded on this page.
2092 function areSubpagesAllowed() {
2093 # Some namespaces don't allow subpages
2094 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2098 * Handle link to subpage if necessary
2100 * @param $target String: the source of the link
2101 * @param &$text String: the link text, modified as necessary
2102 * @return string the full name of the link
2105 function maybeDoSubpageLink( $target, &$text ) {
2106 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2110 * Used by doBlockLevels()
2115 function closeParagraph() {
2117 if ( $this->mLastSection
!= '' ) {
2118 $result = '</' . $this->mLastSection
. ">\n";
2120 $this->mInPre
= false;
2121 $this->mLastSection
= '';
2126 * getCommon() returns the length of the longest common substring
2127 * of both arguments, starting at the beginning of both.
2130 * @param $st1 string
2131 * @param $st2 string
2135 function getCommon( $st1, $st2 ) {
2136 $fl = strlen( $st1 );
2137 $shorter = strlen( $st2 );
2138 if ( $fl < $shorter ) {
2142 for ( $i = 0; $i < $shorter; ++
$i ) {
2143 if ( $st1[$i] != $st2[$i] ) {
2151 * These next three functions open, continue, and close the list
2152 * element appropriate to the prefix character passed into them.
2155 * @param $char string
2159 function openList( $char ) {
2160 $result = $this->closeParagraph();
2162 if ( '*' === $char ) {
2163 $result .= '<ul><li>';
2164 } elseif ( '#' === $char ) {
2165 $result .= '<ol><li>';
2166 } elseif ( ':' === $char ) {
2167 $result .= '<dl><dd>';
2168 } elseif ( ';' === $char ) {
2169 $result .= '<dl><dt>';
2170 $this->mDTopen
= true;
2172 $result = '<!-- ERR 1 -->';
2180 * @param $char String
2185 function nextItem( $char ) {
2186 if ( '*' === $char ||
'#' === $char ) {
2188 } elseif ( ':' === $char ||
';' === $char ) {
2190 if ( $this->mDTopen
) {
2193 if ( ';' === $char ) {
2194 $this->mDTopen
= true;
2195 return $close . '<dt>';
2197 $this->mDTopen
= false;
2198 return $close . '<dd>';
2201 return '<!-- ERR 2 -->';
2206 * @param $char String
2211 function closeList( $char ) {
2212 if ( '*' === $char ) {
2213 $text = '</li></ul>';
2214 } elseif ( '#' === $char ) {
2215 $text = '</li></ol>';
2216 } elseif ( ':' === $char ) {
2217 if ( $this->mDTopen
) {
2218 $this->mDTopen
= false;
2219 $text = '</dt></dl>';
2221 $text = '</dd></dl>';
2224 return '<!-- ERR 3 -->';
2231 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2233 * @param $text String
2234 * @param $linestart Boolean: whether or not this is at the start of a line.
2236 * @return string the lists rendered as HTML
2238 function doBlockLevels( $text, $linestart ) {
2239 wfProfileIn( __METHOD__
);
2241 # Parsing through the text line by line. The main thing
2242 # happening here is handling of block-level elements p, pre,
2243 # and making lists from lines starting with * # : etc.
2245 $textLines = StringUtils
::explode( "\n", $text );
2247 $lastPrefix = $output = '';
2248 $this->mDTopen
= $inBlockElem = false;
2250 $paragraphStack = false;
2252 foreach ( $textLines as $oLine ) {
2254 if ( !$linestart ) {
2264 $lastPrefixLength = strlen( $lastPrefix );
2265 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2266 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2267 # If not in a <pre> element, scan for and figure out what prefixes are there.
2268 if ( !$this->mInPre
) {
2269 # Multiple prefixes may abut each other for nested lists.
2270 $prefixLength = strspn( $oLine, '*#:;' );
2271 $prefix = substr( $oLine, 0, $prefixLength );
2274 # ; and : are both from definition-lists, so they're equivalent
2275 # for the purposes of determining whether or not we need to open/close
2277 $prefix2 = str_replace( ';', ':', $prefix );
2278 $t = substr( $oLine, $prefixLength );
2279 $this->mInPre
= (bool)$preOpenMatch;
2281 # Don't interpret any other prefixes in preformatted text
2283 $prefix = $prefix2 = '';
2288 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2289 # Same as the last item, so no need to deal with nesting or opening stuff
2290 $output .= $this->nextItem( substr( $prefix, -1 ) );
2291 $paragraphStack = false;
2293 if ( substr( $prefix, -1 ) === ';') {
2294 # The one nasty exception: definition lists work like this:
2295 # ; title : definition text
2296 # So we check for : in the remainder text to split up the
2297 # title and definition, without b0rking links.
2299 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2301 $output .= $term . $this->nextItem( ':' );
2304 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2305 # We need to open or close prefixes, or both.
2307 # Either open or close a level...
2308 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2309 $paragraphStack = false;
2311 # Close all the prefixes which aren't shared.
2312 while ( $commonPrefixLength < $lastPrefixLength ) {
2313 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2314 --$lastPrefixLength;
2317 # Continue the current prefix if appropriate.
2318 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2319 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2322 # Open prefixes where appropriate.
2323 while ( $prefixLength > $commonPrefixLength ) {
2324 $char = substr( $prefix, $commonPrefixLength, 1 );
2325 $output .= $this->openList( $char );
2327 if ( ';' === $char ) {
2328 # @todo FIXME: This is dupe of code above
2329 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2331 $output .= $term . $this->nextItem( ':' );
2334 ++
$commonPrefixLength;
2336 $lastPrefix = $prefix2;
2339 # If we have no prefixes, go to paragraph mode.
2340 if ( 0 == $prefixLength ) {
2341 wfProfileIn( __METHOD__
."-paragraph" );
2342 # No prefix (not in list)--go to paragraph mode
2343 # XXX: use a stack for nestable elements like span, table and div
2344 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2345 $closematch = preg_match(
2346 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2347 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2348 if ( $openmatch or $closematch ) {
2349 $paragraphStack = false;
2350 # TODO bug 5718: paragraph closed
2351 $output .= $this->closeParagraph();
2352 if ( $preOpenMatch and !$preCloseMatch ) {
2353 $this->mInPre
= true;
2355 $inBlockElem = !$closematch;
2356 } elseif ( !$inBlockElem && !$this->mInPre
) {
2357 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2359 if ( $this->mLastSection
!== 'pre' ) {
2360 $paragraphStack = false;
2361 $output .= $this->closeParagraph().'<pre>';
2362 $this->mLastSection
= 'pre';
2364 $t = substr( $t, 1 );
2367 if ( trim( $t ) === '' ) {
2368 if ( $paragraphStack ) {
2369 $output .= $paragraphStack.'<br />';
2370 $paragraphStack = false;
2371 $this->mLastSection
= 'p';
2373 if ( $this->mLastSection
!== 'p' ) {
2374 $output .= $this->closeParagraph();
2375 $this->mLastSection
= '';
2376 $paragraphStack = '<p>';
2378 $paragraphStack = '</p><p>';
2382 if ( $paragraphStack ) {
2383 $output .= $paragraphStack;
2384 $paragraphStack = false;
2385 $this->mLastSection
= 'p';
2386 } elseif ( $this->mLastSection
!== 'p' ) {
2387 $output .= $this->closeParagraph().'<p>';
2388 $this->mLastSection
= 'p';
2393 wfProfileOut( __METHOD__
."-paragraph" );
2395 # somewhere above we forget to get out of pre block (bug 785)
2396 if ( $preCloseMatch && $this->mInPre
) {
2397 $this->mInPre
= false;
2399 if ( $paragraphStack === false ) {
2403 while ( $prefixLength ) {
2404 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2407 if ( $this->mLastSection
!= '' ) {
2408 $output .= '</' . $this->mLastSection
. '>';
2409 $this->mLastSection
= '';
2412 wfProfileOut( __METHOD__
);
2417 * Split up a string on ':', ignoring any occurrences inside tags
2418 * to prevent illegal overlapping.
2420 * @param $str String the string to split
2421 * @param &$before String set to everything before the ':'
2422 * @param &$after String set to everything after the ':'
2423 * @return String the position of the ':', or false if none found
2425 function findColonNoLinks( $str, &$before, &$after ) {
2426 wfProfileIn( __METHOD__
);
2428 $pos = strpos( $str, ':' );
2429 if ( $pos === false ) {
2431 wfProfileOut( __METHOD__
);
2435 $lt = strpos( $str, '<' );
2436 if ( $lt === false ||
$lt > $pos ) {
2437 # Easy; no tag nesting to worry about
2438 $before = substr( $str, 0, $pos );
2439 $after = substr( $str, $pos+
1 );
2440 wfProfileOut( __METHOD__
);
2444 # Ugly state machine to walk through avoiding tags.
2445 $state = self
::COLON_STATE_TEXT
;
2447 $len = strlen( $str );
2448 for( $i = 0; $i < $len; $i++
) {
2452 # (Using the number is a performance hack for common cases)
2453 case 0: # self::COLON_STATE_TEXT:
2456 # Could be either a <start> tag or an </end> tag
2457 $state = self
::COLON_STATE_TAGSTART
;
2460 if ( $stack == 0 ) {
2462 $before = substr( $str, 0, $i );
2463 $after = substr( $str, $i +
1 );
2464 wfProfileOut( __METHOD__
);
2467 # Embedded in a tag; don't break it.
2470 # Skip ahead looking for something interesting
2471 $colon = strpos( $str, ':', $i );
2472 if ( $colon === false ) {
2473 # Nothing else interesting
2474 wfProfileOut( __METHOD__
);
2477 $lt = strpos( $str, '<', $i );
2478 if ( $stack === 0 ) {
2479 if ( $lt === false ||
$colon < $lt ) {
2481 $before = substr( $str, 0, $colon );
2482 $after = substr( $str, $colon +
1 );
2483 wfProfileOut( __METHOD__
);
2487 if ( $lt === false ) {
2488 # Nothing else interesting to find; abort!
2489 # We're nested, but there's no close tags left. Abort!
2492 # Skip ahead to next tag start
2494 $state = self
::COLON_STATE_TAGSTART
;
2497 case 1: # self::COLON_STATE_TAG:
2502 $state = self
::COLON_STATE_TEXT
;
2505 # Slash may be followed by >?
2506 $state = self
::COLON_STATE_TAGSLASH
;
2512 case 2: # self::COLON_STATE_TAGSTART:
2515 $state = self
::COLON_STATE_CLOSETAG
;
2518 $state = self
::COLON_STATE_COMMENT
;
2521 # Illegal early close? This shouldn't happen D:
2522 $state = self
::COLON_STATE_TEXT
;
2525 $state = self
::COLON_STATE_TAG
;
2528 case 3: # self::COLON_STATE_CLOSETAG:
2533 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2534 wfProfileOut( __METHOD__
);
2537 $state = self
::COLON_STATE_TEXT
;
2540 case self
::COLON_STATE_TAGSLASH
:
2542 # Yes, a self-closed tag <blah/>
2543 $state = self
::COLON_STATE_TEXT
;
2545 # Probably we're jumping the gun, and this is an attribute
2546 $state = self
::COLON_STATE_TAG
;
2549 case 5: # self::COLON_STATE_COMMENT:
2551 $state = self
::COLON_STATE_COMMENTDASH
;
2554 case self
::COLON_STATE_COMMENTDASH
:
2556 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2558 $state = self
::COLON_STATE_COMMENT
;
2561 case self
::COLON_STATE_COMMENTDASHDASH
:
2563 $state = self
::COLON_STATE_TEXT
;
2565 $state = self
::COLON_STATE_COMMENT
;
2569 throw new MWException( "State machine error in " . __METHOD__
);
2573 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2574 wfProfileOut( __METHOD__
);
2577 wfProfileOut( __METHOD__
);
2582 * Return value of a magic variable (like PAGENAME)
2586 * @param $index integer
2587 * @param $frame PPFrame
2591 function getVariableValue( $index, $frame = false ) {
2592 global $wgContLang, $wgSitename, $wgServer;
2593 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2595 if ( is_null( $this->mTitle
) ) {
2596 // If no title set, bad things are going to happen
2597 // later. Title should always be set since this
2598 // should only be called in the middle of a parse
2599 // operation (but the unit-tests do funky stuff)
2600 throw new MWException( __METHOD__
. ' Should only be '
2601 . ' called while parsing (no title set)' );
2605 * Some of these require message or data lookups and can be
2606 * expensive to check many times.
2608 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2609 if ( isset( $this->mVarCache
[$index] ) ) {
2610 return $this->mVarCache
[$index];
2614 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2615 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2618 global $wgLocaltimezone;
2619 if ( isset( $wgLocaltimezone ) ) {
2620 $oldtz = date_default_timezone_get();
2621 date_default_timezone_set( $wgLocaltimezone );
2624 $localTimestamp = date( 'YmdHis', $ts );
2625 $localMonth = date( 'm', $ts );
2626 $localMonth1 = date( 'n', $ts );
2627 $localMonthName = date( 'n', $ts );
2628 $localDay = date( 'j', $ts );
2629 $localDay2 = date( 'd', $ts );
2630 $localDayOfWeek = date( 'w', $ts );
2631 $localWeek = date( 'W', $ts );
2632 $localYear = date( 'Y', $ts );
2633 $localHour = date( 'H', $ts );
2634 if ( isset( $wgLocaltimezone ) ) {
2635 date_default_timezone_set( $oldtz );
2638 $pageLang = $this->getFunctionLang();
2641 case 'currentmonth':
2642 $value = $pageLang->formatNum( gmdate( 'm', $ts ) );
2644 case 'currentmonth1':
2645 $value = $pageLang->formatNum( gmdate( 'n', $ts ) );
2647 case 'currentmonthname':
2648 $value = $pageLang->getMonthName( gmdate( 'n', $ts ) );
2650 case 'currentmonthnamegen':
2651 $value = $pageLang->getMonthNameGen( gmdate( 'n', $ts ) );
2653 case 'currentmonthabbrev':
2654 $value = $pageLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2657 $value = $pageLang->formatNum( gmdate( 'j', $ts ) );
2660 $value = $pageLang->formatNum( gmdate( 'd', $ts ) );
2663 $value = $pageLang->formatNum( $localMonth );
2666 $value = $pageLang->formatNum( $localMonth1 );
2668 case 'localmonthname':
2669 $value = $pageLang->getMonthName( $localMonthName );
2671 case 'localmonthnamegen':
2672 $value = $pageLang->getMonthNameGen( $localMonthName );
2674 case 'localmonthabbrev':
2675 $value = $pageLang->getMonthAbbreviation( $localMonthName );
2678 $value = $pageLang->formatNum( $localDay );
2681 $value = $pageLang->formatNum( $localDay2 );
2684 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2687 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2689 case 'fullpagename':
2690 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2692 case 'fullpagenamee':
2693 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2696 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2698 case 'subpagenamee':
2699 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2701 case 'basepagename':
2702 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2704 case 'basepagenamee':
2705 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2707 case 'talkpagename':
2708 if ( $this->mTitle
->canTalk() ) {
2709 $talkPage = $this->mTitle
->getTalkPage();
2710 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2715 case 'talkpagenamee':
2716 if ( $this->mTitle
->canTalk() ) {
2717 $talkPage = $this->mTitle
->getTalkPage();
2718 $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() );
2723 case 'subjectpagename':
2724 $subjPage = $this->mTitle
->getSubjectPage();
2725 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2727 case 'subjectpagenamee':
2728 $subjPage = $this->mTitle
->getSubjectPage();
2729 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() );
2731 case 'pageid': // requested in bug 23427
2732 $pageid = $this->getTitle()->getArticleId();
2733 if( $pageid == 0 ) {
2734 # 0 means the page doesn't exist in the database,
2735 # which means the user is previewing a new page.
2736 # The vary-revision flag must be set, because the magic word
2737 # will have a different value once the page is saved.
2738 $this->mOutput
->setFlag( 'vary-revision' );
2739 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2741 $value = $pageid ?
$pageid : null;
2744 # Let the edit saving system know we should parse the page
2745 # *after* a revision ID has been assigned.
2746 $this->mOutput
->setFlag( 'vary-revision' );
2747 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2748 $value = $this->mRevisionId
;
2751 # Let the edit saving system know we should parse the page
2752 # *after* a revision ID has been assigned. This is for null edits.
2753 $this->mOutput
->setFlag( 'vary-revision' );
2754 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2755 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2757 case 'revisionday2':
2758 # Let the edit saving system know we should parse the page
2759 # *after* a revision ID has been assigned. This is for null edits.
2760 $this->mOutput
->setFlag( 'vary-revision' );
2761 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2762 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2764 case 'revisionmonth':
2765 # Let the edit saving system know we should parse the page
2766 # *after* a revision ID has been assigned. This is for null edits.
2767 $this->mOutput
->setFlag( 'vary-revision' );
2768 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2769 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2771 case 'revisionmonth1':
2772 # Let the edit saving system know we should parse the page
2773 # *after* a revision ID has been assigned. This is for null edits.
2774 $this->mOutput
->setFlag( 'vary-revision' );
2775 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2776 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2778 case 'revisionyear':
2779 # Let the edit saving system know we should parse the page
2780 # *after* a revision ID has been assigned. This is for null edits.
2781 $this->mOutput
->setFlag( 'vary-revision' );
2782 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2783 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2785 case 'revisiontimestamp':
2786 # Let the edit saving system know we should parse the page
2787 # *after* a revision ID has been assigned. This is for null edits.
2788 $this->mOutput
->setFlag( 'vary-revision' );
2789 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2790 $value = $this->getRevisionTimestamp();
2792 case 'revisionuser':
2793 # Let the edit saving system know we should parse the page
2794 # *after* a revision ID has been assigned. This is for null edits.
2795 $this->mOutput
->setFlag( 'vary-revision' );
2796 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2797 $value = $this->getRevisionUser();
2800 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2803 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2805 case 'namespacenumber':
2806 $value = $this->mTitle
->getNamespace();
2809 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2812 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2814 case 'subjectspace':
2815 $value = $this->mTitle
->getSubjectNsText();
2817 case 'subjectspacee':
2818 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2820 case 'currentdayname':
2821 $value = $pageLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2824 $value = $pageLang->formatNum( gmdate( 'Y', $ts ), true );
2827 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2830 $value = $pageLang->formatNum( gmdate( 'H', $ts ), true );
2833 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2834 # int to remove the padding
2835 $value = $pageLang->formatNum( (int)gmdate( 'W', $ts ) );
2838 $value = $pageLang->formatNum( gmdate( 'w', $ts ) );
2840 case 'localdayname':
2841 $value = $pageLang->getWeekdayName( $localDayOfWeek +
1 );
2844 $value = $pageLang->formatNum( $localYear, true );
2847 $value = $pageLang->time( $localTimestamp, false, false );
2850 $value = $pageLang->formatNum( $localHour, true );
2853 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2854 # int to remove the padding
2855 $value = $pageLang->formatNum( (int)$localWeek );
2858 $value = $pageLang->formatNum( $localDayOfWeek );
2860 case 'numberofarticles':
2861 $value = $pageLang->formatNum( SiteStats
::articles() );
2863 case 'numberoffiles':
2864 $value = $pageLang->formatNum( SiteStats
::images() );
2866 case 'numberofusers':
2867 $value = $pageLang->formatNum( SiteStats
::users() );
2869 case 'numberofactiveusers':
2870 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2872 case 'numberofpages':
2873 $value = $pageLang->formatNum( SiteStats
::pages() );
2875 case 'numberofadmins':
2876 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2878 case 'numberofedits':
2879 $value = $pageLang->formatNum( SiteStats
::edits() );
2881 case 'numberofviews':
2882 global $wgDisableCounters;
2883 $value = !$wgDisableCounters ?
$pageLang->formatNum( SiteStats
::views() ) : '';
2885 case 'currenttimestamp':
2886 $value = wfTimestamp( TS_MW
, $ts );
2888 case 'localtimestamp':
2889 $value = $localTimestamp;
2891 case 'currentversion':
2892 $value = SpecialVersion
::getVersion();
2895 return $wgArticlePath;
2901 $serverParts = wfParseUrl( $wgServer );
2902 return $serverParts && isset( $serverParts['host'] ) ?
$serverParts['host'] : $wgServer;
2904 return $wgScriptPath;
2906 return $wgStylePath;
2907 case 'directionmark':
2908 return $pageLang->getDirMark();
2909 case 'contentlanguage':
2910 global $wgLanguageCode;
2911 return $wgLanguageCode;
2914 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2922 $this->mVarCache
[$index] = $value;
2929 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2933 function initialiseVariables() {
2934 wfProfileIn( __METHOD__
);
2935 $variableIDs = MagicWord
::getVariableIDs();
2936 $substIDs = MagicWord
::getSubstIDs();
2938 $this->mVariables
= new MagicWordArray( $variableIDs );
2939 $this->mSubstWords
= new MagicWordArray( $substIDs );
2940 wfProfileOut( __METHOD__
);
2944 * Preprocess some wikitext and return the document tree.
2945 * This is the ghost of replace_variables().
2947 * @param $text String: The text to parse
2948 * @param $flags Integer: bitwise combination of:
2949 * self::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
2950 * included. Default is to assume a direct page view.
2952 * The generated DOM tree must depend only on the input text and the flags.
2953 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2955 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2956 * change in the DOM tree for a given text, must be passed through the section identifier
2957 * in the section edit link and thus back to extractSections().
2959 * The output of this function is currently only cached in process memory, but a persistent
2960 * cache may be implemented at a later date which takes further advantage of these strict
2961 * dependency requirements.
2967 function preprocessToDom( $text, $flags = 0 ) {
2968 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2973 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2979 public static function splitWhitespace( $s ) {
2980 $ltrimmed = ltrim( $s );
2981 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2982 $trimmed = rtrim( $ltrimmed );
2983 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2985 $w2 = substr( $ltrimmed, -$diff );
2989 return array( $w1, $trimmed, $w2 );
2993 * Replace magic variables, templates, and template arguments
2994 * with the appropriate text. Templates are substituted recursively,
2995 * taking care to avoid infinite loops.
2997 * Note that the substitution depends on value of $mOutputType:
2998 * self::OT_WIKI: only {{subst:}} templates
2999 * self::OT_PREPROCESS: templates but not extension tags
3000 * self::OT_HTML: all templates and extension tags
3002 * @param $text String the text to transform
3003 * @param $frame PPFrame Object describing the arguments passed to the template.
3004 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
3005 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
3006 * @param $argsOnly Boolean only do argument (triple-brace) expansion, not double-brace expansion
3011 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3012 # Is there any text? Also, Prevent too big inclusions!
3013 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3016 wfProfileIn( __METHOD__
);
3018 if ( $frame === false ) {
3019 $frame = $this->getPreprocessor()->newFrame();
3020 } elseif ( !( $frame instanceof PPFrame
) ) {
3021 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
3022 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3025 $dom = $this->preprocessToDom( $text );
3026 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3027 $text = $frame->expand( $dom, $flags );
3029 wfProfileOut( __METHOD__
);
3034 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3036 * @param $args array
3040 static function createAssocArgs( $args ) {
3041 $assocArgs = array();
3043 foreach ( $args as $arg ) {
3044 $eqpos = strpos( $arg, '=' );
3045 if ( $eqpos === false ) {
3046 $assocArgs[$index++
] = $arg;
3048 $name = trim( substr( $arg, 0, $eqpos ) );
3049 $value = trim( substr( $arg, $eqpos+
1 ) );
3050 if ( $value === false ) {
3053 if ( $name !== false ) {
3054 $assocArgs[$name] = $value;
3063 * Warn the user when a parser limitation is reached
3064 * Will warn at most once the user per limitation type
3066 * @param $limitationType String: should be one of:
3067 * 'expensive-parserfunction' (corresponding messages:
3068 * 'expensive-parserfunction-warning',
3069 * 'expensive-parserfunction-category')
3070 * 'post-expand-template-argument' (corresponding messages:
3071 * 'post-expand-template-argument-warning',
3072 * 'post-expand-template-argument-category')
3073 * 'post-expand-template-inclusion' (corresponding messages:
3074 * 'post-expand-template-inclusion-warning',
3075 * 'post-expand-template-inclusion-category')
3076 * @param $current int|null Current value
3077 * @param $max int|null Maximum allowed, when an explicit limit has been
3078 * exceeded, provide the values (optional)
3080 function limitationWarn( $limitationType, $current = null, $max = null) {
3081 # does no harm if $current and $max are present but are unnecessary for the message
3082 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
3083 $this->mOutput
->addWarning( $warning );
3084 $this->addTrackingCategory( "$limitationType-category" );
3088 * Return the text of a template, after recursively
3089 * replacing any variables or templates within the template.
3091 * @param $piece Array: the parts of the template
3092 * $piece['title']: the title, i.e. the part before the |
3093 * $piece['parts']: the parameter array
3094 * $piece['lineStart']: whether the brace was at the start of a line
3095 * @param $frame PPFrame The current frame, contains template arguments
3096 * @return String: the text of the template
3099 function braceSubstitution( $piece, $frame ) {
3101 wfProfileIn( __METHOD__
);
3102 wfProfileIn( __METHOD__
.'-setup' );
3105 $found = false; # $text has been filled
3106 $nowiki = false; # wiki markup in $text should be escaped
3107 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3108 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3109 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3110 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3112 # Title object, where $text came from
3115 # $part1 is the bit before the first |, and must contain only title characters.
3116 # Various prefixes will be stripped from it later.
3117 $titleWithSpaces = $frame->expand( $piece['title'] );
3118 $part1 = trim( $titleWithSpaces );
3121 # Original title text preserved for various purposes
3122 $originalTitle = $part1;
3124 # $args is a list of argument nodes, starting from index 0, not including $part1
3125 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3126 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3127 wfProfileOut( __METHOD__
.'-setup' );
3129 $titleProfileIn = null; // profile templates
3132 wfProfileIn( __METHOD__
.'-modifiers' );
3135 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3137 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3138 # Decide whether to expand template or keep wikitext as-is.
3139 if ( $this->ot
['wiki'] ) {
3140 if ( $substMatch === false ) {
3141 $literal = true; # literal when in PST with no prefix
3143 $literal = false; # expand when in PST with subst: or safesubst:
3146 if ( $substMatch == 'subst' ) {
3147 $literal = true; # literal when not in PST with plain subst:
3149 $literal = false; # expand when not in PST with safesubst: or no prefix
3153 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3160 if ( !$found && $args->getLength() == 0 ) {
3161 $id = $this->mVariables
->matchStartToEnd( $part1 );
3162 if ( $id !== false ) {
3163 $text = $this->getVariableValue( $id, $frame );
3164 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3165 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3171 # MSG, MSGNW and RAW
3174 $mwMsgnw = MagicWord
::get( 'msgnw' );
3175 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3178 # Remove obsolete MSG:
3179 $mwMsg = MagicWord
::get( 'msg' );
3180 $mwMsg->matchStartAndRemove( $part1 );
3184 $mwRaw = MagicWord
::get( 'raw' );
3185 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3186 $forceRawInterwiki = true;
3189 wfProfileOut( __METHOD__
.'-modifiers' );
3193 wfProfileIn( __METHOD__
. '-pfunc' );
3195 $colonPos = strpos( $part1, ':' );
3196 if ( $colonPos !== false ) {
3197 # Case sensitive functions
3198 $function = substr( $part1, 0, $colonPos );
3199 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3200 $function = $this->mFunctionSynonyms
[1][$function];
3202 # Case insensitive functions
3203 $function = $wgContLang->lc( $function );
3204 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3205 $function = $this->mFunctionSynonyms
[0][$function];
3211 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3212 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3213 $initialArgs = array( &$this );
3214 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3215 if ( $flags & SFH_OBJECT_ARGS
) {
3216 # Add a frame parameter, and pass the arguments as an array
3217 $allArgs = $initialArgs;
3218 $allArgs[] = $frame;
3219 for ( $i = 0; $i < $args->getLength(); $i++
) {
3220 $funcArgs[] = $args->item( $i );
3222 $allArgs[] = $funcArgs;
3224 # Convert arguments to plain text
3225 for ( $i = 0; $i < $args->getLength(); $i++
) {
3226 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3228 $allArgs = array_merge( $initialArgs, $funcArgs );
3231 # Workaround for PHP bug 35229 and similar
3232 if ( !is_callable( $callback ) ) {
3233 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3234 wfProfileOut( __METHOD__
. '-pfunc' );
3235 wfProfileOut( __METHOD__
);
3236 throw new MWException( "Tag hook for $function is not callable\n" );
3238 $result = call_user_func_array( $callback, $allArgs );
3241 $preprocessFlags = 0;
3243 if ( is_array( $result ) ) {
3244 if ( isset( $result[0] ) ) {
3246 unset( $result[0] );
3249 # Extract flags into the local scope
3250 # This allows callers to set flags such as nowiki, found, etc.
3256 $text = $this->preprocessToDom( $text, $preprocessFlags );
3259 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3262 wfProfileOut( __METHOD__
. '-pfunc' );
3265 # Finish mangling title and then check for loops.
3266 # Set $title to a Title object and $titleText to the PDBK
3269 # Split the title into page and subpage
3271 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3272 if ( $subpage !== '' ) {
3273 $ns = $this->mTitle
->getNamespace();
3275 $title = Title
::newFromText( $part1, $ns );
3277 $titleText = $title->getPrefixedText();
3278 # Check for language variants if the template is not found
3279 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3280 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3282 # Do recursion depth check
3283 $limit = $this->mOptions
->getMaxTemplateDepth();
3284 if ( $frame->depth
>= $limit ) {
3286 $text = '<span class="error">'
3287 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
3293 # Load from database
3294 if ( !$found && $title ) {
3295 if ( !Profiler
::instance()->isPersistent() ) {
3296 # Too many unique items can kill profiling DBs/collectors
3297 $titleProfileIn = __METHOD__
. "-title-" . $title->getDBKey();
3298 wfProfileIn( $titleProfileIn ); // template in
3300 wfProfileIn( __METHOD__
. '-loadtpl' );
3301 if ( !$title->isExternal() ) {
3302 if ( $title->isSpecialPage()
3303 && $this->mOptions
->getAllowSpecialInclusion()
3304 && $this->ot
['html'] )
3306 // Pass the template arguments as URL parameters.
3307 // "uselang" will have no effect since the Language object
3308 // is forced to the one defined in ParserOptions.
3309 $pageArgs = array();
3310 for ( $i = 0; $i < $args->getLength(); $i++
) {
3311 $bits = $args->item( $i )->splitArg();
3312 if ( strval( $bits['index'] ) === '' ) {
3313 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3314 $value = trim( $frame->expand( $bits['value'] ) );
3315 $pageArgs[$name] = $value;
3319 // Create a new context to execute the special page
3320 $context = new RequestContext
;
3321 $context->setTitle( $title );
3322 $context->setRequest( new FauxRequest( $pageArgs ) );
3323 $context->setUser( $this->getUser() );
3324 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3325 $ret = SpecialPageFactory
::capturePath( $title, $context );
3327 $text = $context->getOutput()->getHTML();
3328 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3331 $this->disableCache();
3333 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3334 $found = false; # access denied
3335 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3337 list( $text, $title ) = $this->getTemplateDom( $title );
3338 if ( $text !== false ) {
3344 # If the title is valid but undisplayable, make a link to it
3345 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3346 $text = "[[:$titleText]]";
3349 } elseif ( $title->isTrans() ) {
3350 # Interwiki transclusion
3351 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3352 $text = $this->interwikiTransclude( $title, 'render' );
3355 $text = $this->interwikiTransclude( $title, 'raw' );
3356 # Preprocess it like a template
3357 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3363 # Do infinite loop check
3364 # This has to be done after redirect resolution to avoid infinite loops via redirects
3365 if ( !$frame->loopCheck( $title ) ) {
3367 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3368 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3370 wfProfileOut( __METHOD__
. '-loadtpl' );
3373 # If we haven't found text to substitute by now, we're done
3374 # Recover the source wikitext and return it
3376 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3377 if ( $titleProfileIn ) {
3378 wfProfileOut( $titleProfileIn ); // template out
3380 wfProfileOut( __METHOD__
);
3381 return array( 'object' => $text );
3384 # Expand DOM-style return values in a child frame
3385 if ( $isChildObj ) {
3386 # Clean up argument array
3387 $newFrame = $frame->newChild( $args, $title );
3390 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3391 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3392 # Expansion is eligible for the empty-frame cache
3393 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3394 $text = $this->mTplExpandCache
[$titleText];
3396 $text = $newFrame->expand( $text );
3397 $this->mTplExpandCache
[$titleText] = $text;
3400 # Uncached expansion
3401 $text = $newFrame->expand( $text );
3404 if ( $isLocalObj && $nowiki ) {
3405 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3406 $isLocalObj = false;
3409 if ( $titleProfileIn ) {
3410 wfProfileOut( $titleProfileIn ); // template out
3413 # Replace raw HTML by a placeholder
3415 $text = $this->insertStripItem( $text );
3416 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3417 # Escape nowiki-style return values
3418 $text = wfEscapeWikiText( $text );
3419 } elseif ( is_string( $text )
3420 && !$piece['lineStart']
3421 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3423 # Bug 529: if the template begins with a table or block-level
3424 # element, it should be treated as beginning a new line.
3425 # This behaviour is somewhat controversial.
3426 $text = "\n" . $text;
3429 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3430 # Error, oversize inclusion
3431 if ( $titleText !== false ) {
3432 # Make a working, properly escaped link if possible (bug 23588)
3433 $text = "[[:$titleText]]";
3435 # This will probably not be a working link, but at least it may
3436 # provide some hint of where the problem is
3437 preg_replace( '/^:/', '', $originalTitle );
3438 $text = "[[:$originalTitle]]";
3440 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3441 $this->limitationWarn( 'post-expand-template-inclusion' );
3444 if ( $isLocalObj ) {
3445 $ret = array( 'object' => $text );
3447 $ret = array( 'text' => $text );
3450 wfProfileOut( __METHOD__
);
3455 * Get the semi-parsed DOM representation of a template with a given title,
3456 * and its redirect destination title. Cached.
3458 * @param $title Title
3462 function getTemplateDom( $title ) {
3463 $cacheTitle = $title;
3464 $titleText = $title->getPrefixedDBkey();
3466 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3467 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3468 $title = Title
::makeTitle( $ns, $dbk );
3469 $titleText = $title->getPrefixedDBkey();
3471 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3472 return array( $this->mTplDomCache
[$titleText], $title );
3475 # Cache miss, go to the database
3476 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3478 if ( $text === false ) {
3479 $this->mTplDomCache
[$titleText] = false;
3480 return array( false, $title );
3483 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3484 $this->mTplDomCache
[ $titleText ] = $dom;
3486 if ( !$title->equals( $cacheTitle ) ) {
3487 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3488 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3491 return array( $dom, $title );
3495 * Fetch the unparsed text of a template and register a reference to it.
3496 * @param Title $title
3497 * @return Array ( string or false, Title )
3499 function fetchTemplateAndTitle( $title ) {
3500 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3501 $stuff = call_user_func( $templateCb, $title, $this );
3502 $text = $stuff['text'];
3503 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3504 if ( isset( $stuff['deps'] ) ) {
3505 foreach ( $stuff['deps'] as $dep ) {
3506 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3509 return array( $text, $finalTitle );
3513 * Fetch the unparsed text of a template and register a reference to it.
3514 * @param Title $title
3515 * @return mixed string or false
3517 function fetchTemplate( $title ) {
3518 $rv = $this->fetchTemplateAndTitle( $title );
3523 * Static function to get a template
3524 * Can be overridden via ParserOptions::setTemplateCallback().
3526 * @param $title Title
3527 * @param $parser Parser
3531 static function statelessFetchTemplate( $title, $parser = false ) {
3532 $text = $skip = false;
3533 $finalTitle = $title;
3536 # Loop to fetch the article, with up to 1 redirect
3537 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3538 # Give extensions a chance to select the revision instead
3539 $id = false; # Assume current
3540 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3541 array( $parser, $title, &$skip, &$id ) );
3547 'page_id' => $title->getArticleID(),
3554 ? Revision
::newFromId( $id )
3555 : Revision
::newFromTitle( $title, 0, Revision
::READ_NORMAL
);
3556 $rev_id = $rev ?
$rev->getId() : 0;
3557 # If there is no current revision, there is no page
3558 if ( $id === false && !$rev ) {
3559 $linkCache = LinkCache
::singleton();
3560 $linkCache->addBadLinkObj( $title );
3565 'page_id' => $title->getArticleID(),
3566 'rev_id' => $rev_id );
3567 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3568 # We fetched a rev from a different title; register it too...
3570 'title' => $rev->getTitle(),
3571 'page_id' => $rev->getPage(),
3572 'rev_id' => $rev_id );
3576 $text = $rev->getText();
3577 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3579 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3580 if ( !$message->exists() ) {
3584 $text = $message->plain();
3588 if ( $text === false ) {
3592 $finalTitle = $title;
3593 $title = Title
::newFromRedirect( $text );
3597 'finalTitle' => $finalTitle,
3602 * Fetch a file and its title and register a reference to it.
3603 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3604 * @param Title $title
3605 * @param Array $options Array of options to RepoGroup::findFile
3608 function fetchFile( $title, $options = array() ) {
3609 $res = $this->fetchFileAndTitle( $title, $options );
3614 * Fetch a file and its title and register a reference to it.
3615 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3616 * @param Title $title
3617 * @param Array $options Array of options to RepoGroup::findFile
3618 * @return Array ( File or false, Title of file )
3620 function fetchFileAndTitle( $title, $options = array() ) {
3621 if ( isset( $options['broken'] ) ) {
3622 $file = false; // broken thumbnail forced by hook
3623 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3624 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3625 } else { // get by (name,timestamp)
3626 $file = wfFindFile( $title, $options );
3628 $time = $file ?
$file->getTimestamp() : false;
3629 $sha1 = $file ?
$file->getSha1() : false;
3630 # Register the file as a dependency...
3631 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3632 if ( $file && !$title->equals( $file->getTitle() ) ) {
3633 # Update fetched file title
3634 $title = $file->getTitle();
3635 if ( is_null( $file->getRedirectedTitle() ) ) {
3636 # This file was not a redirect, but the title does not match.
3637 # Register under the new name because otherwise the link will
3639 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3642 return array( $file, $title );
3646 * Transclude an interwiki link.
3648 * @param $title Title
3653 function interwikiTransclude( $title, $action ) {
3654 global $wgEnableScaryTranscluding;
3656 if ( !$wgEnableScaryTranscluding ) {
3657 return wfMsgForContent('scarytranscludedisabled');
3660 $url = $title->getFullUrl( "action=$action" );
3662 if ( strlen( $url ) > 255 ) {
3663 return wfMsgForContent( 'scarytranscludetoolong' );
3665 return $this->fetchScaryTemplateMaybeFromCache( $url );
3669 * @param $url string
3670 * @return Mixed|String
3672 function fetchScaryTemplateMaybeFromCache( $url ) {
3673 global $wgTranscludeCacheExpiry;
3674 $dbr = wfGetDB( DB_SLAVE
);
3675 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3676 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3677 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3679 return $obj->tc_contents
;
3682 $text = Http
::get( $url );
3684 return wfMsgForContent( 'scarytranscludefailed', $url );
3687 $dbw = wfGetDB( DB_MASTER
);
3688 $dbw->replace( 'transcache', array('tc_url'), array(
3690 'tc_time' => $dbw->timestamp( time() ),
3691 'tc_contents' => $text)
3697 * Triple brace replacement -- used for template arguments
3700 * @param $piece array
3701 * @param $frame PPFrame
3705 function argSubstitution( $piece, $frame ) {
3706 wfProfileIn( __METHOD__
);
3709 $parts = $piece['parts'];
3710 $nameWithSpaces = $frame->expand( $piece['title'] );
3711 $argName = trim( $nameWithSpaces );
3713 $text = $frame->getArgument( $argName );
3714 if ( $text === false && $parts->getLength() > 0
3718 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3721 # No match in frame, use the supplied default
3722 $object = $parts->item( 0 )->getChildren();
3724 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3725 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3726 $this->limitationWarn( 'post-expand-template-argument' );
3729 if ( $text === false && $object === false ) {
3731 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3733 if ( $error !== false ) {
3736 if ( $object !== false ) {
3737 $ret = array( 'object' => $object );
3739 $ret = array( 'text' => $text );
3742 wfProfileOut( __METHOD__
);
3747 * Return the text to be used for a given extension tag.
3748 * This is the ghost of strip().
3750 * @param $params array Associative array of parameters:
3751 * name PPNode for the tag name
3752 * attr PPNode for unparsed text where tag attributes are thought to be
3753 * attributes Optional associative array of parsed attributes
3754 * inner Contents of extension element
3755 * noClose Original text did not have a close tag
3756 * @param $frame PPFrame
3760 function extensionSubstitution( $params, $frame ) {
3761 $name = $frame->expand( $params['name'] );
3762 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3763 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3764 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3766 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3767 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3768 if ( $isFunctionTag ) {
3769 $markerType = 'none';
3771 $markerType = 'general';
3773 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3774 $name = strtolower( $name );
3775 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3776 if ( isset( $params['attributes'] ) ) {
3777 $attributes = $attributes +
$params['attributes'];
3780 if ( isset( $this->mTagHooks
[$name] ) ) {
3781 # Workaround for PHP bug 35229 and similar
3782 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3783 throw new MWException( "Tag hook for $name is not callable\n" );
3785 $output = call_user_func_array( $this->mTagHooks
[$name],
3786 array( $content, $attributes, $this, $frame ) );
3787 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3788 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3789 if ( !is_callable( $callback ) ) {
3790 throw new MWException( "Tag hook for $name is not callable\n" );
3793 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3795 $output = '<span class="error">Invalid tag extension name: ' .
3796 htmlspecialchars( $name ) . '</span>';
3799 if ( is_array( $output ) ) {
3800 # Extract flags to local scope (to override $markerType)
3802 $output = $flags[0];
3807 if ( is_null( $attrText ) ) {
3810 if ( isset( $params['attributes'] ) ) {
3811 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3812 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3813 htmlspecialchars( $attrValue ) . '"';
3816 if ( $content === null ) {
3817 $output = "<$name$attrText/>";
3819 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3820 $output = "<$name$attrText>$content$close";
3824 if ( $markerType === 'none' ) {
3826 } elseif ( $markerType === 'nowiki' ) {
3827 $this->mStripState
->addNoWiki( $marker, $output );
3828 } elseif ( $markerType === 'general' ) {
3829 $this->mStripState
->addGeneral( $marker, $output );
3831 throw new MWException( __METHOD__
.': invalid marker type' );
3837 * Increment an include size counter
3839 * @param $type String: the type of expansion
3840 * @param $size Integer: the size of the text
3841 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3843 function incrementIncludeSize( $type, $size ) {
3844 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3847 $this->mIncludeSizes
[$type] +
= $size;
3853 * Increment the expensive function count
3855 * @return Boolean: false if the limit has been exceeded
3857 function incrementExpensiveFunctionCount() {
3858 $this->mExpensiveFunctionCount++
;
3859 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
3863 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3864 * Fills $this->mDoubleUnderscores, returns the modified text
3866 * @param $text string
3870 function doDoubleUnderscore( $text ) {
3871 wfProfileIn( __METHOD__
);
3873 # The position of __TOC__ needs to be recorded
3874 $mw = MagicWord
::get( 'toc' );
3875 if ( $mw->match( $text ) ) {
3876 $this->mShowToc
= true;
3877 $this->mForceTocPosition
= true;
3879 # Set a placeholder. At the end we'll fill it in with the TOC.
3880 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3882 # Only keep the first one.
3883 $text = $mw->replace( '', $text );
3886 # Now match and remove the rest of them
3887 $mwa = MagicWord
::getDoubleUnderscoreArray();
3888 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3890 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3891 $this->mOutput
->mNoGallery
= true;
3893 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3894 $this->mShowToc
= false;
3896 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3897 $this->addTrackingCategory( 'hidden-category-category' );
3899 # (bug 8068) Allow control over whether robots index a page.
3901 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
3902 # is not desirable, the last one on the page should win.
3903 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3904 $this->mOutput
->setIndexPolicy( 'noindex' );
3905 $this->addTrackingCategory( 'noindex-category' );
3907 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3908 $this->mOutput
->setIndexPolicy( 'index' );
3909 $this->addTrackingCategory( 'index-category' );
3912 # Cache all double underscores in the database
3913 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
3914 $this->mOutput
->setProperty( $key, '' );
3917 wfProfileOut( __METHOD__
);
3922 * Add a tracking category, getting the title from a system message,
3923 * or print a debug message if the title is invalid.
3925 * @param $msg String: message key
3926 * @return Boolean: whether the addition was successful
3928 public function addTrackingCategory( $msg ) {
3929 if ( $this->mTitle
->getNamespace() === NS_SPECIAL
) {
3930 wfDebug( __METHOD__
.": Not adding tracking category $msg to special page!\n" );
3933 // Important to parse with correct title (bug 31469)
3934 $cat = wfMessage( $msg )
3935 ->title( $this->getTitle() )
3936 ->inContentLanguage()
3939 # Allow tracking categories to be disabled by setting them to "-"
3940 if ( $cat === '-' ) {
3944 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3945 if ( $containerCategory ) {
3946 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3949 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3955 * This function accomplishes several tasks:
3956 * 1) Auto-number headings if that option is enabled
3957 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3958 * 3) Add a Table of contents on the top for users who have enabled the option
3959 * 4) Auto-anchor headings
3961 * It loops through all headlines, collects the necessary data, then splits up the
3962 * string and re-inserts the newly formatted headlines.
3964 * @param $text String
3965 * @param $origText String: original, untouched wikitext
3966 * @param $isMain Boolean
3967 * @return mixed|string
3970 function formatHeadings( $text, $origText, $isMain=true ) {
3971 global $wgMaxTocLevel, $wgHtml5, $wgExperimentalHtmlIds;
3973 # Inhibit editsection links if requested in the page
3974 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3975 $maybeShowEditLink = $showEditLink = false;
3977 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
3978 $showEditLink = $this->mOptions
->getEditSection();
3980 if ( $showEditLink ) {
3981 $this->mOutput
->setEditSectionTokens( true );
3984 # Get all headlines for numbering them and adding funky stuff like [edit]
3985 # links - this is for later, but we need the number of headlines right now
3987 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3989 # if there are fewer than 4 headlines in the article, do not show TOC
3990 # unless it's been explicitly enabled.
3991 $enoughToc = $this->mShowToc
&&
3992 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
3994 # Allow user to stipulate that a page should have a "new section"
3995 # link added via __NEWSECTIONLINK__
3996 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3997 $this->mOutput
->setNewSection( true );
4000 # Allow user to remove the "new section"
4001 # link via __NONEWSECTIONLINK__
4002 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4003 $this->mOutput
->hideNewSection( true );
4006 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4007 # override above conditions and always show TOC above first header
4008 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4009 $this->mShowToc
= true;
4017 # Ugh .. the TOC should have neat indentation levels which can be
4018 # passed to the skin functions. These are determined here
4022 $sublevelCount = array();
4023 $levelCount = array();
4028 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4029 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4030 $oldType = $this->mOutputType
;
4031 $this->setOutputType( self
::OT_WIKI
);
4032 $frame = $this->getPreprocessor()->newFrame();
4033 $root = $this->preprocessToDom( $origText );
4034 $node = $root->getFirstChild();
4039 foreach ( $matches[3] as $headline ) {
4040 $isTemplate = false;
4042 $sectionIndex = false;
4044 $markerMatches = array();
4045 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
4046 $serial = $markerMatches[1];
4047 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4048 $isTemplate = ( $titleText != $baseTitleText );
4049 $headline = preg_replace( "/^$markerRegex/", "", $headline );
4053 $prevlevel = $level;
4055 $level = $matches[1][$headlineCount];
4057 if ( $level > $prevlevel ) {
4058 # Increase TOC level
4060 $sublevelCount[$toclevel] = 0;
4061 if ( $toclevel<$wgMaxTocLevel ) {
4062 $prevtoclevel = $toclevel;
4063 $toc .= Linker
::tocIndent();
4066 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4067 # Decrease TOC level, find level to jump to
4069 for ( $i = $toclevel; $i > 0; $i-- ) {
4070 if ( $levelCount[$i] == $level ) {
4071 # Found last matching level
4074 } elseif ( $levelCount[$i] < $level ) {
4075 # Found first matching level below current level
4083 if ( $toclevel<$wgMaxTocLevel ) {
4084 if ( $prevtoclevel < $wgMaxTocLevel ) {
4085 # Unindent only if the previous toc level was shown :p
4086 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4087 $prevtoclevel = $toclevel;
4089 $toc .= Linker
::tocLineEnd();
4093 # No change in level, end TOC line
4094 if ( $toclevel<$wgMaxTocLevel ) {
4095 $toc .= Linker
::tocLineEnd();
4099 $levelCount[$toclevel] = $level;
4101 # count number of headlines for each level
4102 @$sublevelCount[$toclevel]++
;
4104 for( $i = 1; $i <= $toclevel; $i++
) {
4105 if ( !empty( $sublevelCount[$i] ) ) {
4109 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4114 # The safe header is a version of the header text safe to use for links
4116 # Remove link placeholders by the link text.
4117 # <!--LINK number-->
4119 # link text with suffix
4120 # Do this before unstrip since link text can contain strip markers
4121 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4123 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4124 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4126 # Strip out HTML (first regex removes any tag not allowed)
4127 # Allowed tags are <sup> and <sub> (bug 8393), <i> (bug 26375) and <b> (r105284)
4128 # We strip any parameter from accepted tags (second regex)
4129 $tocline = preg_replace(
4130 array( '#<(?!/?(sup|sub|i|b)(?: [^>]*)?>).*?'.'>#', '#<(/?(sup|sub|i|b))(?: .*?)?'.'>#' ),
4131 array( '', '<$1>' ),
4134 $tocline = trim( $tocline );
4136 # For the anchor, strip out HTML-y stuff period
4137 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
4138 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4140 # Save headline for section edit hint before it's escaped
4141 $headlineHint = $safeHeadline;
4143 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
4144 # For reverse compatibility, provide an id that's
4145 # HTML4-compatible, like we used to.
4147 # It may be worth noting, academically, that it's possible for
4148 # the legacy anchor to conflict with a non-legacy headline
4149 # anchor on the page. In this case likely the "correct" thing
4150 # would be to either drop the legacy anchors or make sure
4151 # they're numbered first. However, this would require people
4152 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4153 # manually, so let's not bother worrying about it.
4154 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4155 array( 'noninitial', 'legacy' ) );
4156 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4158 if ( $legacyHeadline == $safeHeadline ) {
4159 # No reason to have both (in fact, we can't)
4160 $legacyHeadline = false;
4163 $legacyHeadline = false;
4164 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4168 # HTML names must be case-insensitively unique (bug 10721).
4169 # This does not apply to Unicode characters per
4170 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4171 # @todo FIXME: We may be changing them depending on the current locale.
4172 $arrayKey = strtolower( $safeHeadline );
4173 if ( $legacyHeadline === false ) {
4174 $legacyArrayKey = false;
4176 $legacyArrayKey = strtolower( $legacyHeadline );
4179 # count how many in assoc. array so we can track dupes in anchors
4180 if ( isset( $refers[$arrayKey] ) ) {
4181 $refers[$arrayKey]++
;
4183 $refers[$arrayKey] = 1;
4185 if ( isset( $refers[$legacyArrayKey] ) ) {
4186 $refers[$legacyArrayKey]++
;
4188 $refers[$legacyArrayKey] = 1;
4191 # Don't number the heading if it is the only one (looks silly)
4192 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4193 # the two are different if the line contains a link
4194 $headline = Html
::element( 'span', array( 'class' => 'mw-headline-number' ), $numbering ) . ' ' . $headline;
4197 # Create the anchor for linking from the TOC to the section
4198 $anchor = $safeHeadline;
4199 $legacyAnchor = $legacyHeadline;
4200 if ( $refers[$arrayKey] > 1 ) {
4201 $anchor .= '_' . $refers[$arrayKey];
4203 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4204 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4206 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4207 $toc .= Linker
::tocLine( $anchor, $tocline,
4208 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4211 # Add the section to the section tree
4212 # Find the DOM node for this header
4213 while ( $node && !$isTemplate ) {
4214 if ( $node->getName() === 'h' ) {
4215 $bits = $node->splitHeading();
4216 if ( $bits['i'] == $sectionIndex ) {
4220 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4221 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4222 $node = $node->getNextSibling();
4225 'toclevel' => $toclevel,
4228 'number' => $numbering,
4229 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4230 'fromtitle' => $titleText,
4231 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
4232 'anchor' => $anchor,
4235 # give headline the correct <h#> tag
4236 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4237 // Output edit section links as markers with styles that can be customized by skins
4238 if ( $isTemplate ) {
4239 # Put a T flag in the section identifier, to indicate to extractSections()
4240 # that sections inside <includeonly> should be counted.
4241 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4243 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
4245 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4246 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4247 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4248 // so we don't have to worry about a user trying to input one of these markers directly.
4249 // We use a page and section attribute to stop the language converter from converting these important bits
4250 // of data, but put the headline hint inside a content block because the language converter is supposed to
4251 // be able to convert that piece of data.
4252 $editlink = '<mw:editsection page="' . htmlspecialchars($editlinkArgs[0]);
4253 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"';
4254 if ( isset($editlinkArgs[2]) ) {
4255 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4262 $head[$headlineCount] = Linker
::makeHeadline( $level,
4263 $matches['attrib'][$headlineCount], $anchor, $headline,
4264 $editlink, $legacyAnchor );
4269 $this->setOutputType( $oldType );
4271 # Never ever show TOC if no headers
4272 if ( $numVisible < 1 ) {
4277 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4278 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4280 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4281 $this->mOutput
->setTOCHTML( $toc );
4285 $this->mOutput
->setSections( $tocraw );
4288 # split up and insert constructed headlines
4289 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4292 // build an array of document sections
4293 $sections = array();
4294 foreach ( $blocks as $block ) {
4295 // $head is zero-based, sections aren't.
4296 if ( empty( $head[$i - 1] ) ) {
4297 $sections[$i] = $block;
4299 $sections[$i] = $head[$i - 1] . $block;
4303 * Send a hook, one per section.
4304 * The idea here is to be able to make section-level DIVs, but to do so in a
4305 * lower-impact, more correct way than r50769
4308 * $section : the section number
4309 * &$sectionContent : ref to the content of the section
4310 * $showEditLinks : boolean describing whether this section has an edit link
4312 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4317 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4318 // append the TOC at the beginning
4319 // Top anchor now in skin
4320 $sections[0] = $sections[0] . $toc . "\n";
4323 $full .= join( '', $sections );
4325 if ( $this->mForceTocPosition
) {
4326 return str_replace( '<!--MWTOC-->', $toc, $full );
4333 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4334 * conversion, substitting signatures, {{subst:}} templates, etc.
4336 * @param $text String: the text to transform
4337 * @param $title Title: the Title object for the current article
4338 * @param $user User: the User object describing the current user
4339 * @param $options ParserOptions: parsing options
4340 * @param $clearState Boolean: whether to clear the parser state first
4341 * @return String: the altered wiki markup
4343 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4344 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4345 $this->setUser( $user );
4350 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4351 if( $options->getPreSaveTransform() ) {
4352 $text = $this->pstPass2( $text, $user );
4354 $text = $this->mStripState
->unstripBoth( $text );
4356 $this->setUser( null ); #Reset
4362 * Pre-save transform helper function
4365 * @param $text string
4370 function pstPass2( $text, $user ) {
4371 global $wgContLang, $wgLocaltimezone;
4373 # Note: This is the timestamp saved as hardcoded wikitext to
4374 # the database, we use $wgContLang here in order to give
4375 # everyone the same signature and use the default one rather
4376 # than the one selected in each user's preferences.
4377 # (see also bug 12815)
4378 $ts = $this->mOptions
->getTimestamp();
4379 if ( isset( $wgLocaltimezone ) ) {
4380 $tz = $wgLocaltimezone;
4382 $tz = date_default_timezone_get();
4385 $unixts = wfTimestamp( TS_UNIX
, $ts );
4386 $oldtz = date_default_timezone_get();
4387 date_default_timezone_set( $tz );
4388 $ts = date( 'YmdHis', $unixts );
4389 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4391 # Allow translation of timezones through wiki. date() can return
4392 # whatever crap the system uses, localised or not, so we cannot
4393 # ship premade translations.
4394 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4395 $msg = wfMessage( $key )->inContentLanguage();
4396 if ( $msg->exists() ) {
4397 $tzMsg = $msg->text();
4400 date_default_timezone_set( $oldtz );
4402 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4404 # Variable replacement
4405 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4406 $text = $this->replaceVariables( $text );
4408 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4409 # which may corrupt this parser instance via its wfMsgExt( parsemag ) call-
4412 $sigText = $this->getUserSig( $user );
4413 $text = strtr( $text, array(
4415 '~~~~' => "$sigText $d",
4419 # Context links: [[|name]] and [[name (context)|]]
4420 $tc = '[' . Title
::legalChars() . ']';
4421 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4423 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4424 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]]
4425 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/"; # [[ns:page (context), context|]]
4426 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4428 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4429 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4430 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4431 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4433 $t = $this->mTitle
->getText();
4435 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4436 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4437 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4438 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4440 # if there's no context, don't bother duplicating the title
4441 $text = preg_replace( $p2, '[[\\1]]', $text );
4444 # Trim trailing whitespace
4445 $text = rtrim( $text );
4451 * Fetch the user's signature text, if any, and normalize to
4452 * validated, ready-to-insert wikitext.
4453 * If you have pre-fetched the nickname or the fancySig option, you can
4454 * specify them here to save a database query.
4455 * Do not reuse this parser instance after calling getUserSig(),
4456 * as it may have changed if it's the $wgParser.
4459 * @param $nickname String|bool nickname to use or false to use user's default nickname
4460 * @param $fancySig Boolean|null whether the nicknname is the complete signature
4461 * or null to use default value
4464 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4465 global $wgMaxSigChars;
4467 $username = $user->getName();
4469 # If not given, retrieve from the user object.
4470 if ( $nickname === false )
4471 $nickname = $user->getOption( 'nickname' );
4473 if ( is_null( $fancySig ) ) {
4474 $fancySig = $user->getBoolOption( 'fancysig' );
4477 $nickname = $nickname == null ?
$username : $nickname;
4479 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4480 $nickname = $username;
4481 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4482 } elseif ( $fancySig !== false ) {
4483 # Sig. might contain markup; validate this
4484 if ( $this->validateSig( $nickname ) !== false ) {
4485 # Validated; clean up (if needed) and return it
4486 return $this->cleanSig( $nickname, true );
4488 # Failed to validate; fall back to the default
4489 $nickname = $username;
4490 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4494 # Make sure nickname doesnt get a sig in a sig
4495 $nickname = self
::cleanSigInSig( $nickname );
4497 # If we're still here, make it a link to the user page
4498 $userText = wfEscapeWikiText( $username );
4499 $nickText = wfEscapeWikiText( $nickname );
4500 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4502 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4506 * Check that the user's signature contains no bad XML
4508 * @param $text String
4509 * @return mixed An expanded string, or false if invalid.
4511 function validateSig( $text ) {
4512 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4516 * Clean up signature text
4518 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4519 * 2) Substitute all transclusions
4521 * @param $text String
4522 * @param $parsing bool Whether we're cleaning (preferences save) or parsing
4523 * @return String: signature text
4525 public function cleanSig( $text, $parsing = false ) {
4528 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4531 # Option to disable this feature
4532 if ( !$this->mOptions
->getCleanSignatures() ) {
4536 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4537 # => Move this logic to braceSubstitution()
4538 $substWord = MagicWord
::get( 'subst' );
4539 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4540 $substText = '{{' . $substWord->getSynonym( 0 );
4542 $text = preg_replace( $substRegex, $substText, $text );
4543 $text = self
::cleanSigInSig( $text );
4544 $dom = $this->preprocessToDom( $text );
4545 $frame = $this->getPreprocessor()->newFrame();
4546 $text = $frame->expand( $dom );
4549 $text = $this->mStripState
->unstripBoth( $text );
4556 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4558 * @param $text String
4559 * @return String: signature text with /~{3,5}/ removed
4561 public static function cleanSigInSig( $text ) {
4562 $text = preg_replace( '/~{3,5}/', '', $text );
4567 * Set up some variables which are usually set up in parse()
4568 * so that an external function can call some class members with confidence
4570 * @param $title Title|null
4571 * @param $options ParserOptions
4572 * @param $outputType
4573 * @param $clearState bool
4575 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4576 $this->startParse( $title, $options, $outputType, $clearState );
4580 * @param $title Title|null
4581 * @param $options ParserOptions
4582 * @param $outputType
4583 * @param $clearState bool
4585 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4586 $this->setTitle( $title );
4587 $this->mOptions
= $options;
4588 $this->setOutputType( $outputType );
4589 if ( $clearState ) {
4590 $this->clearState();
4595 * Wrapper for preprocess()
4597 * @param $text String: the text to preprocess
4598 * @param $options ParserOptions: options
4599 * @param $title Title object or null to use $wgTitle
4602 public function transformMsg( $text, $options, $title = null ) {
4603 static $executing = false;
4605 # Guard against infinite recursion
4611 wfProfileIn( __METHOD__
);
4617 # It's not uncommon having a null $wgTitle in scripts. See r80898
4618 # Create a ghost title in such case
4619 $title = Title
::newFromText( 'Dwimmerlaik' );
4621 $text = $this->preprocess( $text, $title, $options );
4624 wfProfileOut( __METHOD__
);
4629 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4630 * The callback should have the following form:
4631 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4633 * Transform and return $text. Use $parser for any required context, e.g. use
4634 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4636 * Hooks may return extended information by returning an array, of which the
4637 * first numbered element (index 0) must be the return string, and all other
4638 * entries are extracted into local variables within an internal function
4639 * in the Parser class.
4641 * This interface (introduced r61913) appears to be undocumented, but
4642 * 'markerName' is used by some core tag hooks to override which strip
4643 * array their results are placed in. **Use great caution if attempting
4644 * this interface, as it is not documented and injudicious use could smash
4645 * private variables.**
4647 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4648 * @param $callback Mixed: the callback function (and object) to use for the tag
4649 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4651 public function setHook( $tag, $callback ) {
4652 $tag = strtolower( $tag );
4653 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4654 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4656 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4657 $this->mTagHooks
[$tag] = $callback;
4658 if ( !in_array( $tag, $this->mStripList
) ) {
4659 $this->mStripList
[] = $tag;
4666 * As setHook(), but letting the contents be parsed.
4668 * Transparent tag hooks are like regular XML-style tag hooks, except they
4669 * operate late in the transformation sequence, on HTML instead of wikitext.
4671 * This is probably obsoleted by things dealing with parser frames?
4672 * The only extension currently using it is geoserver.
4675 * @todo better document or deprecate this
4677 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4678 * @param $callback Mixed: the callback function (and object) to use for the tag
4679 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4681 function setTransparentTagHook( $tag, $callback ) {
4682 $tag = strtolower( $tag );
4683 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4684 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4686 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4687 $this->mTransparentTagHooks
[$tag] = $callback;
4693 * Remove all tag hooks
4695 function clearTagHooks() {
4696 $this->mTagHooks
= array();
4697 $this->mFunctionTagHooks
= array();
4698 $this->mStripList
= $this->mDefaultStripList
;
4702 * Create a function, e.g. {{sum:1|2|3}}
4703 * The callback function should have the form:
4704 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4706 * Or with SFH_OBJECT_ARGS:
4707 * function myParserFunction( $parser, $frame, $args ) { ... }
4709 * The callback may either return the text result of the function, or an array with the text
4710 * in element 0, and a number of flags in the other elements. The names of the flags are
4711 * specified in the keys. Valid flags are:
4712 * found The text returned is valid, stop processing the template. This
4714 * nowiki Wiki markup in the return value should be escaped
4715 * isHTML The returned text is HTML, armour it against wikitext transformation
4717 * @param $id String: The magic word ID
4718 * @param $callback Mixed: the callback function (and object) to use
4719 * @param $flags Integer: a combination of the following flags:
4720 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4722 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4723 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4724 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4725 * the arguments, and to control the way they are expanded.
4727 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4728 * arguments, for instance:
4729 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4731 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4732 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4733 * working if/when this is changed.
4735 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4738 * Please read the documentation in includes/parser/Preprocessor.php for more information
4739 * about the methods available in PPFrame and PPNode.
4741 * @return string|callback The old callback function for this name, if any
4743 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4746 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4747 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4749 # Add to function cache
4750 $mw = MagicWord
::get( $id );
4752 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4754 $synonyms = $mw->getSynonyms();
4755 $sensitive = intval( $mw->isCaseSensitive() );
4757 foreach ( $synonyms as $syn ) {
4759 if ( !$sensitive ) {
4760 $syn = $wgContLang->lc( $syn );
4763 if ( !( $flags & SFH_NO_HASH
) ) {
4766 # Remove trailing colon
4767 if ( substr( $syn, -1, 1 ) === ':' ) {
4768 $syn = substr( $syn, 0, -1 );
4770 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4776 * Get all registered function hook identifiers
4780 function getFunctionHooks() {
4781 return array_keys( $this->mFunctionHooks
);
4785 * Create a tag function, e.g. "<test>some stuff</test>".
4786 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4787 * Unlike parser functions, their content is not preprocessed.
4790 function setFunctionTagHook( $tag, $callback, $flags ) {
4791 $tag = strtolower( $tag );
4792 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4793 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4794 $this->mFunctionTagHooks
[$tag] : null;
4795 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4797 if ( !in_array( $tag, $this->mStripList
) ) {
4798 $this->mStripList
[] = $tag;
4805 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
4806 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
4807 * Placeholders created in Skin::makeLinkObj()
4809 * @param $text string
4810 * @param $options int
4812 * @return array of link CSS classes, indexed by PDBK.
4814 function replaceLinkHolders( &$text, $options = 0 ) {
4815 return $this->mLinkHolders
->replace( $text );
4819 * Replace "<!--LINK-->" link placeholders with plain text of links
4820 * (not HTML-formatted).
4822 * @param $text String
4825 function replaceLinkHoldersText( $text ) {
4826 return $this->mLinkHolders
->replaceText( $text );
4830 * Renders an image gallery from a text with one line per image.
4831 * text labels may be given by using |-style alternative text. E.g.
4832 * Image:one.jpg|The number "1"
4833 * Image:tree.jpg|A tree
4834 * given as text will return the HTML of a gallery with two images,
4835 * labeled 'The number "1"' and
4838 * @param string $text
4839 * @param array $params
4840 * @return string HTML
4842 function renderImageGallery( $text, $params ) {
4843 $ig = new ImageGallery();
4844 $ig->setContextTitle( $this->mTitle
);
4845 $ig->setShowBytes( false );
4846 $ig->setShowFilename( false );
4847 $ig->setParser( $this );
4848 $ig->setHideBadImages();
4849 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4851 if ( isset( $params['showfilename'] ) ) {
4852 $ig->setShowFilename( true );
4854 $ig->setShowFilename( false );
4856 if ( isset( $params['caption'] ) ) {
4857 $caption = $params['caption'];
4858 $caption = htmlspecialchars( $caption );
4859 $caption = $this->replaceInternalLinks( $caption );
4860 $ig->setCaptionHtml( $caption );
4862 if ( isset( $params['perrow'] ) ) {
4863 $ig->setPerRow( $params['perrow'] );
4865 if ( isset( $params['widths'] ) ) {
4866 $ig->setWidths( $params['widths'] );
4868 if ( isset( $params['heights'] ) ) {
4869 $ig->setHeights( $params['heights'] );
4872 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4874 $lines = StringUtils
::explode( "\n", $text );
4875 foreach ( $lines as $line ) {
4876 # match lines like these:
4877 # Image:someimage.jpg|This is some image
4879 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4881 if ( count( $matches ) == 0 ) {
4885 if ( strpos( $matches[0], '%' ) !== false ) {
4886 $matches[1] = rawurldecode( $matches[1] );
4888 $title = Title
::newFromText( $matches[1], NS_FILE
);
4889 if ( is_null( $title ) ) {
4890 # Bogus title. Ignore these so we don't bomb out later.
4897 if ( isset( $matches[3] ) ) {
4898 // look for an |alt= definition while trying not to break existing
4899 // captions with multiple pipes (|) in it, until a more sensible grammar
4900 // is defined for images in galleries
4902 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
4903 $parameterMatches = StringUtils
::explode('|', $matches[3]);
4904 $magicWordAlt = MagicWord
::get( 'img_alt' );
4905 $magicWordLink = MagicWord
::get( 'img_link' );
4907 foreach ( $parameterMatches as $parameterMatch ) {
4908 if ( $match = $magicWordAlt->matchVariableStartToEnd( $parameterMatch ) ) {
4909 $alt = $this->stripAltText( $match, false );
4911 elseif( $match = $magicWordLink->matchVariableStartToEnd( $parameterMatch ) ){
4912 $link = strip_tags($this->replaceLinkHoldersText($match));
4913 $chars = self
::EXT_LINK_URL_CLASS
;
4914 $prots = $this->mUrlProtocols
;
4915 //check to see if link matches an absolute url, if not then it must be a wiki link.
4916 if(!preg_match( "/^($prots)$chars+$/u", $link)){
4917 $localLinkTitle = Title
::newFromText($link);
4918 $link = $localLinkTitle->getLocalURL();
4922 // concatenate all other pipes
4923 $label .= '|' . $parameterMatch;
4926 // remove the first pipe
4927 $label = substr( $label, 1 );
4930 $ig->add( $title, $label, $alt ,$link);
4932 return $ig->toHTML();
4939 function getImageParams( $handler ) {
4941 $handlerClass = get_class( $handler );
4945 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4946 # Initialise static lists
4947 static $internalParamNames = array(
4948 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4949 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4950 'bottom', 'text-bottom' ),
4951 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4952 'upright', 'border', 'link', 'alt' ),
4954 static $internalParamMap;
4955 if ( !$internalParamMap ) {
4956 $internalParamMap = array();
4957 foreach ( $internalParamNames as $type => $names ) {
4958 foreach ( $names as $name ) {
4959 $magicName = str_replace( '-', '_', "img_$name" );
4960 $internalParamMap[$magicName] = array( $type, $name );
4965 # Add handler params
4966 $paramMap = $internalParamMap;
4968 $handlerParamMap = $handler->getParamMap();
4969 foreach ( $handlerParamMap as $magic => $paramName ) {
4970 $paramMap[$magic] = array( 'handler', $paramName );
4973 $this->mImageParams
[$handlerClass] = $paramMap;
4974 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4976 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4980 * Parse image options text and use it to make an image
4982 * @param $title Title
4983 * @param $options String
4984 * @param $holders LinkHolderArray|bool
4985 * @return string HTML
4987 function makeImage( $title, $options, $holders = false ) {
4988 # Check if the options text is of the form "options|alt text"
4990 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4991 # * left no resizing, just left align. label is used for alt= only
4992 # * right same, but right aligned
4993 # * none same, but not aligned
4994 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4995 # * center center the image
4996 # * frame Keep original image size, no magnify-button.
4997 # * framed Same as "frame"
4998 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4999 # * upright reduce width for upright images, rounded to full __0 px
5000 # * border draw a 1px border around the image
5001 # * alt Text for HTML alt attribute (defaults to empty)
5002 # * link Set the target of the image link. Can be external, interwiki, or local
5003 # vertical-align values (no % or length right now):
5013 $parts = StringUtils
::explode( "|", $options );
5015 # Give extensions a chance to select the file revision for us
5018 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5019 array( $this, $title, &$options, &$descQuery ) );
5020 # Fetch and register the file (file title may be different via hooks)
5021 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5024 $handler = $file ?
$file->getHandler() : false;
5026 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5029 $this->addTrackingCategory( 'broken-file-category' );
5032 # Process the input parameters
5034 $params = array( 'frame' => array(), 'handler' => array(),
5035 'horizAlign' => array(), 'vertAlign' => array() );
5036 foreach ( $parts as $part ) {
5037 $part = trim( $part );
5038 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5040 if ( isset( $paramMap[$magicName] ) ) {
5041 list( $type, $paramName ) = $paramMap[$magicName];
5043 # Special case; width and height come in one variable together
5044 if ( $type === 'handler' && $paramName === 'width' ) {
5045 $parsedWidthParam = $this->parseWidthParam( $value );
5046 if( isset( $parsedWidthParam['width'] ) ) {
5047 $width = $parsedWidthParam['width'];
5048 if ( $handler->validateParam( 'width', $width ) ) {
5049 $params[$type]['width'] = $width;
5053 if( isset( $parsedWidthParam['height'] ) ) {
5054 $height = $parsedWidthParam['height'];
5055 if ( $handler->validateParam( 'height', $height ) ) {
5056 $params[$type]['height'] = $height;
5060 # else no validation -- bug 13436
5062 if ( $type === 'handler' ) {
5063 # Validate handler parameter
5064 $validated = $handler->validateParam( $paramName, $value );
5066 # Validate internal parameters
5067 switch( $paramName ) {
5070 # @todo FIXME: Possibly check validity here for
5071 # manualthumb? downstream behavior seems odd with
5072 # missing manual thumbs.
5074 $value = $this->stripAltText( $value, $holders );
5077 $chars = self
::EXT_LINK_URL_CLASS
;
5078 $prots = $this->mUrlProtocols
;
5079 if ( $value === '' ) {
5080 $paramName = 'no-link';
5083 } elseif ( preg_match( "/^$prots/", $value ) ) {
5084 if ( preg_match( "/^($prots)$chars+$/u", $value, $m ) ) {
5085 $paramName = 'link-url';
5086 $this->mOutput
->addExternalLink( $value );
5087 if ( $this->mOptions
->getExternalLinkTarget() ) {
5088 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5093 $linkTitle = Title
::newFromText( $value );
5095 $paramName = 'link-title';
5096 $value = $linkTitle;
5097 $this->mOutput
->addLink( $linkTitle );
5103 # Most other things appear to be empty or numeric...
5104 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5109 $params[$type][$paramName] = $value;
5113 if ( !$validated ) {
5118 # Process alignment parameters
5119 if ( $params['horizAlign'] ) {
5120 $params['frame']['align'] = key( $params['horizAlign'] );
5122 if ( $params['vertAlign'] ) {
5123 $params['frame']['valign'] = key( $params['vertAlign'] );
5126 $params['frame']['caption'] = $caption;
5128 # Will the image be presented in a frame, with the caption below?
5129 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5130 isset( $params['frame']['framed'] ) ||
5131 isset( $params['frame']['thumbnail'] ) ||
5132 isset( $params['frame']['manualthumb'] );
5134 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5135 # came to also set the caption, ordinary text after the image -- which
5136 # makes no sense, because that just repeats the text multiple times in
5137 # screen readers. It *also* came to set the title attribute.
5139 # Now that we have an alt attribute, we should not set the alt text to
5140 # equal the caption: that's worse than useless, it just repeats the
5141 # text. This is the framed/thumbnail case. If there's no caption, we
5142 # use the unnamed parameter for alt text as well, just for the time be-
5143 # ing, if the unnamed param is set and the alt param is not.
5145 # For the future, we need to figure out if we want to tweak this more,
5146 # e.g., introducing a title= parameter for the title; ignoring the un-
5147 # named parameter entirely for images without a caption; adding an ex-
5148 # plicit caption= parameter and preserving the old magic unnamed para-
5150 if ( $imageIsFramed ) { # Framed image
5151 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5152 # No caption or alt text, add the filename as the alt text so
5153 # that screen readers at least get some description of the image
5154 $params['frame']['alt'] = $title->getText();
5156 # Do not set $params['frame']['title'] because tooltips don't make sense
5158 } else { # Inline image
5159 if ( !isset( $params['frame']['alt'] ) ) {
5160 # No alt text, use the "caption" for the alt text
5161 if ( $caption !== '') {
5162 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5164 # No caption, fall back to using the filename for the
5166 $params['frame']['alt'] = $title->getText();
5169 # Use the "caption" for the tooltip text
5170 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5173 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5175 # Linker does the rest
5176 $time = isset( $options['time'] ) ?
$options['time'] : false;
5177 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5178 $time, $descQuery, $this->mOptions
->getThumbSize() );
5180 # Give the handler a chance to modify the parser object
5182 $handler->parserTransformHook( $this, $file );
5190 * @param $holders LinkHolderArray
5191 * @return mixed|String
5193 protected function stripAltText( $caption, $holders ) {
5194 # Strip bad stuff out of the title (tooltip). We can't just use
5195 # replaceLinkHoldersText() here, because if this function is called
5196 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5198 $tooltip = $holders->replaceText( $caption );
5200 $tooltip = $this->replaceLinkHoldersText( $caption );
5203 # make sure there are no placeholders in thumbnail attributes
5204 # that are later expanded to html- so expand them now and
5206 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5207 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5213 * Set a flag in the output object indicating that the content is dynamic and
5214 * shouldn't be cached.
5216 function disableCache() {
5217 wfDebug( "Parser output marked as uncacheable.\n" );
5218 if ( !$this->mOutput
) {
5219 throw new MWException( __METHOD__
.
5220 " can only be called when actually parsing something" );
5222 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5223 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5227 * Callback from the Sanitizer for expanding items found in HTML attribute
5228 * values, so they can be safely tested and escaped.
5230 * @param $text String
5231 * @param $frame PPFrame
5234 function attributeStripCallback( &$text, $frame = false ) {
5235 $text = $this->replaceVariables( $text, $frame );
5236 $text = $this->mStripState
->unstripBoth( $text );
5245 function getTags() {
5246 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
), array_keys( $this->mFunctionTagHooks
) );
5250 * Replace transparent tags in $text with the values given by the callbacks.
5252 * Transparent tag hooks are like regular XML-style tag hooks, except they
5253 * operate late in the transformation sequence, on HTML instead of wikitext.
5255 * @param $text string
5259 function replaceTransparentTags( $text ) {
5261 $elements = array_keys( $this->mTransparentTagHooks
);
5262 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5263 $replacements = array();
5265 foreach ( $matches as $marker => $data ) {
5266 list( $element, $content, $params, $tag ) = $data;
5267 $tagName = strtolower( $element );
5268 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5269 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
5273 $replacements[$marker] = $output;
5275 return strtr( $text, $replacements );
5279 * Break wikitext input into sections, and either pull or replace
5280 * some particular section's text.
5282 * External callers should use the getSection and replaceSection methods.
5284 * @param $text String: Page wikitext
5285 * @param $section String: a section identifier string of the form:
5286 * "<flag1> - <flag2> - ... - <section number>"
5288 * Currently the only recognised flag is "T", which means the target section number
5289 * was derived during a template inclusion parse, in other words this is a template
5290 * section edit link. If no flags are given, it was an ordinary section edit link.
5291 * This flag is required to avoid a section numbering mismatch when a section is
5292 * enclosed by "<includeonly>" (bug 6563).
5294 * The section number 0 pulls the text before the first heading; other numbers will
5295 * pull the given section along with its lower-level subsections. If the section is
5296 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5298 * Section 0 is always considered to exist, even if it only contains the empty
5299 * string. If $text is the empty string and section 0 is replaced, $newText is
5302 * @param $mode String: one of "get" or "replace"
5303 * @param $newText String: replacement text for section data.
5304 * @return String: for "get", the extracted section text.
5305 * for "replace", the whole page with the section replaced.
5307 private function extractSections( $text, $section, $mode, $newText='' ) {
5308 global $wgTitle; # not generally used but removes an ugly failure mode
5309 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5311 $frame = $this->getPreprocessor()->newFrame();
5313 # Process section extraction flags
5315 $sectionParts = explode( '-', $section );
5316 $sectionIndex = array_pop( $sectionParts );
5317 foreach ( $sectionParts as $part ) {
5318 if ( $part === 'T' ) {
5319 $flags |
= self
::PTD_FOR_INCLUSION
;
5323 # Check for empty input
5324 if ( strval( $text ) === '' ) {
5325 # Only sections 0 and T-0 exist in an empty document
5326 if ( $sectionIndex == 0 ) {
5327 if ( $mode === 'get' ) {
5333 if ( $mode === 'get' ) {
5341 # Preprocess the text
5342 $root = $this->preprocessToDom( $text, $flags );
5344 # <h> nodes indicate section breaks
5345 # They can only occur at the top level, so we can find them by iterating the root's children
5346 $node = $root->getFirstChild();
5348 # Find the target section
5349 if ( $sectionIndex == 0 ) {
5350 # Section zero doesn't nest, level=big
5351 $targetLevel = 1000;
5354 if ( $node->getName() === 'h' ) {
5355 $bits = $node->splitHeading();
5356 if ( $bits['i'] == $sectionIndex ) {
5357 $targetLevel = $bits['level'];
5361 if ( $mode === 'replace' ) {
5362 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5364 $node = $node->getNextSibling();
5370 if ( $mode === 'get' ) {
5377 # Find the end of the section, including nested sections
5379 if ( $node->getName() === 'h' ) {
5380 $bits = $node->splitHeading();
5381 $curLevel = $bits['level'];
5382 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5386 if ( $mode === 'get' ) {
5387 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5389 $node = $node->getNextSibling();
5392 # Write out the remainder (in replace mode only)
5393 if ( $mode === 'replace' ) {
5394 # Output the replacement text
5395 # Add two newlines on -- trailing whitespace in $newText is conventionally
5396 # stripped by the editor, so we need both newlines to restore the paragraph gap
5397 # Only add trailing whitespace if there is newText
5398 if ( $newText != "" ) {
5399 $outText .= $newText . "\n\n";
5403 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5404 $node = $node->getNextSibling();
5408 if ( is_string( $outText ) ) {
5409 # Re-insert stripped tags
5410 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5417 * This function returns the text of a section, specified by a number ($section).
5418 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5419 * the first section before any such heading (section 0).
5421 * If a section contains subsections, these are also returned.
5423 * @param $text String: text to look in
5424 * @param $section String: section identifier
5425 * @param $deftext String: default to return if section is not found
5426 * @return string text of the requested section
5428 public function getSection( $text, $section, $deftext='' ) {
5429 return $this->extractSections( $text, $section, "get", $deftext );
5433 * This function returns $oldtext after the content of the section
5434 * specified by $section has been replaced with $text. If the target
5435 * section does not exist, $oldtext is returned unchanged.
5437 * @param $oldtext String: former text of the article
5438 * @param $section int section identifier
5439 * @param $text String: replacing text
5440 * @return String: modified text
5442 public function replaceSection( $oldtext, $section, $text ) {
5443 return $this->extractSections( $oldtext, $section, "replace", $text );
5447 * Get the ID of the revision we are parsing
5449 * @return Mixed: integer or null
5451 function getRevisionId() {
5452 return $this->mRevisionId
;
5456 * Get the revision object for $this->mRevisionId
5458 * @return Revision|null either a Revision object or null
5460 protected function getRevisionObject() {
5461 if ( !is_null( $this->mRevisionObject
) ) {
5462 return $this->mRevisionObject
;
5464 if ( is_null( $this->mRevisionId
) ) {
5468 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5469 return $this->mRevisionObject
;
5473 * Get the timestamp associated with the current revision, adjusted for
5474 * the default server-local timestamp
5476 function getRevisionTimestamp() {
5477 if ( is_null( $this->mRevisionTimestamp
) ) {
5478 wfProfileIn( __METHOD__
);
5482 $revObject = $this->getRevisionObject();
5483 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5485 # The cryptic '' timezone parameter tells to use the site-default
5486 # timezone offset instead of the user settings.
5488 # Since this value will be saved into the parser cache, served
5489 # to other users, and potentially even used inside links and such,
5490 # it needs to be consistent for all visitors.
5491 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5493 wfProfileOut( __METHOD__
);
5495 return $this->mRevisionTimestamp
;
5499 * Get the name of the user that edited the last revision
5501 * @return String: user name
5503 function getRevisionUser() {
5504 if( is_null( $this->mRevisionUser
) ) {
5505 $revObject = $this->getRevisionObject();
5507 # if this template is subst: the revision id will be blank,
5508 # so just use the current user's name
5510 $this->mRevisionUser
= $revObject->getUserText();
5511 } elseif( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5512 $this->mRevisionUser
= $this->getUser()->getName();
5515 return $this->mRevisionUser
;
5519 * Mutator for $mDefaultSort
5521 * @param $sort string New value
5523 public function setDefaultSort( $sort ) {
5524 $this->mDefaultSort
= $sort;
5525 $this->mOutput
->setProperty( 'defaultsort', $sort );
5529 * Accessor for $mDefaultSort
5530 * Will use the empty string if none is set.
5532 * This value is treated as a prefix, so the
5533 * empty string is equivalent to sorting by
5538 public function getDefaultSort() {
5539 if ( $this->mDefaultSort
!== false ) {
5540 return $this->mDefaultSort
;
5547 * Accessor for $mDefaultSort
5548 * Unlike getDefaultSort(), will return false if none is set
5550 * @return string or false
5552 public function getCustomDefaultSort() {
5553 return $this->mDefaultSort
;
5557 * Try to guess the section anchor name based on a wikitext fragment
5558 * presumably extracted from a heading, for example "Header" from
5561 * @param $text string
5565 public function guessSectionNameFromWikiText( $text ) {
5566 # Strip out wikitext links(they break the anchor)
5567 $text = $this->stripSectionName( $text );
5568 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5569 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5573 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5574 * instead. For use in redirects, since IE6 interprets Redirect: headers
5575 * as something other than UTF-8 (apparently?), resulting in breakage.
5577 * @param $text String: The section name
5578 * @return string An anchor
5580 public function guessLegacySectionNameFromWikiText( $text ) {
5581 # Strip out wikitext links(they break the anchor)
5582 $text = $this->stripSectionName( $text );
5583 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5584 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5588 * Strips a text string of wikitext for use in a section anchor
5590 * Accepts a text string and then removes all wikitext from the
5591 * string and leaves only the resultant text (i.e. the result of
5592 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5593 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5594 * to create valid section anchors by mimicing the output of the
5595 * parser when headings are parsed.
5597 * @param $text String: text string to be stripped of wikitext
5598 * for use in a Section anchor
5599 * @return string Filtered text string
5601 public function stripSectionName( $text ) {
5602 # Strip internal link markup
5603 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5604 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5606 # Strip external link markup
5607 # @todo FIXME: Not tolerant to blank link text
5608 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5609 # on how many empty links there are on the page - need to figure that out.
5610 $text = preg_replace( '/\[(?:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5612 # Parse wikitext quotes (italics & bold)
5613 $text = $this->doQuotes( $text );
5616 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5621 * strip/replaceVariables/unstrip for preprocessor regression testing
5623 * @param $text string
5624 * @param $title Title
5625 * @param $options ParserOptions
5626 * @param $outputType int
5630 function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5631 $this->startParse( $title, $options, $outputType, true );
5633 $text = $this->replaceVariables( $text );
5634 $text = $this->mStripState
->unstripBoth( $text );
5635 $text = Sanitizer
::removeHTMLtags( $text );
5640 * @param $text string
5641 * @param $title Title
5642 * @param $options ParserOptions
5645 function testPst( $text, Title
$title, ParserOptions
$options ) {
5646 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5651 * @param $title Title
5652 * @param $options ParserOptions
5655 function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5656 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5660 * Call a callback function on all regions of the given text that are not
5661 * inside strip markers, and replace those regions with the return value
5662 * of the callback. For example, with input:
5666 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5667 * two strings will be replaced with the value returned by the callback in
5675 function markerSkipCallback( $s, $callback ) {
5678 while ( $i < strlen( $s ) ) {
5679 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5680 if ( $markerStart === false ) {
5681 $out .= call_user_func( $callback, substr( $s, $i ) );
5684 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5685 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5686 if ( $markerEnd === false ) {
5687 $out .= substr( $s, $markerStart );
5690 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5691 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5700 * Remove any strip markers found in the given text.
5702 * @param $text Input string
5705 function killMarkers( $text ) {
5706 return $this->mStripState
->killMarkers( $text );
5710 * Save the parser state required to convert the given half-parsed text to
5711 * HTML. "Half-parsed" in this context means the output of
5712 * recursiveTagParse() or internalParse(). This output has strip markers
5713 * from replaceVariables (extensionSubstitution() etc.), and link
5714 * placeholders from replaceLinkHolders().
5716 * Returns an array which can be serialized and stored persistently. This
5717 * array can later be loaded into another parser instance with
5718 * unserializeHalfParsedText(). The text can then be safely incorporated into
5719 * the return value of a parser hook.
5721 * @param $text string
5725 function serializeHalfParsedText( $text ) {
5726 wfProfileIn( __METHOD__
);
5729 'version' => self
::HALF_PARSED_VERSION
,
5730 'stripState' => $this->mStripState
->getSubState( $text ),
5731 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
5733 wfProfileOut( __METHOD__
);
5738 * Load the parser state given in the $data array, which is assumed to
5739 * have been generated by serializeHalfParsedText(). The text contents is
5740 * extracted from the array, and its markers are transformed into markers
5741 * appropriate for the current Parser instance. This transformed text is
5742 * returned, and can be safely included in the return value of a parser
5745 * If the $data array has been stored persistently, the caller should first
5746 * check whether it is still valid, by calling isValidHalfParsedText().
5748 * @param $data array Serialized data
5751 function unserializeHalfParsedText( $data ) {
5752 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
5753 throw new MWException( __METHOD__
.': invalid version' );
5756 # First, extract the strip state.
5757 $texts = array( $data['text'] );
5758 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
5760 # Now renumber links
5761 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
5763 # Should be good to go.
5768 * Returns true if the given array, presumed to be generated by
5769 * serializeHalfParsedText(), is compatible with the current version of the
5772 * @param $data Array
5776 function isValidHalfParsedText( $data ) {
5777 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
5781 * Parsed a width param of imagelink like 300px or 200x300px
5783 * @param $value String
5788 public function parseWidthParam( $value ) {
5789 $parsedWidthParam = array();
5790 if( $value === '' ) {
5791 return $parsedWidthParam;
5794 # (bug 13500) In both cases (width/height and width only),
5795 # permit trailing "px" for backward compatibility.
5796 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
5797 $width = intval( $m[1] );
5798 $height = intval( $m[2] );
5799 $parsedWidthParam['width'] = $width;
5800 $parsedWidthParam['height'] = $height;
5801 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
5802 $width = intval( $value );
5803 $parsedWidthParam['width'] = $width;
5805 return $parsedWidthParam;