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.
741 * @return Language|null
743 public function getTargetLanguage() {
744 $target = $this->mOptions
->getTargetLanguage();
746 if ( $target !== null ) {
748 } elseif( $this->mOptions
->getInterfaceMessage() ) {
749 return $this->mOptions
->getUserLangObj();
750 } elseif( is_null( $this->mTitle
) ) {
751 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
754 return $this->mTitle
->getPageLanguage();
758 * Get the language object for language conversion
760 function getConverterLanguage() {
761 global $wgBug34832TransitionalRollback, $wgContLang;
762 if ( $wgBug34832TransitionalRollback ) {
765 return $this->getTargetLanguage();
770 * Get a User object either from $this->mUser, if set, or from the
771 * ParserOptions object otherwise
773 * @return User object
776 if ( !is_null( $this->mUser
) ) {
779 return $this->mOptions
->getUser();
783 * Get a preprocessor object
785 * @return Preprocessor instance
787 function getPreprocessor() {
788 if ( !isset( $this->mPreprocessor
) ) {
789 $class = $this->mPreprocessorClass
;
790 $this->mPreprocessor
= new $class( $this );
792 return $this->mPreprocessor
;
796 * Replaces all occurrences of HTML-style comments and the given tags
797 * in the text with a random marker and returns the next text. The output
798 * parameter $matches will be an associative array filled with data in
802 * 'UNIQ-xxxxx' => array(
805 * array( 'param' => 'x' ),
806 * '<element param="x">tag content</element>' ) )
809 * @param $elements array list of element names. Comments are always extracted.
810 * @param $text string Source text string.
811 * @param $matches array Out parameter, Array: extracted tags
812 * @param $uniq_prefix string
813 * @return String: stripped text
815 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
820 $taglist = implode( '|', $elements );
821 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
823 while ( $text != '' ) {
824 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
826 if ( count( $p ) < 5 ) {
829 if ( count( $p ) > 5 ) {
843 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
844 $stripped .= $marker;
846 if ( $close === '/>' ) {
847 # Empty element tag, <tag />
852 if ( $element === '!--' ) {
855 $end = "/(<\\/$element\\s*>)/i";
857 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
859 if ( count( $q ) < 3 ) {
860 # No end tag -- let it run out to the end of the text.
869 $matches[$marker] = array( $element,
871 Sanitizer
::decodeTagAttributes( $attributes ),
872 "<$element$attributes$close$content$tail" );
878 * Get a list of strippable XML-like elements
882 function getStripList() {
883 return $this->mStripList
;
887 * Add an item to the strip state
888 * Returns the unique tag which must be inserted into the stripped text
889 * The tag will be replaced with the original text in unstrip()
891 * @param $text string
895 function insertStripItem( $text ) {
896 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
897 $this->mMarkerIndex++
;
898 $this->mStripState
->addGeneral( $rnd, $text );
903 * parse the wiki syntax used to render tables
908 function doTableStuff( $text ) {
909 wfProfileIn( __METHOD__
);
911 $lines = StringUtils
::explode( "\n", $text );
913 $td_history = array(); # Is currently a td tag open?
914 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
915 $tr_history = array(); # Is currently a tr tag open?
916 $tr_attributes = array(); # history of tr attributes
917 $has_opened_tr = array(); # Did this table open a <tr> element?
918 $indent_level = 0; # indent level of the table
920 foreach ( $lines as $outLine ) {
921 $line = trim( $outLine );
923 if ( $line === '' ) { # empty line, go to next line
924 $out .= $outLine."\n";
928 $first_character = $line[0];
931 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
932 # First check if we are starting a new table
933 $indent_level = strlen( $matches[1] );
935 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
936 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
938 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
939 array_push( $td_history , false );
940 array_push( $last_tag_history , '' );
941 array_push( $tr_history , false );
942 array_push( $tr_attributes , '' );
943 array_push( $has_opened_tr , false );
944 } elseif ( count( $td_history ) == 0 ) {
945 # Don't do any of the following
946 $out .= $outLine."\n";
948 } elseif ( substr( $line , 0 , 2 ) === '|}' ) {
949 # We are ending a table
950 $line = '</table>' . substr( $line , 2 );
951 $last_tag = array_pop( $last_tag_history );
953 if ( !array_pop( $has_opened_tr ) ) {
954 $line = "<tr><td></td></tr>{$line}";
957 if ( array_pop( $tr_history ) ) {
958 $line = "</tr>{$line}";
961 if ( array_pop( $td_history ) ) {
962 $line = "</{$last_tag}>{$line}";
964 array_pop( $tr_attributes );
965 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
966 } elseif ( substr( $line , 0 , 2 ) === '|-' ) {
967 # Now we have a table row
968 $line = preg_replace( '#^\|-+#', '', $line );
970 # Whats after the tag is now only attributes
971 $attributes = $this->mStripState
->unstripBoth( $line );
972 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
973 array_pop( $tr_attributes );
974 array_push( $tr_attributes, $attributes );
977 $last_tag = array_pop( $last_tag_history );
978 array_pop( $has_opened_tr );
979 array_push( $has_opened_tr , true );
981 if ( array_pop( $tr_history ) ) {
985 if ( array_pop( $td_history ) ) {
986 $line = "</{$last_tag}>{$line}";
990 array_push( $tr_history , false );
991 array_push( $td_history , false );
992 array_push( $last_tag_history , '' );
993 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line , 0 , 2 ) === '|+' ) {
994 # This might be cell elements, td, th or captions
995 if ( substr( $line , 0 , 2 ) === '|+' ) {
996 $first_character = '+';
997 $line = substr( $line , 1 );
1000 $line = substr( $line , 1 );
1002 if ( $first_character === '!' ) {
1003 $line = str_replace( '!!' , '||' , $line );
1006 # Split up multiple cells on the same line.
1007 # FIXME : This can result in improper nesting of tags processed
1008 # by earlier parser steps, but should avoid splitting up eg
1009 # attribute values containing literal "||".
1010 $cells = StringUtils
::explodeMarkup( '||' , $line );
1014 # Loop through each table cell
1015 foreach ( $cells as $cell ) {
1017 if ( $first_character !== '+' ) {
1018 $tr_after = array_pop( $tr_attributes );
1019 if ( !array_pop( $tr_history ) ) {
1020 $previous = "<tr{$tr_after}>\n";
1022 array_push( $tr_history , true );
1023 array_push( $tr_attributes , '' );
1024 array_pop( $has_opened_tr );
1025 array_push( $has_opened_tr , true );
1028 $last_tag = array_pop( $last_tag_history );
1030 if ( array_pop( $td_history ) ) {
1031 $previous = "</{$last_tag}>\n{$previous}";
1034 if ( $first_character === '|' ) {
1036 } elseif ( $first_character === '!' ) {
1038 } elseif ( $first_character === '+' ) {
1039 $last_tag = 'caption';
1044 array_push( $last_tag_history , $last_tag );
1046 # A cell could contain both parameters and data
1047 $cell_data = explode( '|' , $cell , 2 );
1049 # Bug 553: Note that a '|' inside an invalid link should not
1050 # be mistaken as delimiting cell parameters
1051 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1052 $cell = "{$previous}<{$last_tag}>{$cell}";
1053 } elseif ( count( $cell_data ) == 1 ) {
1054 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1056 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1057 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
1058 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1062 array_push( $td_history , true );
1065 $out .= $outLine . "\n";
1068 # Closing open td, tr && table
1069 while ( count( $td_history ) > 0 ) {
1070 if ( array_pop( $td_history ) ) {
1073 if ( array_pop( $tr_history ) ) {
1076 if ( !array_pop( $has_opened_tr ) ) {
1077 $out .= "<tr><td></td></tr>\n" ;
1080 $out .= "</table>\n";
1083 # Remove trailing line-ending (b/c)
1084 if ( substr( $out, -1 ) === "\n" ) {
1085 $out = substr( $out, 0, -1 );
1088 # special case: don't return empty table
1089 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1093 wfProfileOut( __METHOD__
);
1099 * Helper function for parse() that transforms wiki markup into
1100 * HTML. Only called for $mOutputType == self::OT_HTML.
1104 * @param $text string
1105 * @param $isMain bool
1106 * @param $frame bool
1110 function internalParse( $text, $isMain = true, $frame = false ) {
1111 wfProfileIn( __METHOD__
);
1115 # Hook to suspend the parser in this state
1116 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1117 wfProfileOut( __METHOD__
);
1121 # if $frame is provided, then use $frame for replacing any variables
1123 # use frame depth to infer how include/noinclude tags should be handled
1124 # depth=0 means this is the top-level document; otherwise it's an included document
1125 if ( !$frame->depth
) {
1128 $flag = Parser
::PTD_FOR_INCLUSION
;
1130 $dom = $this->preprocessToDom( $text, $flag );
1131 $text = $frame->expand( $dom );
1133 # if $frame is not provided, then use old-style replaceVariables
1134 $text = $this->replaceVariables( $text );
1137 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1138 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1139 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1141 # Tables need to come after variable replacement for things to work
1142 # properly; putting them before other transformations should keep
1143 # exciting things like link expansions from showing up in surprising
1145 $text = $this->doTableStuff( $text );
1147 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1149 $text = $this->doDoubleUnderscore( $text );
1151 $text = $this->doHeadings( $text );
1152 if ( $this->mOptions
->getUseDynamicDates() ) {
1153 $df = DateFormatter
::getInstance();
1154 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1156 $text = $this->replaceInternalLinks( $text );
1157 $text = $this->doAllQuotes( $text );
1158 $text = $this->replaceExternalLinks( $text );
1160 # replaceInternalLinks may sometimes leave behind
1161 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1162 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
1164 $text = $this->doMagicLinks( $text );
1165 $text = $this->formatHeadings( $text, $origText, $isMain );
1167 wfProfileOut( __METHOD__
);
1172 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1173 * magic external links.
1178 * @param $text string
1182 function doMagicLinks( $text ) {
1183 wfProfileIn( __METHOD__
);
1184 $prots = wfUrlProtocolsWithoutProtRel();
1185 $urlChar = self
::EXT_LINK_URL_CLASS
;
1186 $text = preg_replace_callback(
1188 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1189 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1190 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1191 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1192 ISBN\s+(\b # m[5]: ISBN, capture number
1193 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1194 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1195 [0-9Xx] # check digit
1197 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1198 wfProfileOut( __METHOD__
);
1203 * @throws MWException
1205 * @return HTML|string
1207 function magicLinkCallback( $m ) {
1208 if ( isset( $m[1] ) && $m[1] !== '' ) {
1211 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1214 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1215 # Free external link
1216 return $this->makeFreeExternalLink( $m[0] );
1217 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1219 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1222 $CssClass = 'mw-magiclink-rfc';
1224 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1226 $urlmsg = 'pubmedurl';
1227 $CssClass = 'mw-magiclink-pmid';
1230 throw new MWException( __METHOD__
.': unrecognised match type "' .
1231 substr( $m[0], 0, 20 ) . '"' );
1233 $url = wfMsgForContent( $urlmsg, $id );
1234 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1235 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1238 $num = strtr( $isbn, array(
1243 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1245 htmlspecialchars( $titleObj->getLocalUrl() ) .
1246 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1253 * Make a free external link, given a user-supplied URL
1255 * @param $url string
1257 * @return string HTML
1260 function makeFreeExternalLink( $url ) {
1261 wfProfileIn( __METHOD__
);
1265 # The characters '<' and '>' (which were escaped by
1266 # removeHTMLtags()) should not be included in
1267 # URLs, per RFC 2396.
1269 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1270 $trail = substr( $url, $m2[0][1] ) . $trail;
1271 $url = substr( $url, 0, $m2[0][1] );
1274 # Move trailing punctuation to $trail
1276 # If there is no left bracket, then consider right brackets fair game too
1277 if ( strpos( $url, '(' ) === false ) {
1281 $numSepChars = strspn( strrev( $url ), $sep );
1282 if ( $numSepChars ) {
1283 $trail = substr( $url, -$numSepChars ) . $trail;
1284 $url = substr( $url, 0, -$numSepChars );
1287 $url = Sanitizer
::cleanUrl( $url );
1289 # Is this an external image?
1290 $text = $this->maybeMakeExternalImage( $url );
1291 if ( $text === false ) {
1292 # Not an image, make a link
1293 $text = Linker
::makeExternalLink( $url,
1294 $this->getConverterLanguage()->markNoConversion($url), true, 'free',
1295 $this->getExternalLinkAttribs( $url ) );
1296 # Register it in the output object...
1297 # Replace unnecessary URL escape codes with their equivalent characters
1298 $pasteurized = self
::replaceUnusualEscapes( $url );
1299 $this->mOutput
->addExternalLink( $pasteurized );
1301 wfProfileOut( __METHOD__
);
1302 return $text . $trail;
1307 * Parse headers and return html
1311 * @param $text string
1315 function doHeadings( $text ) {
1316 wfProfileIn( __METHOD__
);
1317 for ( $i = 6; $i >= 1; --$i ) {
1318 $h = str_repeat( '=', $i );
1319 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1320 "<h$i>\\1</h$i>", $text );
1322 wfProfileOut( __METHOD__
);
1327 * Replace single quotes with HTML markup
1330 * @param $text string
1332 * @return string the altered text
1334 function doAllQuotes( $text ) {
1335 wfProfileIn( __METHOD__
);
1337 $lines = StringUtils
::explode( "\n", $text );
1338 foreach ( $lines as $line ) {
1339 $outtext .= $this->doQuotes( $line ) . "\n";
1341 $outtext = substr( $outtext, 0,-1 );
1342 wfProfileOut( __METHOD__
);
1347 * Helper function for doAllQuotes()
1349 * @param $text string
1353 public function doQuotes( $text ) {
1354 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1355 if ( count( $arr ) == 1 ) {
1358 # First, do some preliminary work. This may shift some apostrophes from
1359 # being mark-up to being text. It also counts the number of occurrences
1360 # of bold and italics mark-ups.
1363 for ( $i = 0; $i < count( $arr ); $i++
) {
1364 if ( ( $i %
2 ) == 1 ) {
1365 # If there are ever four apostrophes, assume the first is supposed to
1366 # be text, and the remaining three constitute mark-up for bold text.
1367 if ( strlen( $arr[$i] ) == 4 ) {
1370 } elseif ( strlen( $arr[$i] ) > 5 ) {
1371 # If there are more than 5 apostrophes in a row, assume they're all
1372 # text except for the last 5.
1373 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1376 # Count the number of occurrences of bold and italics mark-ups.
1377 # We are not counting sequences of five apostrophes.
1378 if ( strlen( $arr[$i] ) == 2 ) {
1380 } elseif ( strlen( $arr[$i] ) == 3 ) {
1382 } elseif ( strlen( $arr[$i] ) == 5 ) {
1389 # If there is an odd number of both bold and italics, it is likely
1390 # that one of the bold ones was meant to be an apostrophe followed
1391 # by italics. Which one we cannot know for certain, but it is more
1392 # likely to be one that has a single-letter word before it.
1393 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1395 $firstsingleletterword = -1;
1396 $firstmultiletterword = -1;
1398 foreach ( $arr as $r ) {
1399 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1400 $x1 = substr( $arr[$i-1], -1 );
1401 $x2 = substr( $arr[$i-1], -2, 1 );
1402 if ( $x1 === ' ' ) {
1403 if ( $firstspace == -1 ) {
1406 } elseif ( $x2 === ' ') {
1407 if ( $firstsingleletterword == -1 ) {
1408 $firstsingleletterword = $i;
1411 if ( $firstmultiletterword == -1 ) {
1412 $firstmultiletterword = $i;
1419 # If there is a single-letter word, use it!
1420 if ( $firstsingleletterword > -1 ) {
1421 $arr[$firstsingleletterword] = "''";
1422 $arr[$firstsingleletterword-1] .= "'";
1423 } elseif ( $firstmultiletterword > -1 ) {
1424 # If not, but there's a multi-letter word, use that one.
1425 $arr[$firstmultiletterword] = "''";
1426 $arr[$firstmultiletterword-1] .= "'";
1427 } elseif ( $firstspace > -1 ) {
1428 # ... otherwise use the first one that has neither.
1429 # (notice that it is possible for all three to be -1 if, for example,
1430 # there is only one pentuple-apostrophe in the line)
1431 $arr[$firstspace] = "''";
1432 $arr[$firstspace-1] .= "'";
1436 # Now let's actually convert our apostrophic mush to HTML!
1441 foreach ( $arr as $r ) {
1442 if ( ( $i %
2 ) == 0 ) {
1443 if ( $state === 'both' ) {
1449 if ( strlen( $r ) == 2 ) {
1450 if ( $state === 'i' ) {
1451 $output .= '</i>'; $state = '';
1452 } elseif ( $state === 'bi' ) {
1453 $output .= '</i>'; $state = 'b';
1454 } elseif ( $state === 'ib' ) {
1455 $output .= '</b></i><b>'; $state = 'b';
1456 } elseif ( $state === 'both' ) {
1457 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1458 } else { # $state can be 'b' or ''
1459 $output .= '<i>'; $state .= 'i';
1461 } elseif ( strlen( $r ) == 3 ) {
1462 if ( $state === 'b' ) {
1463 $output .= '</b>'; $state = '';
1464 } elseif ( $state === 'bi' ) {
1465 $output .= '</i></b><i>'; $state = 'i';
1466 } elseif ( $state === 'ib' ) {
1467 $output .= '</b>'; $state = 'i';
1468 } elseif ( $state === 'both' ) {
1469 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1470 } else { # $state can be 'i' or ''
1471 $output .= '<b>'; $state .= 'b';
1473 } elseif ( strlen( $r ) == 5 ) {
1474 if ( $state === 'b' ) {
1475 $output .= '</b><i>'; $state = 'i';
1476 } elseif ( $state === 'i' ) {
1477 $output .= '</i><b>'; $state = 'b';
1478 } elseif ( $state === 'bi' ) {
1479 $output .= '</i></b>'; $state = '';
1480 } elseif ( $state === 'ib' ) {
1481 $output .= '</b></i>'; $state = '';
1482 } elseif ( $state === 'both' ) {
1483 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1484 } else { # ($state == '')
1485 $buffer = ''; $state = 'both';
1491 # Now close all remaining tags. Notice that the order is important.
1492 if ( $state === 'b' ||
$state === 'ib' ) {
1495 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1498 if ( $state === 'bi' ) {
1501 # There might be lonely ''''', so make sure we have a buffer
1502 if ( $state === 'both' && $buffer ) {
1503 $output .= '<b><i>'.$buffer.'</i></b>';
1510 * Replace external links (REL)
1512 * Note: this is all very hackish and the order of execution matters a lot.
1513 * Make sure to run maintenance/parserTests.php if you change this code.
1517 * @param $text string
1521 function replaceExternalLinks( $text ) {
1522 wfProfileIn( __METHOD__
);
1524 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1525 $s = array_shift( $bits );
1528 while ( $i<count( $bits ) ) {
1530 $protocol = $bits[$i++
];
1531 $text = $bits[$i++
];
1532 $trail = $bits[$i++
];
1534 # The characters '<' and '>' (which were escaped by
1535 # removeHTMLtags()) should not be included in
1536 # URLs, per RFC 2396.
1538 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1539 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1540 $url = substr( $url, 0, $m2[0][1] );
1543 # If the link text is an image URL, replace it with an <img> tag
1544 # This happened by accident in the original parser, but some people used it extensively
1545 $img = $this->maybeMakeExternalImage( $text );
1546 if ( $img !== false ) {
1552 # Set linktype for CSS - if URL==text, link is essentially free
1553 $linktype = ( $text === $url ) ?
'free' : 'text';
1555 # No link text, e.g. [http://domain.tld/some.link]
1556 if ( $text == '' ) {
1558 $langObj = $this->getTargetLanguage();
1559 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1560 $linktype = 'autonumber';
1562 # Have link text, e.g. [http://domain.tld/some.link text]s
1564 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1567 $text = $this->getConverterLanguage()->markNoConversion( $text );
1569 $url = Sanitizer
::cleanUrl( $url );
1571 # Use the encoded URL
1572 # This means that users can paste URLs directly into the text
1573 # Funny characters like ö aren't valid in URLs anyway
1574 # This was changed in August 2004
1575 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1576 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1578 # Register link in the output object.
1579 # Replace unnecessary URL escape codes with the referenced character
1580 # This prevents spammers from hiding links from the filters
1581 $pasteurized = self
::replaceUnusualEscapes( $url );
1582 $this->mOutput
->addExternalLink( $pasteurized );
1585 wfProfileOut( __METHOD__
);
1590 * Get an associative array of additional HTML attributes appropriate for a
1591 * particular external link. This currently may include rel => nofollow
1592 * (depending on configuration, namespace, and the URL's domain) and/or a
1593 * target attribute (depending on configuration).
1595 * @param $url String|bool optional URL, to extract the domain from for rel =>
1596 * nofollow if appropriate
1597 * @return Array associative array of HTML attributes
1599 function getExternalLinkAttribs( $url = false ) {
1601 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1602 $ns = $this->mTitle
->getNamespace();
1603 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) &&
1604 !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions ) )
1606 $attribs['rel'] = 'nofollow';
1608 if ( $this->mOptions
->getExternalLinkTarget() ) {
1609 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1615 * Replace unusual URL escape codes with their equivalent characters
1617 * @param $url String
1620 * @todo This can merge genuinely required bits in the path or query string,
1621 * breaking legit URLs. A proper fix would treat the various parts of
1622 * the URL differently; as a workaround, just use the output for
1623 * statistical records, not for actual linking/output.
1625 static function replaceUnusualEscapes( $url ) {
1626 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1627 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1631 * Callback function used in replaceUnusualEscapes().
1632 * Replaces unusual URL escape codes with their equivalent character
1634 * @param $matches array
1638 private static function replaceUnusualEscapesCallback( $matches ) {
1639 $char = urldecode( $matches[0] );
1640 $ord = ord( $char );
1641 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1642 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1643 # No, shouldn't be escaped
1646 # Yes, leave it escaped
1652 * make an image if it's allowed, either through the global
1653 * option, through the exception, or through the on-wiki whitelist
1656 * $param $url string
1660 function maybeMakeExternalImage( $url ) {
1661 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1662 $imagesexception = !empty( $imagesfrom );
1664 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1665 if ( $imagesexception && is_array( $imagesfrom ) ) {
1666 $imagematch = false;
1667 foreach ( $imagesfrom as $match ) {
1668 if ( strpos( $url, $match ) === 0 ) {
1673 } elseif ( $imagesexception ) {
1674 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1676 $imagematch = false;
1678 if ( $this->mOptions
->getAllowExternalImages()
1679 ||
( $imagesexception && $imagematch ) ) {
1680 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1682 $text = Linker
::makeExternalImage( $url );
1685 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1686 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1687 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1688 foreach ( $whitelist as $entry ) {
1689 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1690 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1693 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1694 # Image matches a whitelist entry
1695 $text = Linker
::makeExternalImage( $url );
1704 * Process [[ ]] wikilinks
1708 * @return String: processed text
1712 function replaceInternalLinks( $s ) {
1713 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1718 * Process [[ ]] wikilinks (RIL)
1719 * @return LinkHolderArray
1723 function replaceInternalLinks2( &$s ) {
1724 wfProfileIn( __METHOD__
);
1726 wfProfileIn( __METHOD__
.'-setup' );
1727 static $tc = FALSE, $e1, $e1_img;
1728 # the % is needed to support urlencoded titles as well
1730 $tc = Title
::legalChars() . '#%';
1731 # Match a link having the form [[namespace:link|alternate]]trail
1732 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1733 # Match cases where there is no "]]", which might still be images
1734 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1737 $holders = new LinkHolderArray( $this );
1739 # split the entire text string on occurrences of [[
1740 $a = StringUtils
::explode( '[[', ' ' . $s );
1741 # get the first element (all text up to first [[), and remove the space we added
1744 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1745 $s = substr( $s, 1 );
1747 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1749 if ( $useLinkPrefixExtension ) {
1750 # Match the end of a line for a word that's not followed by whitespace,
1751 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1752 $e2 = wfMsgForContent( 'linkprefix' );
1755 if ( is_null( $this->mTitle
) ) {
1756 wfProfileOut( __METHOD__
.'-setup' );
1757 wfProfileOut( __METHOD__
);
1758 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1760 $nottalk = !$this->mTitle
->isTalkPage();
1762 if ( $useLinkPrefixExtension ) {
1764 if ( preg_match( $e2, $s, $m ) ) {
1765 $first_prefix = $m[2];
1767 $first_prefix = false;
1773 if ( $this->getConverterLanguage()->hasVariants() ) {
1774 $selflink = $this->getConverterLanguage()->autoConvertToAllVariants(
1775 $this->mTitle
->getPrefixedText() );
1777 $selflink = array( $this->mTitle
->getPrefixedText() );
1779 $useSubpages = $this->areSubpagesAllowed();
1780 wfProfileOut( __METHOD__
.'-setup' );
1782 # Loop for each link
1783 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1784 # Check for excessive memory usage
1785 if ( $holders->isBig() ) {
1787 # Do the existence check, replace the link holders and clear the array
1788 $holders->replace( $s );
1792 if ( $useLinkPrefixExtension ) {
1793 wfProfileIn( __METHOD__
.'-prefixhandling' );
1794 if ( preg_match( $e2, $s, $m ) ) {
1801 if ( $first_prefix ) {
1802 $prefix = $first_prefix;
1803 $first_prefix = false;
1805 wfProfileOut( __METHOD__
.'-prefixhandling' );
1808 $might_be_img = false;
1810 wfProfileIn( __METHOD__
."-e1" );
1811 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1813 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1814 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1815 # the real problem is with the $e1 regex
1818 # Still some problems for cases where the ] is meant to be outside punctuation,
1819 # and no image is in sight. See bug 2095.
1821 if ( $text !== '' &&
1822 substr( $m[3], 0, 1 ) === ']' &&
1823 strpos( $text, '[' ) !== false
1826 $text .= ']'; # so that replaceExternalLinks($text) works later
1827 $m[3] = substr( $m[3], 1 );
1829 # fix up urlencoded title texts
1830 if ( strpos( $m[1], '%' ) !== false ) {
1831 # Should anchors '#' also be rejected?
1832 $m[1] = str_replace( array('<', '>'), array('<', '>'), rawurldecode( $m[1] ) );
1835 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1836 $might_be_img = true;
1838 if ( strpos( $m[1], '%' ) !== false ) {
1839 $m[1] = rawurldecode( $m[1] );
1842 } else { # Invalid form; output directly
1843 $s .= $prefix . '[[' . $line ;
1844 wfProfileOut( __METHOD__
."-e1" );
1847 wfProfileOut( __METHOD__
."-e1" );
1848 wfProfileIn( __METHOD__
."-misc" );
1850 # Don't allow internal links to pages containing
1851 # PROTO: where PROTO is a valid URL protocol; these
1852 # should be external links.
1853 if ( preg_match( '/^(?:' . $this->mUrlProtocols
. ')/', $m[1] ) ) {
1854 $s .= $prefix . '[[' . $line ;
1855 wfProfileOut( __METHOD__
."-misc" );
1859 # Make subpage if necessary
1860 if ( $useSubpages ) {
1861 $link = $this->maybeDoSubpageLink( $m[1], $text );
1866 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1868 # Strip off leading ':'
1869 $link = substr( $link, 1 );
1872 wfProfileOut( __METHOD__
."-misc" );
1873 wfProfileIn( __METHOD__
."-title" );
1874 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1875 if ( $nt === null ) {
1876 $s .= $prefix . '[[' . $line;
1877 wfProfileOut( __METHOD__
."-title" );
1881 $ns = $nt->getNamespace();
1882 $iw = $nt->getInterWiki();
1883 wfProfileOut( __METHOD__
."-title" );
1885 if ( $might_be_img ) { # if this is actually an invalid link
1886 wfProfileIn( __METHOD__
."-might_be_img" );
1887 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1890 # look at the next 'line' to see if we can close it there
1892 $next_line = $a->current();
1893 if ( $next_line === false ||
$next_line === null ) {
1896 $m = explode( ']]', $next_line, 3 );
1897 if ( count( $m ) == 3 ) {
1898 # the first ]] closes the inner link, the second the image
1900 $text .= "[[{$m[0]}]]{$m[1]}";
1903 } elseif ( count( $m ) == 2 ) {
1904 # if there's exactly one ]] that's fine, we'll keep looking
1905 $text .= "[[{$m[0]}]]{$m[1]}";
1907 # if $next_line is invalid too, we need look no further
1908 $text .= '[[' . $next_line;
1913 # we couldn't find the end of this imageLink, so output it raw
1914 # but don't ignore what might be perfectly normal links in the text we've examined
1915 $holders->merge( $this->replaceInternalLinks2( $text ) );
1916 $s .= "{$prefix}[[$link|$text";
1917 # note: no $trail, because without an end, there *is* no trail
1918 wfProfileOut( __METHOD__
."-might_be_img" );
1921 } else { # it's not an image, so output it raw
1922 $s .= "{$prefix}[[$link|$text";
1923 # note: no $trail, because without an end, there *is* no trail
1924 wfProfileOut( __METHOD__
."-might_be_img" );
1927 wfProfileOut( __METHOD__
."-might_be_img" );
1930 $wasblank = ( $text == '' );
1934 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1935 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1936 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1937 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1938 $text = $this->doQuotes( $text );
1941 # Link not escaped by : , create the various objects
1944 wfProfileIn( __METHOD__
."-interwiki" );
1945 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && Language
::fetchLanguageName( $iw, null, 'mw' ) ) {
1946 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1947 $s = rtrim( $s . $prefix );
1948 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1949 wfProfileOut( __METHOD__
."-interwiki" );
1952 wfProfileOut( __METHOD__
."-interwiki" );
1954 if ( $ns == NS_FILE
) {
1955 wfProfileIn( __METHOD__
."-image" );
1956 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1958 # if no parameters were passed, $text
1959 # becomes something like "File:Foo.png",
1960 # which we don't want to pass on to the
1964 # recursively parse links inside the image caption
1965 # actually, this will parse them in any other parameters, too,
1966 # but it might be hard to fix that, and it doesn't matter ATM
1967 $text = $this->replaceExternalLinks( $text );
1968 $holders->merge( $this->replaceInternalLinks2( $text ) );
1970 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1971 $s .= $prefix . $this->armorLinks(
1972 $this->makeImage( $nt, $text, $holders ) ) . $trail;
1974 $s .= $prefix . $trail;
1976 wfProfileOut( __METHOD__
."-image" );
1980 if ( $ns == NS_CATEGORY
) {
1981 wfProfileIn( __METHOD__
."-category" );
1982 $s = rtrim( $s . "\n" ); # bug 87
1985 $sortkey = $this->getDefaultSort();
1989 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1990 $sortkey = str_replace( "\n", '', $sortkey );
1991 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
1992 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1995 * Strip the whitespace Category links produce, see bug 87
1996 * @todo We might want to use trim($tmp, "\n") here.
1998 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2000 wfProfileOut( __METHOD__
."-category" );
2005 # Self-link checking
2006 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
2007 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
2008 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2013 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2014 # @todo FIXME: Should do batch file existence checks, see comment below
2015 if ( $ns == NS_MEDIA
) {
2016 wfProfileIn( __METHOD__
."-media" );
2017 # Give extensions a chance to select the file revision for us
2020 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2021 array( $this, $nt, &$options, &$descQuery ) );
2022 # Fetch and register the file (file title may be different via hooks)
2023 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2024 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2025 $s .= $prefix . $this->armorLinks(
2026 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2027 wfProfileOut( __METHOD__
."-media" );
2031 wfProfileIn( __METHOD__
."-always_known" );
2032 # Some titles, such as valid special pages or files in foreign repos, should
2033 # be shown as bluelinks even though they're not included in the page table
2035 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2036 # batch file existence checks for NS_FILE and NS_MEDIA
2037 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2038 $this->mOutput
->addLink( $nt );
2039 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2041 # Links will be added to the output link list after checking
2042 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2044 wfProfileOut( __METHOD__
."-always_known" );
2046 wfProfileOut( __METHOD__
);
2051 * Render a forced-blue link inline; protect against double expansion of
2052 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2053 * Since this little disaster has to split off the trail text to avoid
2054 * breaking URLs in the following text without breaking trails on the
2055 * wiki links, it's been made into a horrible function.
2058 * @param $text String
2059 * @param $query Array or String
2060 * @param $trail String
2061 * @param $prefix String
2062 * @return String: HTML-wikitext mix oh yuck
2064 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2065 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2067 if ( is_string( $query ) ) {
2068 $query = wfCgiToArray( $query );
2070 if ( $text == '' ) {
2071 $text = htmlspecialchars( $nt->getPrefixedText() );
2074 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2076 return $this->armorLinks( $link ) . $trail;
2080 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2081 * going to go through further parsing steps before inline URL expansion.
2083 * Not needed quite as much as it used to be since free links are a bit
2084 * more sensible these days. But bracketed links are still an issue.
2086 * @param $text String: more-or-less HTML
2087 * @return String: less-or-more HTML with NOPARSE bits
2089 function armorLinks( $text ) {
2090 return preg_replace( '/\b(' . $this->mUrlProtocols
. ')/',
2091 "{$this->mUniqPrefix}NOPARSE$1", $text );
2095 * Return true if subpage links should be expanded on this page.
2098 function areSubpagesAllowed() {
2099 # Some namespaces don't allow subpages
2100 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2104 * Handle link to subpage if necessary
2106 * @param $target String: the source of the link
2107 * @param &$text String: the link text, modified as necessary
2108 * @return string the full name of the link
2111 function maybeDoSubpageLink( $target, &$text ) {
2112 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2116 * Used by doBlockLevels()
2121 function closeParagraph() {
2123 if ( $this->mLastSection
!= '' ) {
2124 $result = '</' . $this->mLastSection
. ">\n";
2126 $this->mInPre
= false;
2127 $this->mLastSection
= '';
2132 * getCommon() returns the length of the longest common substring
2133 * of both arguments, starting at the beginning of both.
2136 * @param $st1 string
2137 * @param $st2 string
2141 function getCommon( $st1, $st2 ) {
2142 $fl = strlen( $st1 );
2143 $shorter = strlen( $st2 );
2144 if ( $fl < $shorter ) {
2148 for ( $i = 0; $i < $shorter; ++
$i ) {
2149 if ( $st1[$i] != $st2[$i] ) {
2157 * These next three functions open, continue, and close the list
2158 * element appropriate to the prefix character passed into them.
2161 * @param $char string
2165 function openList( $char ) {
2166 $result = $this->closeParagraph();
2168 if ( '*' === $char ) {
2169 $result .= '<ul><li>';
2170 } elseif ( '#' === $char ) {
2171 $result .= '<ol><li>';
2172 } elseif ( ':' === $char ) {
2173 $result .= '<dl><dd>';
2174 } elseif ( ';' === $char ) {
2175 $result .= '<dl><dt>';
2176 $this->mDTopen
= true;
2178 $result = '<!-- ERR 1 -->';
2186 * @param $char String
2191 function nextItem( $char ) {
2192 if ( '*' === $char ||
'#' === $char ) {
2194 } elseif ( ':' === $char ||
';' === $char ) {
2196 if ( $this->mDTopen
) {
2199 if ( ';' === $char ) {
2200 $this->mDTopen
= true;
2201 return $close . '<dt>';
2203 $this->mDTopen
= false;
2204 return $close . '<dd>';
2207 return '<!-- ERR 2 -->';
2212 * @param $char String
2217 function closeList( $char ) {
2218 if ( '*' === $char ) {
2219 $text = '</li></ul>';
2220 } elseif ( '#' === $char ) {
2221 $text = '</li></ol>';
2222 } elseif ( ':' === $char ) {
2223 if ( $this->mDTopen
) {
2224 $this->mDTopen
= false;
2225 $text = '</dt></dl>';
2227 $text = '</dd></dl>';
2230 return '<!-- ERR 3 -->';
2237 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2239 * @param $text String
2240 * @param $linestart Boolean: whether or not this is at the start of a line.
2242 * @return string the lists rendered as HTML
2244 function doBlockLevels( $text, $linestart ) {
2245 wfProfileIn( __METHOD__
);
2247 # Parsing through the text line by line. The main thing
2248 # happening here is handling of block-level elements p, pre,
2249 # and making lists from lines starting with * # : etc.
2251 $textLines = StringUtils
::explode( "\n", $text );
2253 $lastPrefix = $output = '';
2254 $this->mDTopen
= $inBlockElem = false;
2256 $paragraphStack = false;
2258 foreach ( $textLines as $oLine ) {
2260 if ( !$linestart ) {
2270 $lastPrefixLength = strlen( $lastPrefix );
2271 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2272 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2273 # If not in a <pre> element, scan for and figure out what prefixes are there.
2274 if ( !$this->mInPre
) {
2275 # Multiple prefixes may abut each other for nested lists.
2276 $prefixLength = strspn( $oLine, '*#:;' );
2277 $prefix = substr( $oLine, 0, $prefixLength );
2280 # ; and : are both from definition-lists, so they're equivalent
2281 # for the purposes of determining whether or not we need to open/close
2283 $prefix2 = str_replace( ';', ':', $prefix );
2284 $t = substr( $oLine, $prefixLength );
2285 $this->mInPre
= (bool)$preOpenMatch;
2287 # Don't interpret any other prefixes in preformatted text
2289 $prefix = $prefix2 = '';
2294 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2295 # Same as the last item, so no need to deal with nesting or opening stuff
2296 $output .= $this->nextItem( substr( $prefix, -1 ) );
2297 $paragraphStack = false;
2299 if ( substr( $prefix, -1 ) === ';') {
2300 # The one nasty exception: definition lists work like this:
2301 # ; title : definition text
2302 # So we check for : in the remainder text to split up the
2303 # title and definition, without b0rking links.
2305 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2307 $output .= $term . $this->nextItem( ':' );
2310 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2311 # We need to open or close prefixes, or both.
2313 # Either open or close a level...
2314 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2315 $paragraphStack = false;
2317 # Close all the prefixes which aren't shared.
2318 while ( $commonPrefixLength < $lastPrefixLength ) {
2319 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2320 --$lastPrefixLength;
2323 # Continue the current prefix if appropriate.
2324 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2325 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2328 # Open prefixes where appropriate.
2329 while ( $prefixLength > $commonPrefixLength ) {
2330 $char = substr( $prefix, $commonPrefixLength, 1 );
2331 $output .= $this->openList( $char );
2333 if ( ';' === $char ) {
2334 # @todo FIXME: This is dupe of code above
2335 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2337 $output .= $term . $this->nextItem( ':' );
2340 ++
$commonPrefixLength;
2342 $lastPrefix = $prefix2;
2345 # If we have no prefixes, go to paragraph mode.
2346 if ( 0 == $prefixLength ) {
2347 wfProfileIn( __METHOD__
."-paragraph" );
2348 # No prefix (not in list)--go to paragraph mode
2349 # XXX: use a stack for nestable elements like span, table and div
2350 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2351 $closematch = preg_match(
2352 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2353 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2354 if ( $openmatch or $closematch ) {
2355 $paragraphStack = false;
2356 # TODO bug 5718: paragraph closed
2357 $output .= $this->closeParagraph();
2358 if ( $preOpenMatch and !$preCloseMatch ) {
2359 $this->mInPre
= true;
2361 $inBlockElem = !$closematch;
2362 } elseif ( !$inBlockElem && !$this->mInPre
) {
2363 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2365 if ( $this->mLastSection
!== 'pre' ) {
2366 $paragraphStack = false;
2367 $output .= $this->closeParagraph().'<pre>';
2368 $this->mLastSection
= 'pre';
2370 $t = substr( $t, 1 );
2373 if ( trim( $t ) === '' ) {
2374 if ( $paragraphStack ) {
2375 $output .= $paragraphStack.'<br />';
2376 $paragraphStack = false;
2377 $this->mLastSection
= 'p';
2379 if ( $this->mLastSection
!== 'p' ) {
2380 $output .= $this->closeParagraph();
2381 $this->mLastSection
= '';
2382 $paragraphStack = '<p>';
2384 $paragraphStack = '</p><p>';
2388 if ( $paragraphStack ) {
2389 $output .= $paragraphStack;
2390 $paragraphStack = false;
2391 $this->mLastSection
= 'p';
2392 } elseif ( $this->mLastSection
!== 'p' ) {
2393 $output .= $this->closeParagraph().'<p>';
2394 $this->mLastSection
= 'p';
2399 wfProfileOut( __METHOD__
."-paragraph" );
2401 # somewhere above we forget to get out of pre block (bug 785)
2402 if ( $preCloseMatch && $this->mInPre
) {
2403 $this->mInPre
= false;
2405 if ( $paragraphStack === false ) {
2409 while ( $prefixLength ) {
2410 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2413 if ( $this->mLastSection
!= '' ) {
2414 $output .= '</' . $this->mLastSection
. '>';
2415 $this->mLastSection
= '';
2418 wfProfileOut( __METHOD__
);
2423 * Split up a string on ':', ignoring any occurrences inside tags
2424 * to prevent illegal overlapping.
2426 * @param $str String the string to split
2427 * @param &$before String set to everything before the ':'
2428 * @param &$after String set to everything after the ':'
2429 * @return String the position of the ':', or false if none found
2431 function findColonNoLinks( $str, &$before, &$after ) {
2432 wfProfileIn( __METHOD__
);
2434 $pos = strpos( $str, ':' );
2435 if ( $pos === false ) {
2437 wfProfileOut( __METHOD__
);
2441 $lt = strpos( $str, '<' );
2442 if ( $lt === false ||
$lt > $pos ) {
2443 # Easy; no tag nesting to worry about
2444 $before = substr( $str, 0, $pos );
2445 $after = substr( $str, $pos+
1 );
2446 wfProfileOut( __METHOD__
);
2450 # Ugly state machine to walk through avoiding tags.
2451 $state = self
::COLON_STATE_TEXT
;
2453 $len = strlen( $str );
2454 for( $i = 0; $i < $len; $i++
) {
2458 # (Using the number is a performance hack for common cases)
2459 case 0: # self::COLON_STATE_TEXT:
2462 # Could be either a <start> tag or an </end> tag
2463 $state = self
::COLON_STATE_TAGSTART
;
2466 if ( $stack == 0 ) {
2468 $before = substr( $str, 0, $i );
2469 $after = substr( $str, $i +
1 );
2470 wfProfileOut( __METHOD__
);
2473 # Embedded in a tag; don't break it.
2476 # Skip ahead looking for something interesting
2477 $colon = strpos( $str, ':', $i );
2478 if ( $colon === false ) {
2479 # Nothing else interesting
2480 wfProfileOut( __METHOD__
);
2483 $lt = strpos( $str, '<', $i );
2484 if ( $stack === 0 ) {
2485 if ( $lt === false ||
$colon < $lt ) {
2487 $before = substr( $str, 0, $colon );
2488 $after = substr( $str, $colon +
1 );
2489 wfProfileOut( __METHOD__
);
2493 if ( $lt === false ) {
2494 # Nothing else interesting to find; abort!
2495 # We're nested, but there's no close tags left. Abort!
2498 # Skip ahead to next tag start
2500 $state = self
::COLON_STATE_TAGSTART
;
2503 case 1: # self::COLON_STATE_TAG:
2508 $state = self
::COLON_STATE_TEXT
;
2511 # Slash may be followed by >?
2512 $state = self
::COLON_STATE_TAGSLASH
;
2518 case 2: # self::COLON_STATE_TAGSTART:
2521 $state = self
::COLON_STATE_CLOSETAG
;
2524 $state = self
::COLON_STATE_COMMENT
;
2527 # Illegal early close? This shouldn't happen D:
2528 $state = self
::COLON_STATE_TEXT
;
2531 $state = self
::COLON_STATE_TAG
;
2534 case 3: # self::COLON_STATE_CLOSETAG:
2539 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2540 wfProfileOut( __METHOD__
);
2543 $state = self
::COLON_STATE_TEXT
;
2546 case self
::COLON_STATE_TAGSLASH
:
2548 # Yes, a self-closed tag <blah/>
2549 $state = self
::COLON_STATE_TEXT
;
2551 # Probably we're jumping the gun, and this is an attribute
2552 $state = self
::COLON_STATE_TAG
;
2555 case 5: # self::COLON_STATE_COMMENT:
2557 $state = self
::COLON_STATE_COMMENTDASH
;
2560 case self
::COLON_STATE_COMMENTDASH
:
2562 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2564 $state = self
::COLON_STATE_COMMENT
;
2567 case self
::COLON_STATE_COMMENTDASHDASH
:
2569 $state = self
::COLON_STATE_TEXT
;
2571 $state = self
::COLON_STATE_COMMENT
;
2575 throw new MWException( "State machine error in " . __METHOD__
);
2579 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2580 wfProfileOut( __METHOD__
);
2583 wfProfileOut( __METHOD__
);
2588 * Return value of a magic variable (like PAGENAME)
2592 * @param $index integer
2593 * @param $frame PPFrame
2597 function getVariableValue( $index, $frame = false ) {
2598 global $wgContLang, $wgSitename, $wgServer;
2599 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2601 if ( is_null( $this->mTitle
) ) {
2602 // If no title set, bad things are going to happen
2603 // later. Title should always be set since this
2604 // should only be called in the middle of a parse
2605 // operation (but the unit-tests do funky stuff)
2606 throw new MWException( __METHOD__
. ' Should only be '
2607 . ' called while parsing (no title set)' );
2611 * Some of these require message or data lookups and can be
2612 * expensive to check many times.
2614 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2615 if ( isset( $this->mVarCache
[$index] ) ) {
2616 return $this->mVarCache
[$index];
2620 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2621 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2624 global $wgLocaltimezone;
2625 if ( isset( $wgLocaltimezone ) ) {
2626 $oldtz = date_default_timezone_get();
2627 date_default_timezone_set( $wgLocaltimezone );
2630 $localTimestamp = date( 'YmdHis', $ts );
2631 $localMonth = date( 'm', $ts );
2632 $localMonth1 = date( 'n', $ts );
2633 $localMonthName = date( 'n', $ts );
2634 $localDay = date( 'j', $ts );
2635 $localDay2 = date( 'd', $ts );
2636 $localDayOfWeek = date( 'w', $ts );
2637 $localWeek = date( 'W', $ts );
2638 $localYear = date( 'Y', $ts );
2639 $localHour = date( 'H', $ts );
2640 if ( isset( $wgLocaltimezone ) ) {
2641 date_default_timezone_set( $oldtz );
2644 $pageLang = $this->getFunctionLang();
2647 case 'currentmonth':
2648 $value = $pageLang->formatNum( gmdate( 'm', $ts ) );
2650 case 'currentmonth1':
2651 $value = $pageLang->formatNum( gmdate( 'n', $ts ) );
2653 case 'currentmonthname':
2654 $value = $pageLang->getMonthName( gmdate( 'n', $ts ) );
2656 case 'currentmonthnamegen':
2657 $value = $pageLang->getMonthNameGen( gmdate( 'n', $ts ) );
2659 case 'currentmonthabbrev':
2660 $value = $pageLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2663 $value = $pageLang->formatNum( gmdate( 'j', $ts ) );
2666 $value = $pageLang->formatNum( gmdate( 'd', $ts ) );
2669 $value = $pageLang->formatNum( $localMonth );
2672 $value = $pageLang->formatNum( $localMonth1 );
2674 case 'localmonthname':
2675 $value = $pageLang->getMonthName( $localMonthName );
2677 case 'localmonthnamegen':
2678 $value = $pageLang->getMonthNameGen( $localMonthName );
2680 case 'localmonthabbrev':
2681 $value = $pageLang->getMonthAbbreviation( $localMonthName );
2684 $value = $pageLang->formatNum( $localDay );
2687 $value = $pageLang->formatNum( $localDay2 );
2690 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2693 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2695 case 'fullpagename':
2696 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2698 case 'fullpagenamee':
2699 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2702 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2704 case 'subpagenamee':
2705 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2707 case 'basepagename':
2708 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2710 case 'basepagenamee':
2711 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2713 case 'talkpagename':
2714 if ( $this->mTitle
->canTalk() ) {
2715 $talkPage = $this->mTitle
->getTalkPage();
2716 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2721 case 'talkpagenamee':
2722 if ( $this->mTitle
->canTalk() ) {
2723 $talkPage = $this->mTitle
->getTalkPage();
2724 $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() );
2729 case 'subjectpagename':
2730 $subjPage = $this->mTitle
->getSubjectPage();
2731 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2733 case 'subjectpagenamee':
2734 $subjPage = $this->mTitle
->getSubjectPage();
2735 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() );
2737 case 'pageid': // requested in bug 23427
2738 $pageid = $this->getTitle()->getArticleId();
2739 if( $pageid == 0 ) {
2740 # 0 means the page doesn't exist in the database,
2741 # which means the user is previewing a new page.
2742 # The vary-revision flag must be set, because the magic word
2743 # will have a different value once the page is saved.
2744 $this->mOutput
->setFlag( 'vary-revision' );
2745 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2747 $value = $pageid ?
$pageid : null;
2750 # Let the edit saving system know we should parse the page
2751 # *after* a revision ID has been assigned.
2752 $this->mOutput
->setFlag( 'vary-revision' );
2753 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2754 $value = $this->mRevisionId
;
2757 # Let the edit saving system know we should parse the page
2758 # *after* a revision ID has been assigned. This is for null edits.
2759 $this->mOutput
->setFlag( 'vary-revision' );
2760 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2761 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2763 case 'revisionday2':
2764 # Let the edit saving system know we should parse the page
2765 # *after* a revision ID has been assigned. This is for null edits.
2766 $this->mOutput
->setFlag( 'vary-revision' );
2767 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2768 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2770 case 'revisionmonth':
2771 # Let the edit saving system know we should parse the page
2772 # *after* a revision ID has been assigned. This is for null edits.
2773 $this->mOutput
->setFlag( 'vary-revision' );
2774 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2775 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2777 case 'revisionmonth1':
2778 # Let the edit saving system know we should parse the page
2779 # *after* a revision ID has been assigned. This is for null edits.
2780 $this->mOutput
->setFlag( 'vary-revision' );
2781 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2782 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2784 case 'revisionyear':
2785 # Let the edit saving system know we should parse the page
2786 # *after* a revision ID has been assigned. This is for null edits.
2787 $this->mOutput
->setFlag( 'vary-revision' );
2788 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2789 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2791 case 'revisiontimestamp':
2792 # Let the edit saving system know we should parse the page
2793 # *after* a revision ID has been assigned. This is for null edits.
2794 $this->mOutput
->setFlag( 'vary-revision' );
2795 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2796 $value = $this->getRevisionTimestamp();
2798 case 'revisionuser':
2799 # Let the edit saving system know we should parse the page
2800 # *after* a revision ID has been assigned. This is for null edits.
2801 $this->mOutput
->setFlag( 'vary-revision' );
2802 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2803 $value = $this->getRevisionUser();
2806 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2809 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2811 case 'namespacenumber':
2812 $value = $this->mTitle
->getNamespace();
2815 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2818 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2820 case 'subjectspace':
2821 $value = $this->mTitle
->getSubjectNsText();
2823 case 'subjectspacee':
2824 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2826 case 'currentdayname':
2827 $value = $pageLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2830 $value = $pageLang->formatNum( gmdate( 'Y', $ts ), true );
2833 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2836 $value = $pageLang->formatNum( gmdate( 'H', $ts ), true );
2839 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2840 # int to remove the padding
2841 $value = $pageLang->formatNum( (int)gmdate( 'W', $ts ) );
2844 $value = $pageLang->formatNum( gmdate( 'w', $ts ) );
2846 case 'localdayname':
2847 $value = $pageLang->getWeekdayName( $localDayOfWeek +
1 );
2850 $value = $pageLang->formatNum( $localYear, true );
2853 $value = $pageLang->time( $localTimestamp, false, false );
2856 $value = $pageLang->formatNum( $localHour, true );
2859 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2860 # int to remove the padding
2861 $value = $pageLang->formatNum( (int)$localWeek );
2864 $value = $pageLang->formatNum( $localDayOfWeek );
2866 case 'numberofarticles':
2867 $value = $pageLang->formatNum( SiteStats
::articles() );
2869 case 'numberoffiles':
2870 $value = $pageLang->formatNum( SiteStats
::images() );
2872 case 'numberofusers':
2873 $value = $pageLang->formatNum( SiteStats
::users() );
2875 case 'numberofactiveusers':
2876 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2878 case 'numberofpages':
2879 $value = $pageLang->formatNum( SiteStats
::pages() );
2881 case 'numberofadmins':
2882 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2884 case 'numberofedits':
2885 $value = $pageLang->formatNum( SiteStats
::edits() );
2887 case 'numberofviews':
2888 global $wgDisableCounters;
2889 $value = !$wgDisableCounters ?
$pageLang->formatNum( SiteStats
::views() ) : '';
2891 case 'currenttimestamp':
2892 $value = wfTimestamp( TS_MW
, $ts );
2894 case 'localtimestamp':
2895 $value = $localTimestamp;
2897 case 'currentversion':
2898 $value = SpecialVersion
::getVersion();
2901 return $wgArticlePath;
2907 $serverParts = wfParseUrl( $wgServer );
2908 return $serverParts && isset( $serverParts['host'] ) ?
$serverParts['host'] : $wgServer;
2910 return $wgScriptPath;
2912 return $wgStylePath;
2913 case 'directionmark':
2914 return $pageLang->getDirMark();
2915 case 'contentlanguage':
2916 global $wgLanguageCode;
2917 return $wgLanguageCode;
2920 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2928 $this->mVarCache
[$index] = $value;
2935 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2939 function initialiseVariables() {
2940 wfProfileIn( __METHOD__
);
2941 $variableIDs = MagicWord
::getVariableIDs();
2942 $substIDs = MagicWord
::getSubstIDs();
2944 $this->mVariables
= new MagicWordArray( $variableIDs );
2945 $this->mSubstWords
= new MagicWordArray( $substIDs );
2946 wfProfileOut( __METHOD__
);
2950 * Preprocess some wikitext and return the document tree.
2951 * This is the ghost of replace_variables().
2953 * @param $text String: The text to parse
2954 * @param $flags Integer: bitwise combination of:
2955 * self::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
2956 * included. Default is to assume a direct page view.
2958 * The generated DOM tree must depend only on the input text and the flags.
2959 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2961 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2962 * change in the DOM tree for a given text, must be passed through the section identifier
2963 * in the section edit link and thus back to extractSections().
2965 * The output of this function is currently only cached in process memory, but a persistent
2966 * cache may be implemented at a later date which takes further advantage of these strict
2967 * dependency requirements.
2973 function preprocessToDom( $text, $flags = 0 ) {
2974 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2979 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2985 public static function splitWhitespace( $s ) {
2986 $ltrimmed = ltrim( $s );
2987 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2988 $trimmed = rtrim( $ltrimmed );
2989 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2991 $w2 = substr( $ltrimmed, -$diff );
2995 return array( $w1, $trimmed, $w2 );
2999 * Replace magic variables, templates, and template arguments
3000 * with the appropriate text. Templates are substituted recursively,
3001 * taking care to avoid infinite loops.
3003 * Note that the substitution depends on value of $mOutputType:
3004 * self::OT_WIKI: only {{subst:}} templates
3005 * self::OT_PREPROCESS: templates but not extension tags
3006 * self::OT_HTML: all templates and extension tags
3008 * @param $text String the text to transform
3009 * @param $frame PPFrame Object describing the arguments passed to the template.
3010 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
3011 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
3012 * @param $argsOnly Boolean only do argument (triple-brace) expansion, not double-brace expansion
3017 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3018 # Is there any text? Also, Prevent too big inclusions!
3019 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3022 wfProfileIn( __METHOD__
);
3024 if ( $frame === false ) {
3025 $frame = $this->getPreprocessor()->newFrame();
3026 } elseif ( !( $frame instanceof PPFrame
) ) {
3027 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
3028 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3031 $dom = $this->preprocessToDom( $text );
3032 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3033 $text = $frame->expand( $dom, $flags );
3035 wfProfileOut( __METHOD__
);
3040 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3042 * @param $args array
3046 static function createAssocArgs( $args ) {
3047 $assocArgs = array();
3049 foreach ( $args as $arg ) {
3050 $eqpos = strpos( $arg, '=' );
3051 if ( $eqpos === false ) {
3052 $assocArgs[$index++
] = $arg;
3054 $name = trim( substr( $arg, 0, $eqpos ) );
3055 $value = trim( substr( $arg, $eqpos+
1 ) );
3056 if ( $value === false ) {
3059 if ( $name !== false ) {
3060 $assocArgs[$name] = $value;
3069 * Warn the user when a parser limitation is reached
3070 * Will warn at most once the user per limitation type
3072 * @param $limitationType String: should be one of:
3073 * 'expensive-parserfunction' (corresponding messages:
3074 * 'expensive-parserfunction-warning',
3075 * 'expensive-parserfunction-category')
3076 * 'post-expand-template-argument' (corresponding messages:
3077 * 'post-expand-template-argument-warning',
3078 * 'post-expand-template-argument-category')
3079 * 'post-expand-template-inclusion' (corresponding messages:
3080 * 'post-expand-template-inclusion-warning',
3081 * 'post-expand-template-inclusion-category')
3082 * @param $current int|null Current value
3083 * @param $max int|null Maximum allowed, when an explicit limit has been
3084 * exceeded, provide the values (optional)
3086 function limitationWarn( $limitationType, $current = null, $max = null) {
3087 # does no harm if $current and $max are present but are unnecessary for the message
3088 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
3089 $this->mOutput
->addWarning( $warning );
3090 $this->addTrackingCategory( "$limitationType-category" );
3094 * Return the text of a template, after recursively
3095 * replacing any variables or templates within the template.
3097 * @param $piece Array: the parts of the template
3098 * $piece['title']: the title, i.e. the part before the |
3099 * $piece['parts']: the parameter array
3100 * $piece['lineStart']: whether the brace was at the start of a line
3101 * @param $frame PPFrame The current frame, contains template arguments
3102 * @return String: the text of the template
3105 function braceSubstitution( $piece, $frame ) {
3107 wfProfileIn( __METHOD__
);
3108 wfProfileIn( __METHOD__
.'-setup' );
3111 $found = false; # $text has been filled
3112 $nowiki = false; # wiki markup in $text should be escaped
3113 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3114 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3115 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3116 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3118 # Title object, where $text came from
3121 # $part1 is the bit before the first |, and must contain only title characters.
3122 # Various prefixes will be stripped from it later.
3123 $titleWithSpaces = $frame->expand( $piece['title'] );
3124 $part1 = trim( $titleWithSpaces );
3127 # Original title text preserved for various purposes
3128 $originalTitle = $part1;
3130 # $args is a list of argument nodes, starting from index 0, not including $part1
3131 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3132 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3133 wfProfileOut( __METHOD__
.'-setup' );
3135 $titleProfileIn = null; // profile templates
3138 wfProfileIn( __METHOD__
.'-modifiers' );
3141 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3143 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3144 # Decide whether to expand template or keep wikitext as-is.
3145 if ( $this->ot
['wiki'] ) {
3146 if ( $substMatch === false ) {
3147 $literal = true; # literal when in PST with no prefix
3149 $literal = false; # expand when in PST with subst: or safesubst:
3152 if ( $substMatch == 'subst' ) {
3153 $literal = true; # literal when not in PST with plain subst:
3155 $literal = false; # expand when not in PST with safesubst: or no prefix
3159 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3166 if ( !$found && $args->getLength() == 0 ) {
3167 $id = $this->mVariables
->matchStartToEnd( $part1 );
3168 if ( $id !== false ) {
3169 $text = $this->getVariableValue( $id, $frame );
3170 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3171 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3177 # MSG, MSGNW and RAW
3180 $mwMsgnw = MagicWord
::get( 'msgnw' );
3181 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3184 # Remove obsolete MSG:
3185 $mwMsg = MagicWord
::get( 'msg' );
3186 $mwMsg->matchStartAndRemove( $part1 );
3190 $mwRaw = MagicWord
::get( 'raw' );
3191 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3192 $forceRawInterwiki = true;
3195 wfProfileOut( __METHOD__
.'-modifiers' );
3199 wfProfileIn( __METHOD__
. '-pfunc' );
3201 $colonPos = strpos( $part1, ':' );
3202 if ( $colonPos !== false ) {
3203 # Case sensitive functions
3204 $function = substr( $part1, 0, $colonPos );
3205 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3206 $function = $this->mFunctionSynonyms
[1][$function];
3208 # Case insensitive functions
3209 $function = $wgContLang->lc( $function );
3210 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3211 $function = $this->mFunctionSynonyms
[0][$function];
3217 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3218 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3219 $initialArgs = array( &$this );
3220 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3221 if ( $flags & SFH_OBJECT_ARGS
) {
3222 # Add a frame parameter, and pass the arguments as an array
3223 $allArgs = $initialArgs;
3224 $allArgs[] = $frame;
3225 for ( $i = 0; $i < $args->getLength(); $i++
) {
3226 $funcArgs[] = $args->item( $i );
3228 $allArgs[] = $funcArgs;
3230 # Convert arguments to plain text
3231 for ( $i = 0; $i < $args->getLength(); $i++
) {
3232 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3234 $allArgs = array_merge( $initialArgs, $funcArgs );
3237 # Workaround for PHP bug 35229 and similar
3238 if ( !is_callable( $callback ) ) {
3239 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3240 wfProfileOut( __METHOD__
. '-pfunc' );
3241 wfProfileOut( __METHOD__
);
3242 throw new MWException( "Tag hook for $function is not callable\n" );
3244 $result = call_user_func_array( $callback, $allArgs );
3247 $preprocessFlags = 0;
3249 if ( is_array( $result ) ) {
3250 if ( isset( $result[0] ) ) {
3252 unset( $result[0] );
3255 # Extract flags into the local scope
3256 # This allows callers to set flags such as nowiki, found, etc.
3262 $text = $this->preprocessToDom( $text, $preprocessFlags );
3265 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3268 wfProfileOut( __METHOD__
. '-pfunc' );
3271 # Finish mangling title and then check for loops.
3272 # Set $title to a Title object and $titleText to the PDBK
3275 # Split the title into page and subpage
3277 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3278 if ( $subpage !== '' ) {
3279 $ns = $this->mTitle
->getNamespace();
3281 $title = Title
::newFromText( $part1, $ns );
3283 $titleText = $title->getPrefixedText();
3284 # Check for language variants if the template is not found
3285 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3286 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3288 # Do recursion depth check
3289 $limit = $this->mOptions
->getMaxTemplateDepth();
3290 if ( $frame->depth
>= $limit ) {
3292 $text = '<span class="error">'
3293 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
3299 # Load from database
3300 if ( !$found && $title ) {
3301 if ( !Profiler
::instance()->isPersistent() ) {
3302 # Too many unique items can kill profiling DBs/collectors
3303 $titleProfileIn = __METHOD__
. "-title-" . $title->getDBKey();
3304 wfProfileIn( $titleProfileIn ); // template in
3306 wfProfileIn( __METHOD__
. '-loadtpl' );
3307 if ( !$title->isExternal() ) {
3308 if ( $title->isSpecialPage()
3309 && $this->mOptions
->getAllowSpecialInclusion()
3310 && $this->ot
['html'] )
3312 // Pass the template arguments as URL parameters.
3313 // "uselang" will have no effect since the Language object
3314 // is forced to the one defined in ParserOptions.
3315 $pageArgs = array();
3316 for ( $i = 0; $i < $args->getLength(); $i++
) {
3317 $bits = $args->item( $i )->splitArg();
3318 if ( strval( $bits['index'] ) === '' ) {
3319 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3320 $value = trim( $frame->expand( $bits['value'] ) );
3321 $pageArgs[$name] = $value;
3325 // Create a new context to execute the special page
3326 $context = new RequestContext
;
3327 $context->setTitle( $title );
3328 $context->setRequest( new FauxRequest( $pageArgs ) );
3329 $context->setUser( $this->getUser() );
3330 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3331 $ret = SpecialPageFactory
::capturePath( $title, $context );
3333 $text = $context->getOutput()->getHTML();
3334 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3337 $this->disableCache();
3339 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3340 $found = false; # access denied
3341 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3343 list( $text, $title ) = $this->getTemplateDom( $title );
3344 if ( $text !== false ) {
3350 # If the title is valid but undisplayable, make a link to it
3351 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3352 $text = "[[:$titleText]]";
3355 } elseif ( $title->isTrans() ) {
3356 # Interwiki transclusion
3357 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3358 $text = $this->interwikiTransclude( $title, 'render' );
3361 $text = $this->interwikiTransclude( $title, 'raw' );
3362 # Preprocess it like a template
3363 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3369 # Do infinite loop check
3370 # This has to be done after redirect resolution to avoid infinite loops via redirects
3371 if ( !$frame->loopCheck( $title ) ) {
3373 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3374 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3376 wfProfileOut( __METHOD__
. '-loadtpl' );
3379 # If we haven't found text to substitute by now, we're done
3380 # Recover the source wikitext and return it
3382 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3383 if ( $titleProfileIn ) {
3384 wfProfileOut( $titleProfileIn ); // template out
3386 wfProfileOut( __METHOD__
);
3387 return array( 'object' => $text );
3390 # Expand DOM-style return values in a child frame
3391 if ( $isChildObj ) {
3392 # Clean up argument array
3393 $newFrame = $frame->newChild( $args, $title );
3396 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3397 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3398 # Expansion is eligible for the empty-frame cache
3399 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3400 $text = $this->mTplExpandCache
[$titleText];
3402 $text = $newFrame->expand( $text );
3403 $this->mTplExpandCache
[$titleText] = $text;
3406 # Uncached expansion
3407 $text = $newFrame->expand( $text );
3410 if ( $isLocalObj && $nowiki ) {
3411 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3412 $isLocalObj = false;
3415 if ( $titleProfileIn ) {
3416 wfProfileOut( $titleProfileIn ); // template out
3419 # Replace raw HTML by a placeholder
3421 $text = $this->insertStripItem( $text );
3422 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3423 # Escape nowiki-style return values
3424 $text = wfEscapeWikiText( $text );
3425 } elseif ( is_string( $text )
3426 && !$piece['lineStart']
3427 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3429 # Bug 529: if the template begins with a table or block-level
3430 # element, it should be treated as beginning a new line.
3431 # This behaviour is somewhat controversial.
3432 $text = "\n" . $text;
3435 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3436 # Error, oversize inclusion
3437 if ( $titleText !== false ) {
3438 # Make a working, properly escaped link if possible (bug 23588)
3439 $text = "[[:$titleText]]";
3441 # This will probably not be a working link, but at least it may
3442 # provide some hint of where the problem is
3443 preg_replace( '/^:/', '', $originalTitle );
3444 $text = "[[:$originalTitle]]";
3446 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3447 $this->limitationWarn( 'post-expand-template-inclusion' );
3450 if ( $isLocalObj ) {
3451 $ret = array( 'object' => $text );
3453 $ret = array( 'text' => $text );
3456 wfProfileOut( __METHOD__
);
3461 * Get the semi-parsed DOM representation of a template with a given title,
3462 * and its redirect destination title. Cached.
3464 * @param $title Title
3468 function getTemplateDom( $title ) {
3469 $cacheTitle = $title;
3470 $titleText = $title->getPrefixedDBkey();
3472 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3473 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3474 $title = Title
::makeTitle( $ns, $dbk );
3475 $titleText = $title->getPrefixedDBkey();
3477 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3478 return array( $this->mTplDomCache
[$titleText], $title );
3481 # Cache miss, go to the database
3482 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3484 if ( $text === false ) {
3485 $this->mTplDomCache
[$titleText] = false;
3486 return array( false, $title );
3489 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3490 $this->mTplDomCache
[ $titleText ] = $dom;
3492 if ( !$title->equals( $cacheTitle ) ) {
3493 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3494 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3497 return array( $dom, $title );
3501 * Fetch the unparsed text of a template and register a reference to it.
3502 * @param Title $title
3503 * @return Array ( string or false, Title )
3505 function fetchTemplateAndTitle( $title ) {
3506 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3507 $stuff = call_user_func( $templateCb, $title, $this );
3508 $text = $stuff['text'];
3509 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3510 if ( isset( $stuff['deps'] ) ) {
3511 foreach ( $stuff['deps'] as $dep ) {
3512 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3515 return array( $text, $finalTitle );
3519 * Fetch the unparsed text of a template and register a reference to it.
3520 * @param Title $title
3521 * @return mixed string or false
3523 function fetchTemplate( $title ) {
3524 $rv = $this->fetchTemplateAndTitle( $title );
3529 * Static function to get a template
3530 * Can be overridden via ParserOptions::setTemplateCallback().
3532 * @param $title Title
3533 * @param $parser Parser
3537 static function statelessFetchTemplate( $title, $parser = false ) {
3538 $text = $skip = false;
3539 $finalTitle = $title;
3542 # Loop to fetch the article, with up to 1 redirect
3543 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3544 # Give extensions a chance to select the revision instead
3545 $id = false; # Assume current
3546 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3547 array( $parser, $title, &$skip, &$id ) );
3553 'page_id' => $title->getArticleID(),
3560 ? Revision
::newFromId( $id )
3561 : Revision
::newFromTitle( $title, 0, Revision
::READ_NORMAL
);
3562 $rev_id = $rev ?
$rev->getId() : 0;
3563 # If there is no current revision, there is no page
3564 if ( $id === false && !$rev ) {
3565 $linkCache = LinkCache
::singleton();
3566 $linkCache->addBadLinkObj( $title );
3571 'page_id' => $title->getArticleID(),
3572 'rev_id' => $rev_id );
3573 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3574 # We fetched a rev from a different title; register it too...
3576 'title' => $rev->getTitle(),
3577 'page_id' => $rev->getPage(),
3578 'rev_id' => $rev_id );
3582 $text = $rev->getText();
3583 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3585 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3586 if ( !$message->exists() ) {
3590 $text = $message->plain();
3594 if ( $text === false ) {
3598 $finalTitle = $title;
3599 $title = Title
::newFromRedirect( $text );
3603 'finalTitle' => $finalTitle,
3608 * Fetch a file and its title and register a reference to it.
3609 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3610 * @param Title $title
3611 * @param Array $options Array of options to RepoGroup::findFile
3614 function fetchFile( $title, $options = array() ) {
3615 $res = $this->fetchFileAndTitle( $title, $options );
3620 * Fetch a file and its title and register a reference to it.
3621 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3622 * @param Title $title
3623 * @param Array $options Array of options to RepoGroup::findFile
3624 * @return Array ( File or false, Title of file )
3626 function fetchFileAndTitle( $title, $options = array() ) {
3627 if ( isset( $options['broken'] ) ) {
3628 $file = false; // broken thumbnail forced by hook
3629 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3630 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3631 } else { // get by (name,timestamp)
3632 $file = wfFindFile( $title, $options );
3634 $time = $file ?
$file->getTimestamp() : false;
3635 $sha1 = $file ?
$file->getSha1() : false;
3636 # Register the file as a dependency...
3637 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3638 if ( $file && !$title->equals( $file->getTitle() ) ) {
3639 # Update fetched file title
3640 $title = $file->getTitle();
3641 if ( is_null( $file->getRedirectedTitle() ) ) {
3642 # This file was not a redirect, but the title does not match.
3643 # Register under the new name because otherwise the link will
3645 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3648 return array( $file, $title );
3652 * Transclude an interwiki link.
3654 * @param $title Title
3659 function interwikiTransclude( $title, $action ) {
3660 global $wgEnableScaryTranscluding;
3662 if ( !$wgEnableScaryTranscluding ) {
3663 return wfMsgForContent('scarytranscludedisabled');
3666 $url = $title->getFullUrl( "action=$action" );
3668 if ( strlen( $url ) > 255 ) {
3669 return wfMsgForContent( 'scarytranscludetoolong' );
3671 return $this->fetchScaryTemplateMaybeFromCache( $url );
3675 * @param $url string
3676 * @return Mixed|String
3678 function fetchScaryTemplateMaybeFromCache( $url ) {
3679 global $wgTranscludeCacheExpiry;
3680 $dbr = wfGetDB( DB_SLAVE
);
3681 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3682 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3683 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3685 return $obj->tc_contents
;
3688 $text = Http
::get( $url );
3690 return wfMsgForContent( 'scarytranscludefailed', $url );
3693 $dbw = wfGetDB( DB_MASTER
);
3694 $dbw->replace( 'transcache', array('tc_url'), array(
3696 'tc_time' => $dbw->timestamp( time() ),
3697 'tc_contents' => $text)
3703 * Triple brace replacement -- used for template arguments
3706 * @param $piece array
3707 * @param $frame PPFrame
3711 function argSubstitution( $piece, $frame ) {
3712 wfProfileIn( __METHOD__
);
3715 $parts = $piece['parts'];
3716 $nameWithSpaces = $frame->expand( $piece['title'] );
3717 $argName = trim( $nameWithSpaces );
3719 $text = $frame->getArgument( $argName );
3720 if ( $text === false && $parts->getLength() > 0
3724 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3727 # No match in frame, use the supplied default
3728 $object = $parts->item( 0 )->getChildren();
3730 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3731 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3732 $this->limitationWarn( 'post-expand-template-argument' );
3735 if ( $text === false && $object === false ) {
3737 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3739 if ( $error !== false ) {
3742 if ( $object !== false ) {
3743 $ret = array( 'object' => $object );
3745 $ret = array( 'text' => $text );
3748 wfProfileOut( __METHOD__
);
3753 * Return the text to be used for a given extension tag.
3754 * This is the ghost of strip().
3756 * @param $params array Associative array of parameters:
3757 * name PPNode for the tag name
3758 * attr PPNode for unparsed text where tag attributes are thought to be
3759 * attributes Optional associative array of parsed attributes
3760 * inner Contents of extension element
3761 * noClose Original text did not have a close tag
3762 * @param $frame PPFrame
3766 function extensionSubstitution( $params, $frame ) {
3767 $name = $frame->expand( $params['name'] );
3768 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3769 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3770 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3772 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3773 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3774 if ( $isFunctionTag ) {
3775 $markerType = 'none';
3777 $markerType = 'general';
3779 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3780 $name = strtolower( $name );
3781 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3782 if ( isset( $params['attributes'] ) ) {
3783 $attributes = $attributes +
$params['attributes'];
3786 if ( isset( $this->mTagHooks
[$name] ) ) {
3787 # Workaround for PHP bug 35229 and similar
3788 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3789 throw new MWException( "Tag hook for $name is not callable\n" );
3791 $output = call_user_func_array( $this->mTagHooks
[$name],
3792 array( $content, $attributes, $this, $frame ) );
3793 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3794 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3795 if ( !is_callable( $callback ) ) {
3796 throw new MWException( "Tag hook for $name is not callable\n" );
3799 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3801 $output = '<span class="error">Invalid tag extension name: ' .
3802 htmlspecialchars( $name ) . '</span>';
3805 if ( is_array( $output ) ) {
3806 # Extract flags to local scope (to override $markerType)
3808 $output = $flags[0];
3813 if ( is_null( $attrText ) ) {
3816 if ( isset( $params['attributes'] ) ) {
3817 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3818 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3819 htmlspecialchars( $attrValue ) . '"';
3822 if ( $content === null ) {
3823 $output = "<$name$attrText/>";
3825 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3826 $output = "<$name$attrText>$content$close";
3830 if ( $markerType === 'none' ) {
3832 } elseif ( $markerType === 'nowiki' ) {
3833 $this->mStripState
->addNoWiki( $marker, $output );
3834 } elseif ( $markerType === 'general' ) {
3835 $this->mStripState
->addGeneral( $marker, $output );
3837 throw new MWException( __METHOD__
.': invalid marker type' );
3843 * Increment an include size counter
3845 * @param $type String: the type of expansion
3846 * @param $size Integer: the size of the text
3847 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3849 function incrementIncludeSize( $type, $size ) {
3850 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3853 $this->mIncludeSizes
[$type] +
= $size;
3859 * Increment the expensive function count
3861 * @return Boolean: false if the limit has been exceeded
3863 function incrementExpensiveFunctionCount() {
3864 $this->mExpensiveFunctionCount++
;
3865 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
3869 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3870 * Fills $this->mDoubleUnderscores, returns the modified text
3872 * @param $text string
3876 function doDoubleUnderscore( $text ) {
3877 wfProfileIn( __METHOD__
);
3879 # The position of __TOC__ needs to be recorded
3880 $mw = MagicWord
::get( 'toc' );
3881 if ( $mw->match( $text ) ) {
3882 $this->mShowToc
= true;
3883 $this->mForceTocPosition
= true;
3885 # Set a placeholder. At the end we'll fill it in with the TOC.
3886 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3888 # Only keep the first one.
3889 $text = $mw->replace( '', $text );
3892 # Now match and remove the rest of them
3893 $mwa = MagicWord
::getDoubleUnderscoreArray();
3894 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3896 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3897 $this->mOutput
->mNoGallery
= true;
3899 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3900 $this->mShowToc
= false;
3902 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3903 $this->addTrackingCategory( 'hidden-category-category' );
3905 # (bug 8068) Allow control over whether robots index a page.
3907 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
3908 # is not desirable, the last one on the page should win.
3909 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3910 $this->mOutput
->setIndexPolicy( 'noindex' );
3911 $this->addTrackingCategory( 'noindex-category' );
3913 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3914 $this->mOutput
->setIndexPolicy( 'index' );
3915 $this->addTrackingCategory( 'index-category' );
3918 # Cache all double underscores in the database
3919 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
3920 $this->mOutput
->setProperty( $key, '' );
3923 wfProfileOut( __METHOD__
);
3928 * Add a tracking category, getting the title from a system message,
3929 * or print a debug message if the title is invalid.
3931 * @param $msg String: message key
3932 * @return Boolean: whether the addition was successful
3934 public function addTrackingCategory( $msg ) {
3935 if ( $this->mTitle
->getNamespace() === NS_SPECIAL
) {
3936 wfDebug( __METHOD__
.": Not adding tracking category $msg to special page!\n" );
3939 // Important to parse with correct title (bug 31469)
3940 $cat = wfMessage( $msg )
3941 ->title( $this->getTitle() )
3942 ->inContentLanguage()
3945 # Allow tracking categories to be disabled by setting them to "-"
3946 if ( $cat === '-' ) {
3950 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3951 if ( $containerCategory ) {
3952 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3955 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3961 * This function accomplishes several tasks:
3962 * 1) Auto-number headings if that option is enabled
3963 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3964 * 3) Add a Table of contents on the top for users who have enabled the option
3965 * 4) Auto-anchor headings
3967 * It loops through all headlines, collects the necessary data, then splits up the
3968 * string and re-inserts the newly formatted headlines.
3970 * @param $text String
3971 * @param $origText String: original, untouched wikitext
3972 * @param $isMain Boolean
3973 * @return mixed|string
3976 function formatHeadings( $text, $origText, $isMain=true ) {
3977 global $wgMaxTocLevel, $wgHtml5, $wgExperimentalHtmlIds;
3979 # Inhibit editsection links if requested in the page
3980 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3981 $maybeShowEditLink = $showEditLink = false;
3983 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
3984 $showEditLink = $this->mOptions
->getEditSection();
3986 if ( $showEditLink ) {
3987 $this->mOutput
->setEditSectionTokens( true );
3990 # Get all headlines for numbering them and adding funky stuff like [edit]
3991 # links - this is for later, but we need the number of headlines right now
3993 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3995 # if there are fewer than 4 headlines in the article, do not show TOC
3996 # unless it's been explicitly enabled.
3997 $enoughToc = $this->mShowToc
&&
3998 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4000 # Allow user to stipulate that a page should have a "new section"
4001 # link added via __NEWSECTIONLINK__
4002 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4003 $this->mOutput
->setNewSection( true );
4006 # Allow user to remove the "new section"
4007 # link via __NONEWSECTIONLINK__
4008 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4009 $this->mOutput
->hideNewSection( true );
4012 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4013 # override above conditions and always show TOC above first header
4014 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4015 $this->mShowToc
= true;
4023 # Ugh .. the TOC should have neat indentation levels which can be
4024 # passed to the skin functions. These are determined here
4028 $sublevelCount = array();
4029 $levelCount = array();
4034 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4035 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4036 $oldType = $this->mOutputType
;
4037 $this->setOutputType( self
::OT_WIKI
);
4038 $frame = $this->getPreprocessor()->newFrame();
4039 $root = $this->preprocessToDom( $origText );
4040 $node = $root->getFirstChild();
4045 foreach ( $matches[3] as $headline ) {
4046 $isTemplate = false;
4048 $sectionIndex = false;
4050 $markerMatches = array();
4051 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
4052 $serial = $markerMatches[1];
4053 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4054 $isTemplate = ( $titleText != $baseTitleText );
4055 $headline = preg_replace( "/^$markerRegex/", "", $headline );
4059 $prevlevel = $level;
4061 $level = $matches[1][$headlineCount];
4063 if ( $level > $prevlevel ) {
4064 # Increase TOC level
4066 $sublevelCount[$toclevel] = 0;
4067 if ( $toclevel<$wgMaxTocLevel ) {
4068 $prevtoclevel = $toclevel;
4069 $toc .= Linker
::tocIndent();
4072 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4073 # Decrease TOC level, find level to jump to
4075 for ( $i = $toclevel; $i > 0; $i-- ) {
4076 if ( $levelCount[$i] == $level ) {
4077 # Found last matching level
4080 } elseif ( $levelCount[$i] < $level ) {
4081 # Found first matching level below current level
4089 if ( $toclevel<$wgMaxTocLevel ) {
4090 if ( $prevtoclevel < $wgMaxTocLevel ) {
4091 # Unindent only if the previous toc level was shown :p
4092 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4093 $prevtoclevel = $toclevel;
4095 $toc .= Linker
::tocLineEnd();
4099 # No change in level, end TOC line
4100 if ( $toclevel<$wgMaxTocLevel ) {
4101 $toc .= Linker
::tocLineEnd();
4105 $levelCount[$toclevel] = $level;
4107 # count number of headlines for each level
4108 @$sublevelCount[$toclevel]++
;
4110 for( $i = 1; $i <= $toclevel; $i++
) {
4111 if ( !empty( $sublevelCount[$i] ) ) {
4115 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4120 # The safe header is a version of the header text safe to use for links
4122 # Remove link placeholders by the link text.
4123 # <!--LINK number-->
4125 # link text with suffix
4126 # Do this before unstrip since link text can contain strip markers
4127 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4129 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4130 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4132 # Strip out HTML (first regex removes any tag not allowed)
4133 # Allowed tags are <sup> and <sub> (bug 8393), <i> (bug 26375) and <b> (r105284)
4134 # We strip any parameter from accepted tags (second regex)
4135 $tocline = preg_replace(
4136 array( '#<(?!/?(sup|sub|i|b)(?: [^>]*)?>).*?'.'>#', '#<(/?(sup|sub|i|b))(?: .*?)?'.'>#' ),
4137 array( '', '<$1>' ),
4140 $tocline = trim( $tocline );
4142 # For the anchor, strip out HTML-y stuff period
4143 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
4144 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4146 # Save headline for section edit hint before it's escaped
4147 $headlineHint = $safeHeadline;
4149 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
4150 # For reverse compatibility, provide an id that's
4151 # HTML4-compatible, like we used to.
4153 # It may be worth noting, academically, that it's possible for
4154 # the legacy anchor to conflict with a non-legacy headline
4155 # anchor on the page. In this case likely the "correct" thing
4156 # would be to either drop the legacy anchors or make sure
4157 # they're numbered first. However, this would require people
4158 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4159 # manually, so let's not bother worrying about it.
4160 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4161 array( 'noninitial', 'legacy' ) );
4162 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4164 if ( $legacyHeadline == $safeHeadline ) {
4165 # No reason to have both (in fact, we can't)
4166 $legacyHeadline = false;
4169 $legacyHeadline = false;
4170 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4174 # HTML names must be case-insensitively unique (bug 10721).
4175 # This does not apply to Unicode characters per
4176 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4177 # @todo FIXME: We may be changing them depending on the current locale.
4178 $arrayKey = strtolower( $safeHeadline );
4179 if ( $legacyHeadline === false ) {
4180 $legacyArrayKey = false;
4182 $legacyArrayKey = strtolower( $legacyHeadline );
4185 # count how many in assoc. array so we can track dupes in anchors
4186 if ( isset( $refers[$arrayKey] ) ) {
4187 $refers[$arrayKey]++
;
4189 $refers[$arrayKey] = 1;
4191 if ( isset( $refers[$legacyArrayKey] ) ) {
4192 $refers[$legacyArrayKey]++
;
4194 $refers[$legacyArrayKey] = 1;
4197 # Don't number the heading if it is the only one (looks silly)
4198 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4199 # the two are different if the line contains a link
4200 $headline = Html
::element( 'span', array( 'class' => 'mw-headline-number' ), $numbering ) . ' ' . $headline;
4203 # Create the anchor for linking from the TOC to the section
4204 $anchor = $safeHeadline;
4205 $legacyAnchor = $legacyHeadline;
4206 if ( $refers[$arrayKey] > 1 ) {
4207 $anchor .= '_' . $refers[$arrayKey];
4209 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4210 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4212 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4213 $toc .= Linker
::tocLine( $anchor, $tocline,
4214 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4217 # Add the section to the section tree
4218 # Find the DOM node for this header
4219 while ( $node && !$isTemplate ) {
4220 if ( $node->getName() === 'h' ) {
4221 $bits = $node->splitHeading();
4222 if ( $bits['i'] == $sectionIndex ) {
4226 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4227 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4228 $node = $node->getNextSibling();
4231 'toclevel' => $toclevel,
4234 'number' => $numbering,
4235 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4236 'fromtitle' => $titleText,
4237 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
4238 'anchor' => $anchor,
4241 # give headline the correct <h#> tag
4242 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4243 // Output edit section links as markers with styles that can be customized by skins
4244 if ( $isTemplate ) {
4245 # Put a T flag in the section identifier, to indicate to extractSections()
4246 # that sections inside <includeonly> should be counted.
4247 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4249 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
4251 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4252 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4253 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4254 // so we don't have to worry about a user trying to input one of these markers directly.
4255 // We use a page and section attribute to stop the language converter from converting these important bits
4256 // of data, but put the headline hint inside a content block because the language converter is supposed to
4257 // be able to convert that piece of data.
4258 $editlink = '<mw:editsection page="' . htmlspecialchars($editlinkArgs[0]);
4259 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"';
4260 if ( isset($editlinkArgs[2]) ) {
4261 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4268 $head[$headlineCount] = Linker
::makeHeadline( $level,
4269 $matches['attrib'][$headlineCount], $anchor, $headline,
4270 $editlink, $legacyAnchor );
4275 $this->setOutputType( $oldType );
4277 # Never ever show TOC if no headers
4278 if ( $numVisible < 1 ) {
4283 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4284 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4286 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4287 $this->mOutput
->setTOCHTML( $toc );
4291 $this->mOutput
->setSections( $tocraw );
4294 # split up and insert constructed headlines
4295 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4298 // build an array of document sections
4299 $sections = array();
4300 foreach ( $blocks as $block ) {
4301 // $head is zero-based, sections aren't.
4302 if ( empty( $head[$i - 1] ) ) {
4303 $sections[$i] = $block;
4305 $sections[$i] = $head[$i - 1] . $block;
4309 * Send a hook, one per section.
4310 * The idea here is to be able to make section-level DIVs, but to do so in a
4311 * lower-impact, more correct way than r50769
4314 * $section : the section number
4315 * &$sectionContent : ref to the content of the section
4316 * $showEditLinks : boolean describing whether this section has an edit link
4318 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4323 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4324 // append the TOC at the beginning
4325 // Top anchor now in skin
4326 $sections[0] = $sections[0] . $toc . "\n";
4329 $full .= join( '', $sections );
4331 if ( $this->mForceTocPosition
) {
4332 return str_replace( '<!--MWTOC-->', $toc, $full );
4339 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4340 * conversion, substitting signatures, {{subst:}} templates, etc.
4342 * @param $text String: the text to transform
4343 * @param $title Title: the Title object for the current article
4344 * @param $user User: the User object describing the current user
4345 * @param $options ParserOptions: parsing options
4346 * @param $clearState Boolean: whether to clear the parser state first
4347 * @return String: the altered wiki markup
4349 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4350 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4351 $this->setUser( $user );
4356 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4357 if( $options->getPreSaveTransform() ) {
4358 $text = $this->pstPass2( $text, $user );
4360 $text = $this->mStripState
->unstripBoth( $text );
4362 $this->setUser( null ); #Reset
4368 * Pre-save transform helper function
4371 * @param $text string
4376 function pstPass2( $text, $user ) {
4377 global $wgContLang, $wgLocaltimezone;
4379 # Note: This is the timestamp saved as hardcoded wikitext to
4380 # the database, we use $wgContLang here in order to give
4381 # everyone the same signature and use the default one rather
4382 # than the one selected in each user's preferences.
4383 # (see also bug 12815)
4384 $ts = $this->mOptions
->getTimestamp();
4385 if ( isset( $wgLocaltimezone ) ) {
4386 $tz = $wgLocaltimezone;
4388 $tz = date_default_timezone_get();
4391 $unixts = wfTimestamp( TS_UNIX
, $ts );
4392 $oldtz = date_default_timezone_get();
4393 date_default_timezone_set( $tz );
4394 $ts = date( 'YmdHis', $unixts );
4395 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4397 # Allow translation of timezones through wiki. date() can return
4398 # whatever crap the system uses, localised or not, so we cannot
4399 # ship premade translations.
4400 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4401 $msg = wfMessage( $key )->inContentLanguage();
4402 if ( $msg->exists() ) {
4403 $tzMsg = $msg->text();
4406 date_default_timezone_set( $oldtz );
4408 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4410 # Variable replacement
4411 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4412 $text = $this->replaceVariables( $text );
4414 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4415 # which may corrupt this parser instance via its wfMsgExt( parsemag ) call-
4418 $sigText = $this->getUserSig( $user );
4419 $text = strtr( $text, array(
4421 '~~~~' => "$sigText $d",
4425 # Context links: [[|name]] and [[name (context)|]]
4426 $tc = '[' . Title
::legalChars() . ']';
4427 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4429 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4430 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]]
4431 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/"; # [[ns:page (context), context|]]
4432 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4434 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4435 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4436 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4437 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4439 $t = $this->mTitle
->getText();
4441 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4442 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4443 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4444 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4446 # if there's no context, don't bother duplicating the title
4447 $text = preg_replace( $p2, '[[\\1]]', $text );
4450 # Trim trailing whitespace
4451 $text = rtrim( $text );
4457 * Fetch the user's signature text, if any, and normalize to
4458 * validated, ready-to-insert wikitext.
4459 * If you have pre-fetched the nickname or the fancySig option, you can
4460 * specify them here to save a database query.
4461 * Do not reuse this parser instance after calling getUserSig(),
4462 * as it may have changed if it's the $wgParser.
4465 * @param $nickname String|bool nickname to use or false to use user's default nickname
4466 * @param $fancySig Boolean|null whether the nicknname is the complete signature
4467 * or null to use default value
4470 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4471 global $wgMaxSigChars;
4473 $username = $user->getName();
4475 # If not given, retrieve from the user object.
4476 if ( $nickname === false )
4477 $nickname = $user->getOption( 'nickname' );
4479 if ( is_null( $fancySig ) ) {
4480 $fancySig = $user->getBoolOption( 'fancysig' );
4483 $nickname = $nickname == null ?
$username : $nickname;
4485 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4486 $nickname = $username;
4487 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4488 } elseif ( $fancySig !== false ) {
4489 # Sig. might contain markup; validate this
4490 if ( $this->validateSig( $nickname ) !== false ) {
4491 # Validated; clean up (if needed) and return it
4492 return $this->cleanSig( $nickname, true );
4494 # Failed to validate; fall back to the default
4495 $nickname = $username;
4496 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4500 # Make sure nickname doesnt get a sig in a sig
4501 $nickname = self
::cleanSigInSig( $nickname );
4503 # If we're still here, make it a link to the user page
4504 $userText = wfEscapeWikiText( $username );
4505 $nickText = wfEscapeWikiText( $nickname );
4506 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4508 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4512 * Check that the user's signature contains no bad XML
4514 * @param $text String
4515 * @return mixed An expanded string, or false if invalid.
4517 function validateSig( $text ) {
4518 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4522 * Clean up signature text
4524 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4525 * 2) Substitute all transclusions
4527 * @param $text String
4528 * @param $parsing bool Whether we're cleaning (preferences save) or parsing
4529 * @return String: signature text
4531 public function cleanSig( $text, $parsing = false ) {
4534 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4537 # Option to disable this feature
4538 if ( !$this->mOptions
->getCleanSignatures() ) {
4542 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4543 # => Move this logic to braceSubstitution()
4544 $substWord = MagicWord
::get( 'subst' );
4545 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4546 $substText = '{{' . $substWord->getSynonym( 0 );
4548 $text = preg_replace( $substRegex, $substText, $text );
4549 $text = self
::cleanSigInSig( $text );
4550 $dom = $this->preprocessToDom( $text );
4551 $frame = $this->getPreprocessor()->newFrame();
4552 $text = $frame->expand( $dom );
4555 $text = $this->mStripState
->unstripBoth( $text );
4562 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4564 * @param $text String
4565 * @return String: signature text with /~{3,5}/ removed
4567 public static function cleanSigInSig( $text ) {
4568 $text = preg_replace( '/~{3,5}/', '', $text );
4573 * Set up some variables which are usually set up in parse()
4574 * so that an external function can call some class members with confidence
4576 * @param $title Title|null
4577 * @param $options ParserOptions
4578 * @param $outputType
4579 * @param $clearState bool
4581 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4582 $this->startParse( $title, $options, $outputType, $clearState );
4586 * @param $title Title|null
4587 * @param $options ParserOptions
4588 * @param $outputType
4589 * @param $clearState bool
4591 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4592 $this->setTitle( $title );
4593 $this->mOptions
= $options;
4594 $this->setOutputType( $outputType );
4595 if ( $clearState ) {
4596 $this->clearState();
4601 * Wrapper for preprocess()
4603 * @param $text String: the text to preprocess
4604 * @param $options ParserOptions: options
4605 * @param $title Title object or null to use $wgTitle
4608 public function transformMsg( $text, $options, $title = null ) {
4609 static $executing = false;
4611 # Guard against infinite recursion
4617 wfProfileIn( __METHOD__
);
4623 # It's not uncommon having a null $wgTitle in scripts. See r80898
4624 # Create a ghost title in such case
4625 $title = Title
::newFromText( 'Dwimmerlaik' );
4627 $text = $this->preprocess( $text, $title, $options );
4630 wfProfileOut( __METHOD__
);
4635 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4636 * The callback should have the following form:
4637 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4639 * Transform and return $text. Use $parser for any required context, e.g. use
4640 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4642 * Hooks may return extended information by returning an array, of which the
4643 * first numbered element (index 0) must be the return string, and all other
4644 * entries are extracted into local variables within an internal function
4645 * in the Parser class.
4647 * This interface (introduced r61913) appears to be undocumented, but
4648 * 'markerName' is used by some core tag hooks to override which strip
4649 * array their results are placed in. **Use great caution if attempting
4650 * this interface, as it is not documented and injudicious use could smash
4651 * private variables.**
4653 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4654 * @param $callback Mixed: the callback function (and object) to use for the tag
4655 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4657 public function setHook( $tag, $callback ) {
4658 $tag = strtolower( $tag );
4659 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4660 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4662 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4663 $this->mTagHooks
[$tag] = $callback;
4664 if ( !in_array( $tag, $this->mStripList
) ) {
4665 $this->mStripList
[] = $tag;
4672 * As setHook(), but letting the contents be parsed.
4674 * Transparent tag hooks are like regular XML-style tag hooks, except they
4675 * operate late in the transformation sequence, on HTML instead of wikitext.
4677 * This is probably obsoleted by things dealing with parser frames?
4678 * The only extension currently using it is geoserver.
4681 * @todo better document or deprecate this
4683 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4684 * @param $callback Mixed: the callback function (and object) to use for the tag
4685 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4687 function setTransparentTagHook( $tag, $callback ) {
4688 $tag = strtolower( $tag );
4689 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4690 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4692 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4693 $this->mTransparentTagHooks
[$tag] = $callback;
4699 * Remove all tag hooks
4701 function clearTagHooks() {
4702 $this->mTagHooks
= array();
4703 $this->mFunctionTagHooks
= array();
4704 $this->mStripList
= $this->mDefaultStripList
;
4708 * Create a function, e.g. {{sum:1|2|3}}
4709 * The callback function should have the form:
4710 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4712 * Or with SFH_OBJECT_ARGS:
4713 * function myParserFunction( $parser, $frame, $args ) { ... }
4715 * The callback may either return the text result of the function, or an array with the text
4716 * in element 0, and a number of flags in the other elements. The names of the flags are
4717 * specified in the keys. Valid flags are:
4718 * found The text returned is valid, stop processing the template. This
4720 * nowiki Wiki markup in the return value should be escaped
4721 * isHTML The returned text is HTML, armour it against wikitext transformation
4723 * @param $id String: The magic word ID
4724 * @param $callback Mixed: the callback function (and object) to use
4725 * @param $flags Integer: a combination of the following flags:
4726 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4728 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4729 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4730 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4731 * the arguments, and to control the way they are expanded.
4733 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4734 * arguments, for instance:
4735 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4737 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4738 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4739 * working if/when this is changed.
4741 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4744 * Please read the documentation in includes/parser/Preprocessor.php for more information
4745 * about the methods available in PPFrame and PPNode.
4747 * @return string|callback The old callback function for this name, if any
4749 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4752 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4753 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4755 # Add to function cache
4756 $mw = MagicWord
::get( $id );
4758 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4760 $synonyms = $mw->getSynonyms();
4761 $sensitive = intval( $mw->isCaseSensitive() );
4763 foreach ( $synonyms as $syn ) {
4765 if ( !$sensitive ) {
4766 $syn = $wgContLang->lc( $syn );
4769 if ( !( $flags & SFH_NO_HASH
) ) {
4772 # Remove trailing colon
4773 if ( substr( $syn, -1, 1 ) === ':' ) {
4774 $syn = substr( $syn, 0, -1 );
4776 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4782 * Get all registered function hook identifiers
4786 function getFunctionHooks() {
4787 return array_keys( $this->mFunctionHooks
);
4791 * Create a tag function, e.g. "<test>some stuff</test>".
4792 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4793 * Unlike parser functions, their content is not preprocessed.
4796 function setFunctionTagHook( $tag, $callback, $flags ) {
4797 $tag = strtolower( $tag );
4798 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4799 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4800 $this->mFunctionTagHooks
[$tag] : null;
4801 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4803 if ( !in_array( $tag, $this->mStripList
) ) {
4804 $this->mStripList
[] = $tag;
4811 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
4812 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
4813 * Placeholders created in Skin::makeLinkObj()
4815 * @param $text string
4816 * @param $options int
4818 * @return array of link CSS classes, indexed by PDBK.
4820 function replaceLinkHolders( &$text, $options = 0 ) {
4821 return $this->mLinkHolders
->replace( $text );
4825 * Replace "<!--LINK-->" link placeholders with plain text of links
4826 * (not HTML-formatted).
4828 * @param $text String
4831 function replaceLinkHoldersText( $text ) {
4832 return $this->mLinkHolders
->replaceText( $text );
4836 * Renders an image gallery from a text with one line per image.
4837 * text labels may be given by using |-style alternative text. E.g.
4838 * Image:one.jpg|The number "1"
4839 * Image:tree.jpg|A tree
4840 * given as text will return the HTML of a gallery with two images,
4841 * labeled 'The number "1"' and
4844 * @param string $text
4845 * @param array $params
4846 * @return string HTML
4848 function renderImageGallery( $text, $params ) {
4849 $ig = new ImageGallery();
4850 $ig->setContextTitle( $this->mTitle
);
4851 $ig->setShowBytes( false );
4852 $ig->setShowFilename( false );
4853 $ig->setParser( $this );
4854 $ig->setHideBadImages();
4855 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4857 if ( isset( $params['showfilename'] ) ) {
4858 $ig->setShowFilename( true );
4860 $ig->setShowFilename( false );
4862 if ( isset( $params['caption'] ) ) {
4863 $caption = $params['caption'];
4864 $caption = htmlspecialchars( $caption );
4865 $caption = $this->replaceInternalLinks( $caption );
4866 $ig->setCaptionHtml( $caption );
4868 if ( isset( $params['perrow'] ) ) {
4869 $ig->setPerRow( $params['perrow'] );
4871 if ( isset( $params['widths'] ) ) {
4872 $ig->setWidths( $params['widths'] );
4874 if ( isset( $params['heights'] ) ) {
4875 $ig->setHeights( $params['heights'] );
4878 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4880 $lines = StringUtils
::explode( "\n", $text );
4881 foreach ( $lines as $line ) {
4882 # match lines like these:
4883 # Image:someimage.jpg|This is some image
4885 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4887 if ( count( $matches ) == 0 ) {
4891 if ( strpos( $matches[0], '%' ) !== false ) {
4892 $matches[1] = rawurldecode( $matches[1] );
4894 $title = Title
::newFromText( $matches[1], NS_FILE
);
4895 if ( is_null( $title ) ) {
4896 # Bogus title. Ignore these so we don't bomb out later.
4903 if ( isset( $matches[3] ) ) {
4904 // look for an |alt= definition while trying not to break existing
4905 // captions with multiple pipes (|) in it, until a more sensible grammar
4906 // is defined for images in galleries
4908 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
4909 $parameterMatches = StringUtils
::explode('|', $matches[3]);
4910 $magicWordAlt = MagicWord
::get( 'img_alt' );
4911 $magicWordLink = MagicWord
::get( 'img_link' );
4913 foreach ( $parameterMatches as $parameterMatch ) {
4914 if ( $match = $magicWordAlt->matchVariableStartToEnd( $parameterMatch ) ) {
4915 $alt = $this->stripAltText( $match, false );
4917 elseif( $match = $magicWordLink->matchVariableStartToEnd( $parameterMatch ) ){
4918 $link = strip_tags($this->replaceLinkHoldersText($match));
4919 $chars = self
::EXT_LINK_URL_CLASS
;
4920 $prots = $this->mUrlProtocols
;
4921 //check to see if link matches an absolute url, if not then it must be a wiki link.
4922 if(!preg_match( "/^($prots)$chars+$/u", $link)){
4923 $localLinkTitle = Title
::newFromText($link);
4924 $link = $localLinkTitle->getLocalURL();
4928 // concatenate all other pipes
4929 $label .= '|' . $parameterMatch;
4932 // remove the first pipe
4933 $label = substr( $label, 1 );
4936 $ig->add( $title, $label, $alt ,$link);
4938 return $ig->toHTML();
4945 function getImageParams( $handler ) {
4947 $handlerClass = get_class( $handler );
4951 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4952 # Initialise static lists
4953 static $internalParamNames = array(
4954 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4955 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4956 'bottom', 'text-bottom' ),
4957 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4958 'upright', 'border', 'link', 'alt' ),
4960 static $internalParamMap;
4961 if ( !$internalParamMap ) {
4962 $internalParamMap = array();
4963 foreach ( $internalParamNames as $type => $names ) {
4964 foreach ( $names as $name ) {
4965 $magicName = str_replace( '-', '_', "img_$name" );
4966 $internalParamMap[$magicName] = array( $type, $name );
4971 # Add handler params
4972 $paramMap = $internalParamMap;
4974 $handlerParamMap = $handler->getParamMap();
4975 foreach ( $handlerParamMap as $magic => $paramName ) {
4976 $paramMap[$magic] = array( 'handler', $paramName );
4979 $this->mImageParams
[$handlerClass] = $paramMap;
4980 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4982 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4986 * Parse image options text and use it to make an image
4988 * @param $title Title
4989 * @param $options String
4990 * @param $holders LinkHolderArray|bool
4991 * @return string HTML
4993 function makeImage( $title, $options, $holders = false ) {
4994 # Check if the options text is of the form "options|alt text"
4996 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4997 # * left no resizing, just left align. label is used for alt= only
4998 # * right same, but right aligned
4999 # * none same, but not aligned
5000 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5001 # * center center the image
5002 # * frame Keep original image size, no magnify-button.
5003 # * framed Same as "frame"
5004 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5005 # * upright reduce width for upright images, rounded to full __0 px
5006 # * border draw a 1px border around the image
5007 # * alt Text for HTML alt attribute (defaults to empty)
5008 # * link Set the target of the image link. Can be external, interwiki, or local
5009 # vertical-align values (no % or length right now):
5019 $parts = StringUtils
::explode( "|", $options );
5021 # Give extensions a chance to select the file revision for us
5024 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5025 array( $this, $title, &$options, &$descQuery ) );
5026 # Fetch and register the file (file title may be different via hooks)
5027 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5030 $handler = $file ?
$file->getHandler() : false;
5032 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5035 $this->addTrackingCategory( 'broken-file-category' );
5038 # Process the input parameters
5040 $params = array( 'frame' => array(), 'handler' => array(),
5041 'horizAlign' => array(), 'vertAlign' => array() );
5042 foreach ( $parts as $part ) {
5043 $part = trim( $part );
5044 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5046 if ( isset( $paramMap[$magicName] ) ) {
5047 list( $type, $paramName ) = $paramMap[$magicName];
5049 # Special case; width and height come in one variable together
5050 if ( $type === 'handler' && $paramName === 'width' ) {
5051 $parsedWidthParam = $this->parseWidthParam( $value );
5052 if( isset( $parsedWidthParam['width'] ) ) {
5053 $width = $parsedWidthParam['width'];
5054 if ( $handler->validateParam( 'width', $width ) ) {
5055 $params[$type]['width'] = $width;
5059 if( isset( $parsedWidthParam['height'] ) ) {
5060 $height = $parsedWidthParam['height'];
5061 if ( $handler->validateParam( 'height', $height ) ) {
5062 $params[$type]['height'] = $height;
5066 # else no validation -- bug 13436
5068 if ( $type === 'handler' ) {
5069 # Validate handler parameter
5070 $validated = $handler->validateParam( $paramName, $value );
5072 # Validate internal parameters
5073 switch( $paramName ) {
5076 # @todo FIXME: Possibly check validity here for
5077 # manualthumb? downstream behavior seems odd with
5078 # missing manual thumbs.
5080 $value = $this->stripAltText( $value, $holders );
5083 $chars = self
::EXT_LINK_URL_CLASS
;
5084 $prots = $this->mUrlProtocols
;
5085 if ( $value === '' ) {
5086 $paramName = 'no-link';
5089 } elseif ( preg_match( "/^$prots/", $value ) ) {
5090 if ( preg_match( "/^($prots)$chars+$/u", $value, $m ) ) {
5091 $paramName = 'link-url';
5092 $this->mOutput
->addExternalLink( $value );
5093 if ( $this->mOptions
->getExternalLinkTarget() ) {
5094 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5099 $linkTitle = Title
::newFromText( $value );
5101 $paramName = 'link-title';
5102 $value = $linkTitle;
5103 $this->mOutput
->addLink( $linkTitle );
5109 # Most other things appear to be empty or numeric...
5110 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5115 $params[$type][$paramName] = $value;
5119 if ( !$validated ) {
5124 # Process alignment parameters
5125 if ( $params['horizAlign'] ) {
5126 $params['frame']['align'] = key( $params['horizAlign'] );
5128 if ( $params['vertAlign'] ) {
5129 $params['frame']['valign'] = key( $params['vertAlign'] );
5132 $params['frame']['caption'] = $caption;
5134 # Will the image be presented in a frame, with the caption below?
5135 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5136 isset( $params['frame']['framed'] ) ||
5137 isset( $params['frame']['thumbnail'] ) ||
5138 isset( $params['frame']['manualthumb'] );
5140 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5141 # came to also set the caption, ordinary text after the image -- which
5142 # makes no sense, because that just repeats the text multiple times in
5143 # screen readers. It *also* came to set the title attribute.
5145 # Now that we have an alt attribute, we should not set the alt text to
5146 # equal the caption: that's worse than useless, it just repeats the
5147 # text. This is the framed/thumbnail case. If there's no caption, we
5148 # use the unnamed parameter for alt text as well, just for the time be-
5149 # ing, if the unnamed param is set and the alt param is not.
5151 # For the future, we need to figure out if we want to tweak this more,
5152 # e.g., introducing a title= parameter for the title; ignoring the un-
5153 # named parameter entirely for images without a caption; adding an ex-
5154 # plicit caption= parameter and preserving the old magic unnamed para-
5156 if ( $imageIsFramed ) { # Framed image
5157 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5158 # No caption or alt text, add the filename as the alt text so
5159 # that screen readers at least get some description of the image
5160 $params['frame']['alt'] = $title->getText();
5162 # Do not set $params['frame']['title'] because tooltips don't make sense
5164 } else { # Inline image
5165 if ( !isset( $params['frame']['alt'] ) ) {
5166 # No alt text, use the "caption" for the alt text
5167 if ( $caption !== '') {
5168 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5170 # No caption, fall back to using the filename for the
5172 $params['frame']['alt'] = $title->getText();
5175 # Use the "caption" for the tooltip text
5176 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5179 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5181 # Linker does the rest
5182 $time = isset( $options['time'] ) ?
$options['time'] : false;
5183 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5184 $time, $descQuery, $this->mOptions
->getThumbSize() );
5186 # Give the handler a chance to modify the parser object
5188 $handler->parserTransformHook( $this, $file );
5196 * @param $holders LinkHolderArray
5197 * @return mixed|String
5199 protected function stripAltText( $caption, $holders ) {
5200 # Strip bad stuff out of the title (tooltip). We can't just use
5201 # replaceLinkHoldersText() here, because if this function is called
5202 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5204 $tooltip = $holders->replaceText( $caption );
5206 $tooltip = $this->replaceLinkHoldersText( $caption );
5209 # make sure there are no placeholders in thumbnail attributes
5210 # that are later expanded to html- so expand them now and
5212 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5213 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5219 * Set a flag in the output object indicating that the content is dynamic and
5220 * shouldn't be cached.
5222 function disableCache() {
5223 wfDebug( "Parser output marked as uncacheable.\n" );
5224 if ( !$this->mOutput
) {
5225 throw new MWException( __METHOD__
.
5226 " can only be called when actually parsing something" );
5228 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5229 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5233 * Callback from the Sanitizer for expanding items found in HTML attribute
5234 * values, so they can be safely tested and escaped.
5236 * @param $text String
5237 * @param $frame PPFrame
5240 function attributeStripCallback( &$text, $frame = false ) {
5241 $text = $this->replaceVariables( $text, $frame );
5242 $text = $this->mStripState
->unstripBoth( $text );
5251 function getTags() {
5252 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
), array_keys( $this->mFunctionTagHooks
) );
5256 * Replace transparent tags in $text with the values given by the callbacks.
5258 * Transparent tag hooks are like regular XML-style tag hooks, except they
5259 * operate late in the transformation sequence, on HTML instead of wikitext.
5261 * @param $text string
5265 function replaceTransparentTags( $text ) {
5267 $elements = array_keys( $this->mTransparentTagHooks
);
5268 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5269 $replacements = array();
5271 foreach ( $matches as $marker => $data ) {
5272 list( $element, $content, $params, $tag ) = $data;
5273 $tagName = strtolower( $element );
5274 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5275 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
5279 $replacements[$marker] = $output;
5281 return strtr( $text, $replacements );
5285 * Break wikitext input into sections, and either pull or replace
5286 * some particular section's text.
5288 * External callers should use the getSection and replaceSection methods.
5290 * @param $text String: Page wikitext
5291 * @param $section String: a section identifier string of the form:
5292 * "<flag1> - <flag2> - ... - <section number>"
5294 * Currently the only recognised flag is "T", which means the target section number
5295 * was derived during a template inclusion parse, in other words this is a template
5296 * section edit link. If no flags are given, it was an ordinary section edit link.
5297 * This flag is required to avoid a section numbering mismatch when a section is
5298 * enclosed by "<includeonly>" (bug 6563).
5300 * The section number 0 pulls the text before the first heading; other numbers will
5301 * pull the given section along with its lower-level subsections. If the section is
5302 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5304 * Section 0 is always considered to exist, even if it only contains the empty
5305 * string. If $text is the empty string and section 0 is replaced, $newText is
5308 * @param $mode String: one of "get" or "replace"
5309 * @param $newText String: replacement text for section data.
5310 * @return String: for "get", the extracted section text.
5311 * for "replace", the whole page with the section replaced.
5313 private function extractSections( $text, $section, $mode, $newText='' ) {
5314 global $wgTitle; # not generally used but removes an ugly failure mode
5315 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5317 $frame = $this->getPreprocessor()->newFrame();
5319 # Process section extraction flags
5321 $sectionParts = explode( '-', $section );
5322 $sectionIndex = array_pop( $sectionParts );
5323 foreach ( $sectionParts as $part ) {
5324 if ( $part === 'T' ) {
5325 $flags |
= self
::PTD_FOR_INCLUSION
;
5329 # Check for empty input
5330 if ( strval( $text ) === '' ) {
5331 # Only sections 0 and T-0 exist in an empty document
5332 if ( $sectionIndex == 0 ) {
5333 if ( $mode === 'get' ) {
5339 if ( $mode === 'get' ) {
5347 # Preprocess the text
5348 $root = $this->preprocessToDom( $text, $flags );
5350 # <h> nodes indicate section breaks
5351 # They can only occur at the top level, so we can find them by iterating the root's children
5352 $node = $root->getFirstChild();
5354 # Find the target section
5355 if ( $sectionIndex == 0 ) {
5356 # Section zero doesn't nest, level=big
5357 $targetLevel = 1000;
5360 if ( $node->getName() === 'h' ) {
5361 $bits = $node->splitHeading();
5362 if ( $bits['i'] == $sectionIndex ) {
5363 $targetLevel = $bits['level'];
5367 if ( $mode === 'replace' ) {
5368 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5370 $node = $node->getNextSibling();
5376 if ( $mode === 'get' ) {
5383 # Find the end of the section, including nested sections
5385 if ( $node->getName() === 'h' ) {
5386 $bits = $node->splitHeading();
5387 $curLevel = $bits['level'];
5388 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5392 if ( $mode === 'get' ) {
5393 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5395 $node = $node->getNextSibling();
5398 # Write out the remainder (in replace mode only)
5399 if ( $mode === 'replace' ) {
5400 # Output the replacement text
5401 # Add two newlines on -- trailing whitespace in $newText is conventionally
5402 # stripped by the editor, so we need both newlines to restore the paragraph gap
5403 # Only add trailing whitespace if there is newText
5404 if ( $newText != "" ) {
5405 $outText .= $newText . "\n\n";
5409 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5410 $node = $node->getNextSibling();
5414 if ( is_string( $outText ) ) {
5415 # Re-insert stripped tags
5416 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5423 * This function returns the text of a section, specified by a number ($section).
5424 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5425 * the first section before any such heading (section 0).
5427 * If a section contains subsections, these are also returned.
5429 * @param $text String: text to look in
5430 * @param $section String: section identifier
5431 * @param $deftext String: default to return if section is not found
5432 * @return string text of the requested section
5434 public function getSection( $text, $section, $deftext='' ) {
5435 return $this->extractSections( $text, $section, "get", $deftext );
5439 * This function returns $oldtext after the content of the section
5440 * specified by $section has been replaced with $text. If the target
5441 * section does not exist, $oldtext is returned unchanged.
5443 * @param $oldtext String: former text of the article
5444 * @param $section int section identifier
5445 * @param $text String: replacing text
5446 * @return String: modified text
5448 public function replaceSection( $oldtext, $section, $text ) {
5449 return $this->extractSections( $oldtext, $section, "replace", $text );
5453 * Get the ID of the revision we are parsing
5455 * @return Mixed: integer or null
5457 function getRevisionId() {
5458 return $this->mRevisionId
;
5462 * Get the revision object for $this->mRevisionId
5464 * @return Revision|null either a Revision object or null
5466 protected function getRevisionObject() {
5467 if ( !is_null( $this->mRevisionObject
) ) {
5468 return $this->mRevisionObject
;
5470 if ( is_null( $this->mRevisionId
) ) {
5474 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5475 return $this->mRevisionObject
;
5479 * Get the timestamp associated with the current revision, adjusted for
5480 * the default server-local timestamp
5482 function getRevisionTimestamp() {
5483 if ( is_null( $this->mRevisionTimestamp
) ) {
5484 wfProfileIn( __METHOD__
);
5488 $revObject = $this->getRevisionObject();
5489 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5491 # The cryptic '' timezone parameter tells to use the site-default
5492 # timezone offset instead of the user settings.
5494 # Since this value will be saved into the parser cache, served
5495 # to other users, and potentially even used inside links and such,
5496 # it needs to be consistent for all visitors.
5497 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5499 wfProfileOut( __METHOD__
);
5501 return $this->mRevisionTimestamp
;
5505 * Get the name of the user that edited the last revision
5507 * @return String: user name
5509 function getRevisionUser() {
5510 if( is_null( $this->mRevisionUser
) ) {
5511 $revObject = $this->getRevisionObject();
5513 # if this template is subst: the revision id will be blank,
5514 # so just use the current user's name
5516 $this->mRevisionUser
= $revObject->getUserText();
5517 } elseif( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5518 $this->mRevisionUser
= $this->getUser()->getName();
5521 return $this->mRevisionUser
;
5525 * Mutator for $mDefaultSort
5527 * @param $sort string New value
5529 public function setDefaultSort( $sort ) {
5530 $this->mDefaultSort
= $sort;
5531 $this->mOutput
->setProperty( 'defaultsort', $sort );
5535 * Accessor for $mDefaultSort
5536 * Will use the empty string if none is set.
5538 * This value is treated as a prefix, so the
5539 * empty string is equivalent to sorting by
5544 public function getDefaultSort() {
5545 if ( $this->mDefaultSort
!== false ) {
5546 return $this->mDefaultSort
;
5553 * Accessor for $mDefaultSort
5554 * Unlike getDefaultSort(), will return false if none is set
5556 * @return string or false
5558 public function getCustomDefaultSort() {
5559 return $this->mDefaultSort
;
5563 * Try to guess the section anchor name based on a wikitext fragment
5564 * presumably extracted from a heading, for example "Header" from
5567 * @param $text string
5571 public function guessSectionNameFromWikiText( $text ) {
5572 # Strip out wikitext links(they break the anchor)
5573 $text = $this->stripSectionName( $text );
5574 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5575 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5579 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5580 * instead. For use in redirects, since IE6 interprets Redirect: headers
5581 * as something other than UTF-8 (apparently?), resulting in breakage.
5583 * @param $text String: The section name
5584 * @return string An anchor
5586 public function guessLegacySectionNameFromWikiText( $text ) {
5587 # Strip out wikitext links(they break the anchor)
5588 $text = $this->stripSectionName( $text );
5589 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5590 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5594 * Strips a text string of wikitext for use in a section anchor
5596 * Accepts a text string and then removes all wikitext from the
5597 * string and leaves only the resultant text (i.e. the result of
5598 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5599 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5600 * to create valid section anchors by mimicing the output of the
5601 * parser when headings are parsed.
5603 * @param $text String: text string to be stripped of wikitext
5604 * for use in a Section anchor
5605 * @return string Filtered text string
5607 public function stripSectionName( $text ) {
5608 # Strip internal link markup
5609 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5610 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5612 # Strip external link markup
5613 # @todo FIXME: Not tolerant to blank link text
5614 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5615 # on how many empty links there are on the page - need to figure that out.
5616 $text = preg_replace( '/\[(?:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5618 # Parse wikitext quotes (italics & bold)
5619 $text = $this->doQuotes( $text );
5622 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5627 * strip/replaceVariables/unstrip for preprocessor regression testing
5629 * @param $text string
5630 * @param $title Title
5631 * @param $options ParserOptions
5632 * @param $outputType int
5636 function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5637 $this->startParse( $title, $options, $outputType, true );
5639 $text = $this->replaceVariables( $text );
5640 $text = $this->mStripState
->unstripBoth( $text );
5641 $text = Sanitizer
::removeHTMLtags( $text );
5646 * @param $text string
5647 * @param $title Title
5648 * @param $options ParserOptions
5651 function testPst( $text, Title
$title, ParserOptions
$options ) {
5652 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5657 * @param $title Title
5658 * @param $options ParserOptions
5661 function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5662 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5666 * Call a callback function on all regions of the given text that are not
5667 * inside strip markers, and replace those regions with the return value
5668 * of the callback. For example, with input:
5672 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5673 * two strings will be replaced with the value returned by the callback in
5681 function markerSkipCallback( $s, $callback ) {
5684 while ( $i < strlen( $s ) ) {
5685 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5686 if ( $markerStart === false ) {
5687 $out .= call_user_func( $callback, substr( $s, $i ) );
5690 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5691 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5692 if ( $markerEnd === false ) {
5693 $out .= substr( $s, $markerStart );
5696 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5697 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5706 * Remove any strip markers found in the given text.
5708 * @param $text Input string
5711 function killMarkers( $text ) {
5712 return $this->mStripState
->killMarkers( $text );
5716 * Save the parser state required to convert the given half-parsed text to
5717 * HTML. "Half-parsed" in this context means the output of
5718 * recursiveTagParse() or internalParse(). This output has strip markers
5719 * from replaceVariables (extensionSubstitution() etc.), and link
5720 * placeholders from replaceLinkHolders().
5722 * Returns an array which can be serialized and stored persistently. This
5723 * array can later be loaded into another parser instance with
5724 * unserializeHalfParsedText(). The text can then be safely incorporated into
5725 * the return value of a parser hook.
5727 * @param $text string
5731 function serializeHalfParsedText( $text ) {
5732 wfProfileIn( __METHOD__
);
5735 'version' => self
::HALF_PARSED_VERSION
,
5736 'stripState' => $this->mStripState
->getSubState( $text ),
5737 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
5739 wfProfileOut( __METHOD__
);
5744 * Load the parser state given in the $data array, which is assumed to
5745 * have been generated by serializeHalfParsedText(). The text contents is
5746 * extracted from the array, and its markers are transformed into markers
5747 * appropriate for the current Parser instance. This transformed text is
5748 * returned, and can be safely included in the return value of a parser
5751 * If the $data array has been stored persistently, the caller should first
5752 * check whether it is still valid, by calling isValidHalfParsedText().
5754 * @param $data array Serialized data
5757 function unserializeHalfParsedText( $data ) {
5758 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
5759 throw new MWException( __METHOD__
.': invalid version' );
5762 # First, extract the strip state.
5763 $texts = array( $data['text'] );
5764 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
5766 # Now renumber links
5767 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
5769 # Should be good to go.
5774 * Returns true if the given array, presumed to be generated by
5775 * serializeHalfParsedText(), is compatible with the current version of the
5778 * @param $data Array
5782 function isValidHalfParsedText( $data ) {
5783 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
5787 * Parsed a width param of imagelink like 300px or 200x300px
5789 * @param $value String
5794 public function parseWidthParam( $value ) {
5795 $parsedWidthParam = array();
5796 if( $value === '' ) {
5797 return $parsedWidthParam;
5800 # (bug 13500) In both cases (width/height and width only),
5801 # permit trailing "px" for backward compatibility.
5802 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
5803 $width = intval( $m[1] );
5804 $height = intval( $m[2] );
5805 $parsedWidthParam['width'] = $width;
5806 $parsedWidthParam['height'] = $height;
5807 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
5808 $width = intval( $value );
5809 $parsedWidthParam['width'] = $width;
5811 return $parsedWidthParam;