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, $mGeneratedPPNodeCount, $mHighestExpansionDepth;
168 var $mTplExpandCache; # empty-frame expansion cache
169 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
170 var $mExpensiveFunctionCount; # number of expensive parser function calls
171 var $mShowToc, $mForceTocPosition;
176 var $mUser; # User object; only used when doing pre-save transform
179 # These are variables reset at least once per parse regardless of $clearState
189 var $mTitle; # Title context, used for self-link rendering and similar things
190 var $mOutputType; # Output type, one of the OT_xxx constants
191 var $ot; # Shortcut alias, see setOutputType()
192 var $mRevisionObject; # The revision object of the specified revision ID
193 var $mRevisionId; # ID to display in {{REVISIONID}} tags
194 var $mRevisionTimestamp; # The timestamp of the specified revision ID
195 var $mRevisionUser; # User to display in {{REVISIONUSER}} tag
196 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp
208 public function __construct( $conf = array() ) {
209 $this->mConf
= $conf;
210 $this->mUrlProtocols
= wfUrlProtocols();
211 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')'.
212 self
::EXT_LINK_URL_CLASS
.'+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
213 if ( isset( $conf['preprocessorClass'] ) ) {
214 $this->mPreprocessorClass
= $conf['preprocessorClass'];
215 } elseif ( defined( 'MW_COMPILED' ) ) {
216 # Preprocessor_Hash is much faster than Preprocessor_DOM in compiled mode
217 $this->mPreprocessorClass
= 'Preprocessor_Hash';
218 } elseif ( extension_loaded( 'domxml' ) ) {
219 # PECL extension that conflicts with the core DOM extension (bug 13770)
220 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
221 $this->mPreprocessorClass
= 'Preprocessor_Hash';
222 } elseif ( extension_loaded( 'dom' ) ) {
223 $this->mPreprocessorClass
= 'Preprocessor_DOM';
225 $this->mPreprocessorClass
= 'Preprocessor_Hash';
227 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
231 * Reduce memory usage to reduce the impact of circular references
233 function __destruct() {
234 if ( isset( $this->mLinkHolders
) ) {
235 unset( $this->mLinkHolders
);
237 foreach ( $this as $name => $value ) {
238 unset( $this->$name );
243 * Do various kinds of initialisation on the first call of the parser
245 function firstCallInit() {
246 if ( !$this->mFirstCall
) {
249 $this->mFirstCall
= false;
251 wfProfileIn( __METHOD__
);
253 CoreParserFunctions
::register( $this );
254 CoreTagHooks
::register( $this );
255 $this->initialiseVariables();
257 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
258 wfProfileOut( __METHOD__
);
266 function clearState() {
267 wfProfileIn( __METHOD__
);
268 if ( $this->mFirstCall
) {
269 $this->firstCallInit();
271 $this->mOutput
= new ParserOutput
;
272 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
273 $this->mAutonumber
= 0;
274 $this->mLastSection
= '';
275 $this->mDTopen
= false;
276 $this->mIncludeCount
= array();
277 $this->mArgStack
= false;
278 $this->mInPre
= false;
279 $this->mLinkHolders
= new LinkHolderArray( $this );
281 $this->mRevisionObject
= $this->mRevisionTimestamp
=
282 $this->mRevisionId
= $this->mRevisionUser
= null;
283 $this->mVarCache
= array();
287 * Prefix for temporary replacement strings for the multipass parser.
288 * \x07 should never appear in input as it's disallowed in XML.
289 * Using it at the front also gives us a little extra robustness
290 * since it shouldn't match when butted up against identifier-like
293 * Must not consist of all title characters, or else it will change
294 * the behaviour of <nowiki> in a link.
296 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
297 $this->mStripState
= new StripState( $this->mUniqPrefix
);
300 # Clear these on every parse, bug 4549
301 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
303 $this->mShowToc
= true;
304 $this->mForceTocPosition
= false;
305 $this->mIncludeSizes
= array(
309 $this->mPPNodeCount
= 0;
310 $this->mGeneratedPPNodeCount
= 0;
311 $this->mHighestExpansionDepth
= 0;
312 $this->mDefaultSort
= false;
313 $this->mHeadings
= array();
314 $this->mDoubleUnderscores
= array();
315 $this->mExpensiveFunctionCount
= 0;
318 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
319 $this->mPreprocessor
= null;
322 wfRunHooks( 'ParserClearState', array( &$this ) );
323 wfProfileOut( __METHOD__
);
327 * Convert wikitext to HTML
328 * Do not call this function recursively.
330 * @param $text String: text we want to parse
331 * @param $title Title object
332 * @param $options ParserOptions
333 * @param $linestart boolean
334 * @param $clearState boolean
335 * @param $revid Int: number to pass in {{REVISIONID}}
336 * @return ParserOutput a ParserOutput
338 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
340 * First pass--just handle <nowiki> sections, pass the rest off
341 * to internalParse() which does all the real work.
344 global $wgUseTidy, $wgAlwaysUseTidy;
345 $fname = __METHOD__
.'-' . wfGetCaller();
346 wfProfileIn( __METHOD__
);
347 wfProfileIn( $fname );
349 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
351 # Remove the strip marker tag prefix from the input, if present.
353 $text = str_replace( $this->mUniqPrefix
, '', $text );
356 $oldRevisionId = $this->mRevisionId
;
357 $oldRevisionObject = $this->mRevisionObject
;
358 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
359 $oldRevisionUser = $this->mRevisionUser
;
360 if ( $revid !== null ) {
361 $this->mRevisionId
= $revid;
362 $this->mRevisionObject
= null;
363 $this->mRevisionTimestamp
= null;
364 $this->mRevisionUser
= null;
367 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
369 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
370 $text = $this->internalParse( $text );
371 wfRunHooks( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
373 $text = $this->mStripState
->unstripGeneral( $text );
375 # Clean up special characters, only run once, next-to-last before doBlockLevels
377 # french spaces, last one Guillemet-left
378 # only if there is something before the space
379 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
380 # french spaces, Guillemet-right
381 '/(\\302\\253) /' => '\\1 ',
382 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
384 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
386 $text = $this->doBlockLevels( $text, $linestart );
388 $this->replaceLinkHolders( $text );
391 * The input doesn't get language converted if
393 * b) Content isn't converted
394 * c) It's a conversion table
395 * d) it is an interface message (which is in the user language)
397 if ( !( $options->getDisableContentConversion()
398 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) ) )
400 # Run convert unconditionally in 1.18-compatible mode
401 global $wgBug34832TransitionalRollback;
402 if ( $wgBug34832TransitionalRollback ||
!$this->mOptions
->getInterfaceMessage() ) {
403 # The position of the convert() call should not be changed. it
404 # assumes that the links are all replaced and the only thing left
405 # is the <nowiki> mark.
406 $text = $this->getConverterLanguage()->convert( $text );
411 * A converted title will be provided in the output object if title and
412 * content conversion are enabled, the article text does not contain
413 * a conversion-suppressing double-underscore tag, and no
414 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
415 * automatic link conversion.
417 if ( !( $options->getDisableTitleConversion()
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 visited node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
486 "Preprocessor generated node count: " .
487 "{$this->mGeneratedPPNodeCount}/{$this->mOptions->getMaxGeneratedPPNodeCount()}\n" .
488 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
489 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
490 "Highest expansion depth: {$this->mHighestExpansionDepth}/{$this->mOptions->getMaxPPExpandDepth()}\n".
492 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
493 $text .= "\n<!-- \n$limitReport-->\n";
495 $this->mOutput
->setText( $text );
497 $this->mRevisionId
= $oldRevisionId;
498 $this->mRevisionObject
= $oldRevisionObject;
499 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
500 $this->mRevisionUser
= $oldRevisionUser;
501 wfProfileOut( $fname );
502 wfProfileOut( __METHOD__
);
504 return $this->mOutput
;
508 * Recursive parser entry point that can be called from an extension tag
511 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
513 * @param $text String: text extension wants to have parsed
514 * @param $frame PPFrame: The frame to use for expanding any template variables
518 function recursiveTagParse( $text, $frame=false ) {
519 wfProfileIn( __METHOD__
);
520 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
521 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
522 $text = $this->internalParse( $text, false, $frame );
523 wfProfileOut( __METHOD__
);
528 * Expand templates and variables in the text, producing valid, static wikitext.
529 * Also removes comments.
530 * @return mixed|string
532 function preprocess( $text, Title
$title, ParserOptions
$options, $revid = null ) {
533 wfProfileIn( __METHOD__
);
534 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
535 if ( $revid !== null ) {
536 $this->mRevisionId
= $revid;
538 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
539 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
540 $text = $this->replaceVariables( $text );
541 $text = $this->mStripState
->unstripBoth( $text );
542 wfProfileOut( __METHOD__
);
547 * Recursive parser entry point that can be called from an extension tag
550 * @param $text String: text to be expanded
551 * @param $frame PPFrame: The frame to use for expanding any template variables
555 public function recursivePreprocess( $text, $frame = false ) {
556 wfProfileIn( __METHOD__
);
557 $text = $this->replaceVariables( $text, $frame );
558 $text = $this->mStripState
->unstripBoth( $text );
559 wfProfileOut( __METHOD__
);
564 * Process the wikitext for the "?preload=" feature. (bug 5210)
566 * "<noinclude>", "<includeonly>" etc. are parsed as for template
567 * transclusion, comments, templates, arguments, tags hooks and parser
568 * functions are untouched.
570 * @param $text String
571 * @param $title Title
572 * @param $options ParserOptions
575 public function getPreloadText( $text, Title
$title, ParserOptions
$options ) {
576 # Parser (re)initialisation
577 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
579 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
580 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
581 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
582 $text = $this->mStripState
->unstripBoth( $text );
587 * Get a random string
591 static public function getRandomString() {
592 return wfRandomString( 16 );
596 * Set the current user.
597 * Should only be used when doing pre-save transform.
599 * @param $user Mixed: User object or null (to reset)
601 function setUser( $user ) {
602 $this->mUser
= $user;
606 * Accessor for mUniqPrefix.
610 public function uniqPrefix() {
611 if ( !isset( $this->mUniqPrefix
) ) {
612 # @todo FIXME: This is probably *horribly wrong*
613 # LanguageConverter seems to want $wgParser's uniqPrefix, however
614 # if this is called for a parser cache hit, the parser may not
615 # have ever been initialized in the first place.
616 # Not really sure what the heck is supposed to be going on here.
618 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
620 return $this->mUniqPrefix
;
624 * Set the context title
628 function setTitle( $t ) {
629 if ( !$t ||
$t instanceof FakeTitle
) {
630 $t = Title
::newFromText( 'NO TITLE' );
633 if ( strval( $t->getFragment() ) !== '' ) {
634 # Strip the fragment to avoid various odd effects
635 $this->mTitle
= clone $t;
636 $this->mTitle
->setFragment( '' );
643 * Accessor for the Title object
645 * @return Title object
647 function getTitle() {
648 return $this->mTitle
;
652 * Accessor/mutator for the Title object
654 * @param $x Title object or null to just get the current one
655 * @return Title object
657 function Title( $x = null ) {
658 return wfSetVar( $this->mTitle
, $x );
662 * Set the output type
664 * @param $ot Integer: new value
666 function setOutputType( $ot ) {
667 $this->mOutputType
= $ot;
670 'html' => $ot == self
::OT_HTML
,
671 'wiki' => $ot == self
::OT_WIKI
,
672 'pre' => $ot == self
::OT_PREPROCESS
,
673 'plain' => $ot == self
::OT_PLAIN
,
678 * Accessor/mutator for the output type
680 * @param $x int|null New value or null to just get the current one
683 function OutputType( $x = null ) {
684 return wfSetVar( $this->mOutputType
, $x );
688 * Get the ParserOutput object
690 * @return ParserOutput object
692 function getOutput() {
693 return $this->mOutput
;
697 * Get the ParserOptions object
699 * @return ParserOptions object
701 function getOptions() {
702 return $this->mOptions
;
706 * Accessor/mutator for the ParserOptions object
708 * @param $x ParserOptions New value or null to just get the current one
709 * @return ParserOptions Current ParserOptions object
711 function Options( $x = null ) {
712 return wfSetVar( $this->mOptions
, $x );
718 function nextLinkID() {
719 return $this->mLinkID++
;
725 function setLinkID( $id ) {
726 $this->mLinkID
= $id;
730 * Get a language object for use in parser functions such as {{FORMATNUM:}}
733 function getFunctionLang() {
734 return $this->getTargetLanguage();
738 * Get the target language for the content being parsed. This is usually the
739 * language that the content is in.
743 * @return Language|null
745 public function getTargetLanguage() {
746 $target = $this->mOptions
->getTargetLanguage();
748 if ( $target !== null ) {
750 } elseif( $this->mOptions
->getInterfaceMessage() ) {
751 return $this->mOptions
->getUserLangObj();
752 } elseif( is_null( $this->mTitle
) ) {
753 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
756 return $this->mTitle
->getPageLanguage();
760 * Get the language object for language conversion
762 function getConverterLanguage() {
763 global $wgBug34832TransitionalRollback, $wgContLang;
764 if ( $wgBug34832TransitionalRollback ) {
767 return $this->getTargetLanguage();
772 * Get a User object either from $this->mUser, if set, or from the
773 * ParserOptions object otherwise
775 * @return User object
778 if ( !is_null( $this->mUser
) ) {
781 return $this->mOptions
->getUser();
785 * Get a preprocessor object
787 * @return Preprocessor instance
789 function getPreprocessor() {
790 if ( !isset( $this->mPreprocessor
) ) {
791 $class = $this->mPreprocessorClass
;
792 $this->mPreprocessor
= new $class( $this );
794 return $this->mPreprocessor
;
798 * Replaces all occurrences of HTML-style comments and the given tags
799 * in the text with a random marker and returns the next text. The output
800 * parameter $matches will be an associative array filled with data in
804 * 'UNIQ-xxxxx' => array(
807 * array( 'param' => 'x' ),
808 * '<element param="x">tag content</element>' ) )
811 * @param $elements array list of element names. Comments are always extracted.
812 * @param $text string Source text string.
813 * @param $matches array Out parameter, Array: extracted tags
814 * @param $uniq_prefix string
815 * @return String: stripped text
817 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
822 $taglist = implode( '|', $elements );
823 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
825 while ( $text != '' ) {
826 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
828 if ( count( $p ) < 5 ) {
831 if ( count( $p ) > 5 ) {
845 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
846 $stripped .= $marker;
848 if ( $close === '/>' ) {
849 # Empty element tag, <tag />
854 if ( $element === '!--' ) {
857 $end = "/(<\\/$element\\s*>)/i";
859 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
861 if ( count( $q ) < 3 ) {
862 # No end tag -- let it run out to the end of the text.
871 $matches[$marker] = array( $element,
873 Sanitizer
::decodeTagAttributes( $attributes ),
874 "<$element$attributes$close$content$tail" );
880 * Get a list of strippable XML-like elements
884 function getStripList() {
885 return $this->mStripList
;
889 * Add an item to the strip state
890 * Returns the unique tag which must be inserted into the stripped text
891 * The tag will be replaced with the original text in unstrip()
893 * @param $text string
897 function insertStripItem( $text ) {
898 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
899 $this->mMarkerIndex++
;
900 $this->mStripState
->addGeneral( $rnd, $text );
905 * parse the wiki syntax used to render tables
910 function doTableStuff( $text ) {
911 wfProfileIn( __METHOD__
);
913 $lines = StringUtils
::explode( "\n", $text );
915 $td_history = array(); # Is currently a td tag open?
916 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
917 $tr_history = array(); # Is currently a tr tag open?
918 $tr_attributes = array(); # history of tr attributes
919 $has_opened_tr = array(); # Did this table open a <tr> element?
920 $indent_level = 0; # indent level of the table
922 foreach ( $lines as $outLine ) {
923 $line = trim( $outLine );
925 if ( $line === '' ) { # empty line, go to next line
926 $out .= $outLine."\n";
930 $first_character = $line[0];
933 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
934 # First check if we are starting a new table
935 $indent_level = strlen( $matches[1] );
937 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
938 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
940 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
941 array_push( $td_history , false );
942 array_push( $last_tag_history , '' );
943 array_push( $tr_history , false );
944 array_push( $tr_attributes , '' );
945 array_push( $has_opened_tr , false );
946 } elseif ( count( $td_history ) == 0 ) {
947 # Don't do any of the following
948 $out .= $outLine."\n";
950 } elseif ( substr( $line , 0 , 2 ) === '|}' ) {
951 # We are ending a table
952 $line = '</table>' . substr( $line , 2 );
953 $last_tag = array_pop( $last_tag_history );
955 if ( !array_pop( $has_opened_tr ) ) {
956 $line = "<tr><td></td></tr>{$line}";
959 if ( array_pop( $tr_history ) ) {
960 $line = "</tr>{$line}";
963 if ( array_pop( $td_history ) ) {
964 $line = "</{$last_tag}>{$line}";
966 array_pop( $tr_attributes );
967 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
968 } elseif ( substr( $line , 0 , 2 ) === '|-' ) {
969 # Now we have a table row
970 $line = preg_replace( '#^\|-+#', '', $line );
972 # Whats after the tag is now only attributes
973 $attributes = $this->mStripState
->unstripBoth( $line );
974 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
975 array_pop( $tr_attributes );
976 array_push( $tr_attributes, $attributes );
979 $last_tag = array_pop( $last_tag_history );
980 array_pop( $has_opened_tr );
981 array_push( $has_opened_tr , true );
983 if ( array_pop( $tr_history ) ) {
987 if ( array_pop( $td_history ) ) {
988 $line = "</{$last_tag}>{$line}";
992 array_push( $tr_history , false );
993 array_push( $td_history , false );
994 array_push( $last_tag_history , '' );
995 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line , 0 , 2 ) === '|+' ) {
996 # This might be cell elements, td, th or captions
997 if ( substr( $line , 0 , 2 ) === '|+' ) {
998 $first_character = '+';
999 $line = substr( $line , 1 );
1002 $line = substr( $line , 1 );
1004 if ( $first_character === '!' ) {
1005 $line = str_replace( '!!' , '||' , $line );
1008 # Split up multiple cells on the same line.
1009 # FIXME : This can result in improper nesting of tags processed
1010 # by earlier parser steps, but should avoid splitting up eg
1011 # attribute values containing literal "||".
1012 $cells = StringUtils
::explodeMarkup( '||' , $line );
1016 # Loop through each table cell
1017 foreach ( $cells as $cell ) {
1019 if ( $first_character !== '+' ) {
1020 $tr_after = array_pop( $tr_attributes );
1021 if ( !array_pop( $tr_history ) ) {
1022 $previous = "<tr{$tr_after}>\n";
1024 array_push( $tr_history , true );
1025 array_push( $tr_attributes , '' );
1026 array_pop( $has_opened_tr );
1027 array_push( $has_opened_tr , true );
1030 $last_tag = array_pop( $last_tag_history );
1032 if ( array_pop( $td_history ) ) {
1033 $previous = "</{$last_tag}>\n{$previous}";
1036 if ( $first_character === '|' ) {
1038 } elseif ( $first_character === '!' ) {
1040 } elseif ( $first_character === '+' ) {
1041 $last_tag = 'caption';
1046 array_push( $last_tag_history , $last_tag );
1048 # A cell could contain both parameters and data
1049 $cell_data = explode( '|' , $cell , 2 );
1051 # Bug 553: Note that a '|' inside an invalid link should not
1052 # be mistaken as delimiting cell parameters
1053 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1054 $cell = "{$previous}<{$last_tag}>{$cell}";
1055 } elseif ( count( $cell_data ) == 1 ) {
1056 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1058 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1059 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
1060 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1064 array_push( $td_history , true );
1067 $out .= $outLine . "\n";
1070 # Closing open td, tr && table
1071 while ( count( $td_history ) > 0 ) {
1072 if ( array_pop( $td_history ) ) {
1075 if ( array_pop( $tr_history ) ) {
1078 if ( !array_pop( $has_opened_tr ) ) {
1079 $out .= "<tr><td></td></tr>\n" ;
1082 $out .= "</table>\n";
1085 # Remove trailing line-ending (b/c)
1086 if ( substr( $out, -1 ) === "\n" ) {
1087 $out = substr( $out, 0, -1 );
1090 # special case: don't return empty table
1091 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1095 wfProfileOut( __METHOD__
);
1101 * Helper function for parse() that transforms wiki markup into
1102 * HTML. Only called for $mOutputType == self::OT_HTML.
1106 * @param $text string
1107 * @param $isMain bool
1108 * @param $frame bool
1112 function internalParse( $text, $isMain = true, $frame = false ) {
1113 wfProfileIn( __METHOD__
);
1117 # Hook to suspend the parser in this state
1118 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1119 wfProfileOut( __METHOD__
);
1123 # if $frame is provided, then use $frame for replacing any variables
1125 # use frame depth to infer how include/noinclude tags should be handled
1126 # depth=0 means this is the top-level document; otherwise it's an included document
1127 if ( !$frame->depth
) {
1130 $flag = Parser
::PTD_FOR_INCLUSION
;
1132 $dom = $this->preprocessToDom( $text, $flag );
1133 $text = $frame->expand( $dom );
1135 # if $frame is not provided, then use old-style replaceVariables
1136 $text = $this->replaceVariables( $text );
1139 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1140 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1141 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1143 # Tables need to come after variable replacement for things to work
1144 # properly; putting them before other transformations should keep
1145 # exciting things like link expansions from showing up in surprising
1147 $text = $this->doTableStuff( $text );
1149 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1151 $text = $this->doDoubleUnderscore( $text );
1153 $text = $this->doHeadings( $text );
1154 if ( $this->mOptions
->getUseDynamicDates() ) {
1155 $df = DateFormatter
::getInstance();
1156 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1158 $text = $this->replaceInternalLinks( $text );
1159 $text = $this->doAllQuotes( $text );
1160 $text = $this->replaceExternalLinks( $text );
1162 # replaceInternalLinks may sometimes leave behind
1163 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1164 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
1166 $text = $this->doMagicLinks( $text );
1167 $text = $this->formatHeadings( $text, $origText, $isMain );
1169 wfProfileOut( __METHOD__
);
1174 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1175 * magic external links.
1180 * @param $text string
1184 function doMagicLinks( $text ) {
1185 wfProfileIn( __METHOD__
);
1186 $prots = wfUrlProtocolsWithoutProtRel();
1187 $urlChar = self
::EXT_LINK_URL_CLASS
;
1188 $text = preg_replace_callback(
1190 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1191 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1192 (\\b(?i:$prots)$urlChar+) | # m[3]: Free external links" . '
1193 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1194 ISBN\s+(\b # m[5]: ISBN, capture number
1195 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1196 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1197 [0-9Xx] # check digit
1199 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1200 wfProfileOut( __METHOD__
);
1205 * @throws MWException
1207 * @return HTML|string
1209 function magicLinkCallback( $m ) {
1210 if ( isset( $m[1] ) && $m[1] !== '' ) {
1213 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1216 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1217 # Free external link
1218 return $this->makeFreeExternalLink( $m[0] );
1219 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1221 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1224 $CssClass = 'mw-magiclink-rfc';
1226 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1228 $urlmsg = 'pubmedurl';
1229 $CssClass = 'mw-magiclink-pmid';
1232 throw new MWException( __METHOD__
.': unrecognised match type "' .
1233 substr( $m[0], 0, 20 ) . '"' );
1235 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1236 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1237 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1240 $num = strtr( $isbn, array(
1245 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1247 htmlspecialchars( $titleObj->getLocalUrl() ) .
1248 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1255 * Make a free external link, given a user-supplied URL
1257 * @param $url string
1259 * @return string HTML
1262 function makeFreeExternalLink( $url ) {
1263 wfProfileIn( __METHOD__
);
1267 # The characters '<' and '>' (which were escaped by
1268 # removeHTMLtags()) should not be included in
1269 # URLs, per RFC 2396.
1271 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1272 $trail = substr( $url, $m2[0][1] ) . $trail;
1273 $url = substr( $url, 0, $m2[0][1] );
1276 # Move trailing punctuation to $trail
1278 # If there is no left bracket, then consider right brackets fair game too
1279 if ( strpos( $url, '(' ) === false ) {
1283 $numSepChars = strspn( strrev( $url ), $sep );
1284 if ( $numSepChars ) {
1285 $trail = substr( $url, -$numSepChars ) . $trail;
1286 $url = substr( $url, 0, -$numSepChars );
1289 $url = Sanitizer
::cleanUrl( $url );
1291 # Is this an external image?
1292 $text = $this->maybeMakeExternalImage( $url );
1293 if ( $text === false ) {
1294 # Not an image, make a link
1295 $text = Linker
::makeExternalLink( $url,
1296 $this->getConverterLanguage()->markNoConversion($url), true, 'free',
1297 $this->getExternalLinkAttribs( $url ) );
1298 # Register it in the output object...
1299 # Replace unnecessary URL escape codes with their equivalent characters
1300 $pasteurized = self
::replaceUnusualEscapes( $url );
1301 $this->mOutput
->addExternalLink( $pasteurized );
1303 wfProfileOut( __METHOD__
);
1304 return $text . $trail;
1309 * Parse headers and return html
1313 * @param $text string
1317 function doHeadings( $text ) {
1318 wfProfileIn( __METHOD__
);
1319 for ( $i = 6; $i >= 1; --$i ) {
1320 $h = str_repeat( '=', $i );
1321 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1322 "<h$i>\\1</h$i>", $text );
1324 wfProfileOut( __METHOD__
);
1329 * Replace single quotes with HTML markup
1332 * @param $text string
1334 * @return string the altered text
1336 function doAllQuotes( $text ) {
1337 wfProfileIn( __METHOD__
);
1339 $lines = StringUtils
::explode( "\n", $text );
1340 foreach ( $lines as $line ) {
1341 $outtext .= $this->doQuotes( $line ) . "\n";
1343 $outtext = substr( $outtext, 0,-1 );
1344 wfProfileOut( __METHOD__
);
1349 * Helper function for doAllQuotes()
1351 * @param $text string
1355 public function doQuotes( $text ) {
1356 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1357 if ( count( $arr ) == 1 ) {
1360 # First, do some preliminary work. This may shift some apostrophes from
1361 # being mark-up to being text. It also counts the number of occurrences
1362 # of bold and italics mark-ups.
1365 for ( $i = 0; $i < count( $arr ); $i++
) {
1366 if ( ( $i %
2 ) == 1 ) {
1367 # If there are ever four apostrophes, assume the first is supposed to
1368 # be text, and the remaining three constitute mark-up for bold text.
1369 if ( strlen( $arr[$i] ) == 4 ) {
1372 } elseif ( strlen( $arr[$i] ) > 5 ) {
1373 # If there are more than 5 apostrophes in a row, assume they're all
1374 # text except for the last 5.
1375 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1378 # Count the number of occurrences of bold and italics mark-ups.
1379 # We are not counting sequences of five apostrophes.
1380 if ( strlen( $arr[$i] ) == 2 ) {
1382 } elseif ( strlen( $arr[$i] ) == 3 ) {
1384 } elseif ( strlen( $arr[$i] ) == 5 ) {
1391 # If there is an odd number of both bold and italics, it is likely
1392 # that one of the bold ones was meant to be an apostrophe followed
1393 # by italics. Which one we cannot know for certain, but it is more
1394 # likely to be one that has a single-letter word before it.
1395 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1397 $firstsingleletterword = -1;
1398 $firstmultiletterword = -1;
1400 foreach ( $arr as $r ) {
1401 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1402 $x1 = substr( $arr[$i-1], -1 );
1403 $x2 = substr( $arr[$i-1], -2, 1 );
1404 if ( $x1 === ' ' ) {
1405 if ( $firstspace == -1 ) {
1408 } elseif ( $x2 === ' ') {
1409 if ( $firstsingleletterword == -1 ) {
1410 $firstsingleletterword = $i;
1413 if ( $firstmultiletterword == -1 ) {
1414 $firstmultiletterword = $i;
1421 # If there is a single-letter word, use it!
1422 if ( $firstsingleletterword > -1 ) {
1423 $arr[$firstsingleletterword] = "''";
1424 $arr[$firstsingleletterword-1] .= "'";
1425 } elseif ( $firstmultiletterword > -1 ) {
1426 # If not, but there's a multi-letter word, use that one.
1427 $arr[$firstmultiletterword] = "''";
1428 $arr[$firstmultiletterword-1] .= "'";
1429 } elseif ( $firstspace > -1 ) {
1430 # ... otherwise use the first one that has neither.
1431 # (notice that it is possible for all three to be -1 if, for example,
1432 # there is only one pentuple-apostrophe in the line)
1433 $arr[$firstspace] = "''";
1434 $arr[$firstspace-1] .= "'";
1438 # Now let's actually convert our apostrophic mush to HTML!
1443 foreach ( $arr as $r ) {
1444 if ( ( $i %
2 ) == 0 ) {
1445 if ( $state === 'both' ) {
1451 if ( strlen( $r ) == 2 ) {
1452 if ( $state === 'i' ) {
1453 $output .= '</i>'; $state = '';
1454 } elseif ( $state === 'bi' ) {
1455 $output .= '</i>'; $state = 'b';
1456 } elseif ( $state === 'ib' ) {
1457 $output .= '</b></i><b>'; $state = 'b';
1458 } elseif ( $state === 'both' ) {
1459 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1460 } else { # $state can be 'b' or ''
1461 $output .= '<i>'; $state .= 'i';
1463 } elseif ( strlen( $r ) == 3 ) {
1464 if ( $state === 'b' ) {
1465 $output .= '</b>'; $state = '';
1466 } elseif ( $state === 'bi' ) {
1467 $output .= '</i></b><i>'; $state = 'i';
1468 } elseif ( $state === 'ib' ) {
1469 $output .= '</b>'; $state = 'i';
1470 } elseif ( $state === 'both' ) {
1471 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1472 } else { # $state can be 'i' or ''
1473 $output .= '<b>'; $state .= 'b';
1475 } elseif ( strlen( $r ) == 5 ) {
1476 if ( $state === 'b' ) {
1477 $output .= '</b><i>'; $state = 'i';
1478 } elseif ( $state === 'i' ) {
1479 $output .= '</i><b>'; $state = 'b';
1480 } elseif ( $state === 'bi' ) {
1481 $output .= '</i></b>'; $state = '';
1482 } elseif ( $state === 'ib' ) {
1483 $output .= '</b></i>'; $state = '';
1484 } elseif ( $state === 'both' ) {
1485 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1486 } else { # ($state == '')
1487 $buffer = ''; $state = 'both';
1493 # Now close all remaining tags. Notice that the order is important.
1494 if ( $state === 'b' ||
$state === 'ib' ) {
1497 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1500 if ( $state === 'bi' ) {
1503 # There might be lonely ''''', so make sure we have a buffer
1504 if ( $state === 'both' && $buffer ) {
1505 $output .= '<b><i>'.$buffer.'</i></b>';
1512 * Replace external links (REL)
1514 * Note: this is all very hackish and the order of execution matters a lot.
1515 * Make sure to run maintenance/parserTests.php if you change this code.
1519 * @param $text string
1523 function replaceExternalLinks( $text ) {
1524 wfProfileIn( __METHOD__
);
1526 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1527 if ( $bits === false ) {
1528 throw new MWException( "PCRE needs to be compiled with --enable-unicode-properties in order for MediaWiki to function" );
1530 $s = array_shift( $bits );
1533 while ( $i<count( $bits ) ) {
1535 $protocol = $bits[$i++
];
1536 $text = $bits[$i++
];
1537 $trail = $bits[$i++
];
1539 # The characters '<' and '>' (which were escaped by
1540 # removeHTMLtags()) should not be included in
1541 # URLs, per RFC 2396.
1543 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1544 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1545 $url = substr( $url, 0, $m2[0][1] );
1548 # If the link text is an image URL, replace it with an <img> tag
1549 # This happened by accident in the original parser, but some people used it extensively
1550 $img = $this->maybeMakeExternalImage( $text );
1551 if ( $img !== false ) {
1557 # Set linktype for CSS - if URL==text, link is essentially free
1558 $linktype = ( $text === $url ) ?
'free' : 'text';
1560 # No link text, e.g. [http://domain.tld/some.link]
1561 if ( $text == '' ) {
1563 $langObj = $this->getTargetLanguage();
1564 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1565 $linktype = 'autonumber';
1567 # Have link text, e.g. [http://domain.tld/some.link text]s
1569 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1572 $text = $this->getConverterLanguage()->markNoConversion( $text );
1574 $url = Sanitizer
::cleanUrl( $url );
1576 # Use the encoded URL
1577 # This means that users can paste URLs directly into the text
1578 # Funny characters like ö aren't valid in URLs anyway
1579 # This was changed in August 2004
1580 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1581 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1583 # Register link in the output object.
1584 # Replace unnecessary URL escape codes with the referenced character
1585 # This prevents spammers from hiding links from the filters
1586 $pasteurized = self
::replaceUnusualEscapes( $url );
1587 $this->mOutput
->addExternalLink( $pasteurized );
1590 wfProfileOut( __METHOD__
);
1595 * Get an associative array of additional HTML attributes appropriate for a
1596 * particular external link. This currently may include rel => nofollow
1597 * (depending on configuration, namespace, and the URL's domain) and/or a
1598 * target attribute (depending on configuration).
1600 * @param $url String|bool optional URL, to extract the domain from for rel =>
1601 * nofollow if appropriate
1602 * @return Array associative array of HTML attributes
1604 function getExternalLinkAttribs( $url = false ) {
1606 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1607 $ns = $this->mTitle
->getNamespace();
1608 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) &&
1609 !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions ) )
1611 $attribs['rel'] = 'nofollow';
1613 if ( $this->mOptions
->getExternalLinkTarget() ) {
1614 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1620 * Replace unusual URL escape codes with their equivalent characters
1622 * @param $url String
1625 * @todo This can merge genuinely required bits in the path or query string,
1626 * breaking legit URLs. A proper fix would treat the various parts of
1627 * the URL differently; as a workaround, just use the output for
1628 * statistical records, not for actual linking/output.
1630 static function replaceUnusualEscapes( $url ) {
1631 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1632 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1636 * Callback function used in replaceUnusualEscapes().
1637 * Replaces unusual URL escape codes with their equivalent character
1639 * @param $matches array
1643 private static function replaceUnusualEscapesCallback( $matches ) {
1644 $char = urldecode( $matches[0] );
1645 $ord = ord( $char );
1646 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1647 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1648 # No, shouldn't be escaped
1651 # Yes, leave it escaped
1657 * make an image if it's allowed, either through the global
1658 * option, through the exception, or through the on-wiki whitelist
1661 * $param $url string
1665 function maybeMakeExternalImage( $url ) {
1666 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1667 $imagesexception = !empty( $imagesfrom );
1669 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1670 if ( $imagesexception && is_array( $imagesfrom ) ) {
1671 $imagematch = false;
1672 foreach ( $imagesfrom as $match ) {
1673 if ( strpos( $url, $match ) === 0 ) {
1678 } elseif ( $imagesexception ) {
1679 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1681 $imagematch = false;
1683 if ( $this->mOptions
->getAllowExternalImages()
1684 ||
( $imagesexception && $imagematch ) ) {
1685 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1687 $text = Linker
::makeExternalImage( $url );
1690 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1691 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1692 $whitelist = explode( "\n", wfMessage( 'external_image_whitelist' )->inContentLanguage()->text() );
1693 foreach ( $whitelist as $entry ) {
1694 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1695 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1698 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1699 # Image matches a whitelist entry
1700 $text = Linker
::makeExternalImage( $url );
1709 * Process [[ ]] wikilinks
1713 * @return String: processed text
1717 function replaceInternalLinks( $s ) {
1718 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1723 * Process [[ ]] wikilinks (RIL)
1724 * @return LinkHolderArray
1728 function replaceInternalLinks2( &$s ) {
1729 wfProfileIn( __METHOD__
);
1731 wfProfileIn( __METHOD__
.'-setup' );
1732 static $tc = FALSE, $e1, $e1_img;
1733 # the % is needed to support urlencoded titles as well
1735 $tc = Title
::legalChars() . '#%';
1736 # Match a link having the form [[namespace:link|alternate]]trail
1737 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1738 # Match cases where there is no "]]", which might still be images
1739 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1742 $holders = new LinkHolderArray( $this );
1744 # split the entire text string on occurrences of [[
1745 $a = StringUtils
::explode( '[[', ' ' . $s );
1746 # get the first element (all text up to first [[), and remove the space we added
1749 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1750 $s = substr( $s, 1 );
1752 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1754 if ( $useLinkPrefixExtension ) {
1755 # Match the end of a line for a word that's not followed by whitespace,
1756 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1757 $e2 = wfMessage( 'linkprefix' )->inContentLanguage()->text();
1760 if ( is_null( $this->mTitle
) ) {
1761 wfProfileOut( __METHOD__
.'-setup' );
1762 wfProfileOut( __METHOD__
);
1763 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1765 $nottalk = !$this->mTitle
->isTalkPage();
1767 if ( $useLinkPrefixExtension ) {
1769 if ( preg_match( $e2, $s, $m ) ) {
1770 $first_prefix = $m[2];
1772 $first_prefix = false;
1778 if ( $this->getConverterLanguage()->hasVariants() ) {
1779 $selflink = $this->getConverterLanguage()->autoConvertToAllVariants(
1780 $this->mTitle
->getPrefixedText() );
1782 $selflink = array( $this->mTitle
->getPrefixedText() );
1784 $useSubpages = $this->areSubpagesAllowed();
1785 wfProfileOut( __METHOD__
.'-setup' );
1787 # Loop for each link
1788 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1789 # Check for excessive memory usage
1790 if ( $holders->isBig() ) {
1792 # Do the existence check, replace the link holders and clear the array
1793 $holders->replace( $s );
1797 if ( $useLinkPrefixExtension ) {
1798 wfProfileIn( __METHOD__
.'-prefixhandling' );
1799 if ( preg_match( $e2, $s, $m ) ) {
1806 if ( $first_prefix ) {
1807 $prefix = $first_prefix;
1808 $first_prefix = false;
1810 wfProfileOut( __METHOD__
.'-prefixhandling' );
1813 $might_be_img = false;
1815 wfProfileIn( __METHOD__
."-e1" );
1816 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1818 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1819 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1820 # the real problem is with the $e1 regex
1823 # Still some problems for cases where the ] is meant to be outside punctuation,
1824 # and no image is in sight. See bug 2095.
1826 if ( $text !== '' &&
1827 substr( $m[3], 0, 1 ) === ']' &&
1828 strpos( $text, '[' ) !== false
1831 $text .= ']'; # so that replaceExternalLinks($text) works later
1832 $m[3] = substr( $m[3], 1 );
1834 # fix up urlencoded title texts
1835 if ( strpos( $m[1], '%' ) !== false ) {
1836 # Should anchors '#' also be rejected?
1837 $m[1] = str_replace( array('<', '>'), array('<', '>'), rawurldecode( $m[1] ) );
1840 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1841 $might_be_img = true;
1843 if ( strpos( $m[1], '%' ) !== false ) {
1844 $m[1] = rawurldecode( $m[1] );
1847 } else { # Invalid form; output directly
1848 $s .= $prefix . '[[' . $line ;
1849 wfProfileOut( __METHOD__
."-e1" );
1852 wfProfileOut( __METHOD__
."-e1" );
1853 wfProfileIn( __METHOD__
."-misc" );
1855 # Don't allow internal links to pages containing
1856 # PROTO: where PROTO is a valid URL protocol; these
1857 # should be external links.
1858 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $m[1] ) ) {
1859 $s .= $prefix . '[[' . $line ;
1860 wfProfileOut( __METHOD__
."-misc" );
1864 # Make subpage if necessary
1865 if ( $useSubpages ) {
1866 $link = $this->maybeDoSubpageLink( $m[1], $text );
1871 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1873 # Strip off leading ':'
1874 $link = substr( $link, 1 );
1877 wfProfileOut( __METHOD__
."-misc" );
1878 wfProfileIn( __METHOD__
."-title" );
1879 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1880 if ( $nt === null ) {
1881 $s .= $prefix . '[[' . $line;
1882 wfProfileOut( __METHOD__
."-title" );
1886 $ns = $nt->getNamespace();
1887 $iw = $nt->getInterWiki();
1888 wfProfileOut( __METHOD__
."-title" );
1890 if ( $might_be_img ) { # if this is actually an invalid link
1891 wfProfileIn( __METHOD__
."-might_be_img" );
1892 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1895 # look at the next 'line' to see if we can close it there
1897 $next_line = $a->current();
1898 if ( $next_line === false ||
$next_line === null ) {
1901 $m = explode( ']]', $next_line, 3 );
1902 if ( count( $m ) == 3 ) {
1903 # the first ]] closes the inner link, the second the image
1905 $text .= "[[{$m[0]}]]{$m[1]}";
1908 } elseif ( count( $m ) == 2 ) {
1909 # if there's exactly one ]] that's fine, we'll keep looking
1910 $text .= "[[{$m[0]}]]{$m[1]}";
1912 # if $next_line is invalid too, we need look no further
1913 $text .= '[[' . $next_line;
1918 # we couldn't find the end of this imageLink, so output it raw
1919 # but don't ignore what might be perfectly normal links in the text we've examined
1920 $holders->merge( $this->replaceInternalLinks2( $text ) );
1921 $s .= "{$prefix}[[$link|$text";
1922 # note: no $trail, because without an end, there *is* no trail
1923 wfProfileOut( __METHOD__
."-might_be_img" );
1926 } else { # it's not an image, so output it raw
1927 $s .= "{$prefix}[[$link|$text";
1928 # note: no $trail, because without an end, there *is* no trail
1929 wfProfileOut( __METHOD__
."-might_be_img" );
1932 wfProfileOut( __METHOD__
."-might_be_img" );
1935 $wasblank = ( $text == '' );
1939 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1940 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1941 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1942 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1943 $text = $this->doQuotes( $text );
1946 # Link not escaped by : , create the various objects
1949 wfProfileIn( __METHOD__
."-interwiki" );
1950 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && Language
::fetchLanguageName( $iw, null, 'mw' ) ) {
1951 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1952 $s = rtrim( $s . $prefix );
1953 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1954 wfProfileOut( __METHOD__
."-interwiki" );
1957 wfProfileOut( __METHOD__
."-interwiki" );
1959 if ( $ns == NS_FILE
) {
1960 wfProfileIn( __METHOD__
."-image" );
1961 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1963 # if no parameters were passed, $text
1964 # becomes something like "File:Foo.png",
1965 # which we don't want to pass on to the
1969 # recursively parse links inside the image caption
1970 # actually, this will parse them in any other parameters, too,
1971 # but it might be hard to fix that, and it doesn't matter ATM
1972 $text = $this->replaceExternalLinks( $text );
1973 $holders->merge( $this->replaceInternalLinks2( $text ) );
1975 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1976 $s .= $prefix . $this->armorLinks(
1977 $this->makeImage( $nt, $text, $holders ) ) . $trail;
1979 $s .= $prefix . $trail;
1981 wfProfileOut( __METHOD__
."-image" );
1985 if ( $ns == NS_CATEGORY
) {
1986 wfProfileIn( __METHOD__
."-category" );
1987 $s = rtrim( $s . "\n" ); # bug 87
1990 $sortkey = $this->getDefaultSort();
1994 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1995 $sortkey = str_replace( "\n", '', $sortkey );
1996 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
1997 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2000 * Strip the whitespace Category links produce, see bug 87
2001 * @todo We might want to use trim($tmp, "\n") here.
2003 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2005 wfProfileOut( __METHOD__
."-category" );
2010 # Self-link checking
2011 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
2012 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
2013 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2018 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2019 # @todo FIXME: Should do batch file existence checks, see comment below
2020 if ( $ns == NS_MEDIA
) {
2021 wfProfileIn( __METHOD__
."-media" );
2022 # Give extensions a chance to select the file revision for us
2025 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2026 array( $this, $nt, &$options, &$descQuery ) );
2027 # Fetch and register the file (file title may be different via hooks)
2028 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2029 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2030 $s .= $prefix . $this->armorLinks(
2031 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2032 wfProfileOut( __METHOD__
."-media" );
2036 wfProfileIn( __METHOD__
."-always_known" );
2037 # Some titles, such as valid special pages or files in foreign repos, should
2038 # be shown as bluelinks even though they're not included in the page table
2040 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2041 # batch file existence checks for NS_FILE and NS_MEDIA
2042 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2043 $this->mOutput
->addLink( $nt );
2044 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2046 # Links will be added to the output link list after checking
2047 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2049 wfProfileOut( __METHOD__
."-always_known" );
2051 wfProfileOut( __METHOD__
);
2056 * Render a forced-blue link inline; protect against double expansion of
2057 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2058 * Since this little disaster has to split off the trail text to avoid
2059 * breaking URLs in the following text without breaking trails on the
2060 * wiki links, it's been made into a horrible function.
2063 * @param $text String
2064 * @param $query Array or String
2065 * @param $trail String
2066 * @param $prefix String
2067 * @return String: HTML-wikitext mix oh yuck
2069 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2070 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2072 if ( is_string( $query ) ) {
2073 $query = wfCgiToArray( $query );
2075 if ( $text == '' ) {
2076 $text = htmlspecialchars( $nt->getPrefixedText() );
2079 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2081 return $this->armorLinks( $link ) . $trail;
2085 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2086 * going to go through further parsing steps before inline URL expansion.
2088 * Not needed quite as much as it used to be since free links are a bit
2089 * more sensible these days. But bracketed links are still an issue.
2091 * @param $text String: more-or-less HTML
2092 * @return String: less-or-more HTML with NOPARSE bits
2094 function armorLinks( $text ) {
2095 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2096 "{$this->mUniqPrefix}NOPARSE$1", $text );
2100 * Return true if subpage links should be expanded on this page.
2103 function areSubpagesAllowed() {
2104 # Some namespaces don't allow subpages
2105 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2109 * Handle link to subpage if necessary
2111 * @param $target String: the source of the link
2112 * @param &$text String: the link text, modified as necessary
2113 * @return string the full name of the link
2116 function maybeDoSubpageLink( $target, &$text ) {
2117 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2121 * Used by doBlockLevels()
2126 function closeParagraph() {
2128 if ( $this->mLastSection
!= '' ) {
2129 $result = '</' . $this->mLastSection
. ">\n";
2131 $this->mInPre
= false;
2132 $this->mLastSection
= '';
2137 * getCommon() returns the length of the longest common substring
2138 * of both arguments, starting at the beginning of both.
2141 * @param $st1 string
2142 * @param $st2 string
2146 function getCommon( $st1, $st2 ) {
2147 $fl = strlen( $st1 );
2148 $shorter = strlen( $st2 );
2149 if ( $fl < $shorter ) {
2153 for ( $i = 0; $i < $shorter; ++
$i ) {
2154 if ( $st1[$i] != $st2[$i] ) {
2162 * These next three functions open, continue, and close the list
2163 * element appropriate to the prefix character passed into them.
2166 * @param $char string
2170 function openList( $char ) {
2171 $result = $this->closeParagraph();
2173 if ( '*' === $char ) {
2174 $result .= '<ul><li>';
2175 } elseif ( '#' === $char ) {
2176 $result .= '<ol><li>';
2177 } elseif ( ':' === $char ) {
2178 $result .= '<dl><dd>';
2179 } elseif ( ';' === $char ) {
2180 $result .= '<dl><dt>';
2181 $this->mDTopen
= true;
2183 $result = '<!-- ERR 1 -->';
2191 * @param $char String
2196 function nextItem( $char ) {
2197 if ( '*' === $char ||
'#' === $char ) {
2199 } elseif ( ':' === $char ||
';' === $char ) {
2201 if ( $this->mDTopen
) {
2204 if ( ';' === $char ) {
2205 $this->mDTopen
= true;
2206 return $close . '<dt>';
2208 $this->mDTopen
= false;
2209 return $close . '<dd>';
2212 return '<!-- ERR 2 -->';
2217 * @param $char String
2222 function closeList( $char ) {
2223 if ( '*' === $char ) {
2224 $text = '</li></ul>';
2225 } elseif ( '#' === $char ) {
2226 $text = '</li></ol>';
2227 } elseif ( ':' === $char ) {
2228 if ( $this->mDTopen
) {
2229 $this->mDTopen
= false;
2230 $text = '</dt></dl>';
2232 $text = '</dd></dl>';
2235 return '<!-- ERR 3 -->';
2242 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2244 * @param $text String
2245 * @param $linestart Boolean: whether or not this is at the start of a line.
2247 * @return string the lists rendered as HTML
2249 function doBlockLevels( $text, $linestart ) {
2250 wfProfileIn( __METHOD__
);
2252 # Parsing through the text line by line. The main thing
2253 # happening here is handling of block-level elements p, pre,
2254 # and making lists from lines starting with * # : etc.
2256 $textLines = StringUtils
::explode( "\n", $text );
2258 $lastPrefix = $output = '';
2259 $this->mDTopen
= $inBlockElem = false;
2261 $paragraphStack = false;
2263 foreach ( $textLines as $oLine ) {
2265 if ( !$linestart ) {
2275 $lastPrefixLength = strlen( $lastPrefix );
2276 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2277 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2278 # If not in a <pre> element, scan for and figure out what prefixes are there.
2279 if ( !$this->mInPre
) {
2280 # Multiple prefixes may abut each other for nested lists.
2281 $prefixLength = strspn( $oLine, '*#:;' );
2282 $prefix = substr( $oLine, 0, $prefixLength );
2285 # ; and : are both from definition-lists, so they're equivalent
2286 # for the purposes of determining whether or not we need to open/close
2288 $prefix2 = str_replace( ';', ':', $prefix );
2289 $t = substr( $oLine, $prefixLength );
2290 $this->mInPre
= (bool)$preOpenMatch;
2292 # Don't interpret any other prefixes in preformatted text
2294 $prefix = $prefix2 = '';
2299 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2300 # Same as the last item, so no need to deal with nesting or opening stuff
2301 $output .= $this->nextItem( substr( $prefix, -1 ) );
2302 $paragraphStack = false;
2304 if ( substr( $prefix, -1 ) === ';') {
2305 # The one nasty exception: definition lists work like this:
2306 # ; title : definition text
2307 # So we check for : in the remainder text to split up the
2308 # title and definition, without b0rking links.
2310 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2312 $output .= $term . $this->nextItem( ':' );
2315 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2316 # We need to open or close prefixes, or both.
2318 # Either open or close a level...
2319 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2320 $paragraphStack = false;
2322 # Close all the prefixes which aren't shared.
2323 while ( $commonPrefixLength < $lastPrefixLength ) {
2324 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2325 --$lastPrefixLength;
2328 # Continue the current prefix if appropriate.
2329 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2330 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2333 # Open prefixes where appropriate.
2334 while ( $prefixLength > $commonPrefixLength ) {
2335 $char = substr( $prefix, $commonPrefixLength, 1 );
2336 $output .= $this->openList( $char );
2338 if ( ';' === $char ) {
2339 # @todo FIXME: This is dupe of code above
2340 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2342 $output .= $term . $this->nextItem( ':' );
2345 ++
$commonPrefixLength;
2347 $lastPrefix = $prefix2;
2350 # If we have no prefixes, go to paragraph mode.
2351 if ( 0 == $prefixLength ) {
2352 wfProfileIn( __METHOD__
."-paragraph" );
2353 # No prefix (not in list)--go to paragraph mode
2354 # XXX: use a stack for nestable elements like span, table and div
2355 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2356 $closematch = preg_match(
2357 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2358 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2359 if ( $openmatch or $closematch ) {
2360 $paragraphStack = false;
2361 # TODO bug 5718: paragraph closed
2362 $output .= $this->closeParagraph();
2363 if ( $preOpenMatch and !$preCloseMatch ) {
2364 $this->mInPre
= true;
2366 $inBlockElem = !$closematch;
2367 } elseif ( !$inBlockElem && !$this->mInPre
) {
2368 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2370 if ( $this->mLastSection
!== 'pre' ) {
2371 $paragraphStack = false;
2372 $output .= $this->closeParagraph().'<pre>';
2373 $this->mLastSection
= 'pre';
2375 $t = substr( $t, 1 );
2378 if ( trim( $t ) === '' ) {
2379 if ( $paragraphStack ) {
2380 $output .= $paragraphStack.'<br />';
2381 $paragraphStack = false;
2382 $this->mLastSection
= 'p';
2384 if ( $this->mLastSection
!== 'p' ) {
2385 $output .= $this->closeParagraph();
2386 $this->mLastSection
= '';
2387 $paragraphStack = '<p>';
2389 $paragraphStack = '</p><p>';
2393 if ( $paragraphStack ) {
2394 $output .= $paragraphStack;
2395 $paragraphStack = false;
2396 $this->mLastSection
= 'p';
2397 } elseif ( $this->mLastSection
!== 'p' ) {
2398 $output .= $this->closeParagraph().'<p>';
2399 $this->mLastSection
= 'p';
2404 wfProfileOut( __METHOD__
."-paragraph" );
2406 # somewhere above we forget to get out of pre block (bug 785)
2407 if ( $preCloseMatch && $this->mInPre
) {
2408 $this->mInPre
= false;
2410 if ( $paragraphStack === false ) {
2414 while ( $prefixLength ) {
2415 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2418 if ( $this->mLastSection
!= '' ) {
2419 $output .= '</' . $this->mLastSection
. '>';
2420 $this->mLastSection
= '';
2423 wfProfileOut( __METHOD__
);
2428 * Split up a string on ':', ignoring any occurrences inside tags
2429 * to prevent illegal overlapping.
2431 * @param $str String the string to split
2432 * @param &$before String set to everything before the ':'
2433 * @param &$after String set to everything after the ':'
2434 * @return String the position of the ':', or false if none found
2436 function findColonNoLinks( $str, &$before, &$after ) {
2437 wfProfileIn( __METHOD__
);
2439 $pos = strpos( $str, ':' );
2440 if ( $pos === false ) {
2442 wfProfileOut( __METHOD__
);
2446 $lt = strpos( $str, '<' );
2447 if ( $lt === false ||
$lt > $pos ) {
2448 # Easy; no tag nesting to worry about
2449 $before = substr( $str, 0, $pos );
2450 $after = substr( $str, $pos+
1 );
2451 wfProfileOut( __METHOD__
);
2455 # Ugly state machine to walk through avoiding tags.
2456 $state = self
::COLON_STATE_TEXT
;
2458 $len = strlen( $str );
2459 for( $i = 0; $i < $len; $i++
) {
2463 # (Using the number is a performance hack for common cases)
2464 case 0: # self::COLON_STATE_TEXT:
2467 # Could be either a <start> tag or an </end> tag
2468 $state = self
::COLON_STATE_TAGSTART
;
2471 if ( $stack == 0 ) {
2473 $before = substr( $str, 0, $i );
2474 $after = substr( $str, $i +
1 );
2475 wfProfileOut( __METHOD__
);
2478 # Embedded in a tag; don't break it.
2481 # Skip ahead looking for something interesting
2482 $colon = strpos( $str, ':', $i );
2483 if ( $colon === false ) {
2484 # Nothing else interesting
2485 wfProfileOut( __METHOD__
);
2488 $lt = strpos( $str, '<', $i );
2489 if ( $stack === 0 ) {
2490 if ( $lt === false ||
$colon < $lt ) {
2492 $before = substr( $str, 0, $colon );
2493 $after = substr( $str, $colon +
1 );
2494 wfProfileOut( __METHOD__
);
2498 if ( $lt === false ) {
2499 # Nothing else interesting to find; abort!
2500 # We're nested, but there's no close tags left. Abort!
2503 # Skip ahead to next tag start
2505 $state = self
::COLON_STATE_TAGSTART
;
2508 case 1: # self::COLON_STATE_TAG:
2513 $state = self
::COLON_STATE_TEXT
;
2516 # Slash may be followed by >?
2517 $state = self
::COLON_STATE_TAGSLASH
;
2523 case 2: # self::COLON_STATE_TAGSTART:
2526 $state = self
::COLON_STATE_CLOSETAG
;
2529 $state = self
::COLON_STATE_COMMENT
;
2532 # Illegal early close? This shouldn't happen D:
2533 $state = self
::COLON_STATE_TEXT
;
2536 $state = self
::COLON_STATE_TAG
;
2539 case 3: # self::COLON_STATE_CLOSETAG:
2544 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2545 wfProfileOut( __METHOD__
);
2548 $state = self
::COLON_STATE_TEXT
;
2551 case self
::COLON_STATE_TAGSLASH
:
2553 # Yes, a self-closed tag <blah/>
2554 $state = self
::COLON_STATE_TEXT
;
2556 # Probably we're jumping the gun, and this is an attribute
2557 $state = self
::COLON_STATE_TAG
;
2560 case 5: # self::COLON_STATE_COMMENT:
2562 $state = self
::COLON_STATE_COMMENTDASH
;
2565 case self
::COLON_STATE_COMMENTDASH
:
2567 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2569 $state = self
::COLON_STATE_COMMENT
;
2572 case self
::COLON_STATE_COMMENTDASHDASH
:
2574 $state = self
::COLON_STATE_TEXT
;
2576 $state = self
::COLON_STATE_COMMENT
;
2580 throw new MWException( "State machine error in " . __METHOD__
);
2584 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2585 wfProfileOut( __METHOD__
);
2588 wfProfileOut( __METHOD__
);
2593 * Return value of a magic variable (like PAGENAME)
2597 * @param $index integer
2598 * @param $frame PPFrame
2602 function getVariableValue( $index, $frame = false ) {
2603 global $wgContLang, $wgSitename, $wgServer;
2604 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2606 if ( is_null( $this->mTitle
) ) {
2607 // If no title set, bad things are going to happen
2608 // later. Title should always be set since this
2609 // should only be called in the middle of a parse
2610 // operation (but the unit-tests do funky stuff)
2611 throw new MWException( __METHOD__
. ' Should only be '
2612 . ' called while parsing (no title set)' );
2616 * Some of these require message or data lookups and can be
2617 * expensive to check many times.
2619 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2620 if ( isset( $this->mVarCache
[$index] ) ) {
2621 return $this->mVarCache
[$index];
2625 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2626 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2629 global $wgLocaltimezone;
2630 if ( isset( $wgLocaltimezone ) ) {
2631 $oldtz = date_default_timezone_get();
2632 date_default_timezone_set( $wgLocaltimezone );
2635 $localTimestamp = date( 'YmdHis', $ts );
2636 $localMonth = date( 'm', $ts );
2637 $localMonth1 = date( 'n', $ts );
2638 $localMonthName = date( 'n', $ts );
2639 $localDay = date( 'j', $ts );
2640 $localDay2 = date( 'd', $ts );
2641 $localDayOfWeek = date( 'w', $ts );
2642 $localWeek = date( 'W', $ts );
2643 $localYear = date( 'Y', $ts );
2644 $localHour = date( 'H', $ts );
2645 if ( isset( $wgLocaltimezone ) ) {
2646 date_default_timezone_set( $oldtz );
2649 $pageLang = $this->getFunctionLang();
2652 case 'currentmonth':
2653 $value = $pageLang->formatNum( gmdate( 'm', $ts ) );
2655 case 'currentmonth1':
2656 $value = $pageLang->formatNum( gmdate( 'n', $ts ) );
2658 case 'currentmonthname':
2659 $value = $pageLang->getMonthName( gmdate( 'n', $ts ) );
2661 case 'currentmonthnamegen':
2662 $value = $pageLang->getMonthNameGen( gmdate( 'n', $ts ) );
2664 case 'currentmonthabbrev':
2665 $value = $pageLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2668 $value = $pageLang->formatNum( gmdate( 'j', $ts ) );
2671 $value = $pageLang->formatNum( gmdate( 'd', $ts ) );
2674 $value = $pageLang->formatNum( $localMonth );
2677 $value = $pageLang->formatNum( $localMonth1 );
2679 case 'localmonthname':
2680 $value = $pageLang->getMonthName( $localMonthName );
2682 case 'localmonthnamegen':
2683 $value = $pageLang->getMonthNameGen( $localMonthName );
2685 case 'localmonthabbrev':
2686 $value = $pageLang->getMonthAbbreviation( $localMonthName );
2689 $value = $pageLang->formatNum( $localDay );
2692 $value = $pageLang->formatNum( $localDay2 );
2695 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2698 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2700 case 'fullpagename':
2701 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2703 case 'fullpagenamee':
2704 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2707 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2709 case 'subpagenamee':
2710 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2712 case 'basepagename':
2713 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2715 case 'basepagenamee':
2716 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2718 case 'talkpagename':
2719 if ( $this->mTitle
->canTalk() ) {
2720 $talkPage = $this->mTitle
->getTalkPage();
2721 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2726 case 'talkpagenamee':
2727 if ( $this->mTitle
->canTalk() ) {
2728 $talkPage = $this->mTitle
->getTalkPage();
2729 $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() );
2734 case 'subjectpagename':
2735 $subjPage = $this->mTitle
->getSubjectPage();
2736 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2738 case 'subjectpagenamee':
2739 $subjPage = $this->mTitle
->getSubjectPage();
2740 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() );
2742 case 'pageid': // requested in bug 23427
2743 $pageid = $this->getTitle()->getArticleId();
2744 if( $pageid == 0 ) {
2745 # 0 means the page doesn't exist in the database,
2746 # which means the user is previewing a new page.
2747 # The vary-revision flag must be set, because the magic word
2748 # will have a different value once the page is saved.
2749 $this->mOutput
->setFlag( 'vary-revision' );
2750 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2752 $value = $pageid ?
$pageid : null;
2755 # Let the edit saving system know we should parse the page
2756 # *after* a revision ID has been assigned.
2757 $this->mOutput
->setFlag( 'vary-revision' );
2758 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2759 $value = $this->mRevisionId
;
2762 # Let the edit saving system know we should parse the page
2763 # *after* a revision ID has been assigned. This is for null edits.
2764 $this->mOutput
->setFlag( 'vary-revision' );
2765 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2766 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2768 case 'revisionday2':
2769 # Let the edit saving system know we should parse the page
2770 # *after* a revision ID has been assigned. This is for null edits.
2771 $this->mOutput
->setFlag( 'vary-revision' );
2772 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2773 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2775 case 'revisionmonth':
2776 # Let the edit saving system know we should parse the page
2777 # *after* a revision ID has been assigned. This is for null edits.
2778 $this->mOutput
->setFlag( 'vary-revision' );
2779 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2780 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2782 case 'revisionmonth1':
2783 # Let the edit saving system know we should parse the page
2784 # *after* a revision ID has been assigned. This is for null edits.
2785 $this->mOutput
->setFlag( 'vary-revision' );
2786 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2787 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2789 case 'revisionyear':
2790 # Let the edit saving system know we should parse the page
2791 # *after* a revision ID has been assigned. This is for null edits.
2792 $this->mOutput
->setFlag( 'vary-revision' );
2793 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2794 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2796 case 'revisiontimestamp':
2797 # Let the edit saving system know we should parse the page
2798 # *after* a revision ID has been assigned. This is for null edits.
2799 $this->mOutput
->setFlag( 'vary-revision' );
2800 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2801 $value = $this->getRevisionTimestamp();
2803 case 'revisionuser':
2804 # Let the edit saving system know we should parse the page
2805 # *after* a revision ID has been assigned. This is for null edits.
2806 $this->mOutput
->setFlag( 'vary-revision' );
2807 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2808 $value = $this->getRevisionUser();
2811 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2814 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2816 case 'namespacenumber':
2817 $value = $this->mTitle
->getNamespace();
2820 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2823 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2825 case 'subjectspace':
2826 $value = $this->mTitle
->getSubjectNsText();
2828 case 'subjectspacee':
2829 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2831 case 'currentdayname':
2832 $value = $pageLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2835 $value = $pageLang->formatNum( gmdate( 'Y', $ts ), true );
2838 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2841 $value = $pageLang->formatNum( gmdate( 'H', $ts ), true );
2844 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2845 # int to remove the padding
2846 $value = $pageLang->formatNum( (int)gmdate( 'W', $ts ) );
2849 $value = $pageLang->formatNum( gmdate( 'w', $ts ) );
2851 case 'localdayname':
2852 $value = $pageLang->getWeekdayName( $localDayOfWeek +
1 );
2855 $value = $pageLang->formatNum( $localYear, true );
2858 $value = $pageLang->time( $localTimestamp, false, false );
2861 $value = $pageLang->formatNum( $localHour, true );
2864 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2865 # int to remove the padding
2866 $value = $pageLang->formatNum( (int)$localWeek );
2869 $value = $pageLang->formatNum( $localDayOfWeek );
2871 case 'numberofarticles':
2872 $value = $pageLang->formatNum( SiteStats
::articles() );
2874 case 'numberoffiles':
2875 $value = $pageLang->formatNum( SiteStats
::images() );
2877 case 'numberofusers':
2878 $value = $pageLang->formatNum( SiteStats
::users() );
2880 case 'numberofactiveusers':
2881 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2883 case 'numberofpages':
2884 $value = $pageLang->formatNum( SiteStats
::pages() );
2886 case 'numberofadmins':
2887 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2889 case 'numberofedits':
2890 $value = $pageLang->formatNum( SiteStats
::edits() );
2892 case 'numberofviews':
2893 global $wgDisableCounters;
2894 $value = !$wgDisableCounters ?
$pageLang->formatNum( SiteStats
::views() ) : '';
2896 case 'currenttimestamp':
2897 $value = wfTimestamp( TS_MW
, $ts );
2899 case 'localtimestamp':
2900 $value = $localTimestamp;
2902 case 'currentversion':
2903 $value = SpecialVersion
::getVersion();
2906 return $wgArticlePath;
2912 $serverParts = wfParseUrl( $wgServer );
2913 return $serverParts && isset( $serverParts['host'] ) ?
$serverParts['host'] : $wgServer;
2915 return $wgScriptPath;
2917 return $wgStylePath;
2918 case 'directionmark':
2919 return $pageLang->getDirMark();
2920 case 'contentlanguage':
2921 global $wgLanguageCode;
2922 return $wgLanguageCode;
2925 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2933 $this->mVarCache
[$index] = $value;
2940 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2944 function initialiseVariables() {
2945 wfProfileIn( __METHOD__
);
2946 $variableIDs = MagicWord
::getVariableIDs();
2947 $substIDs = MagicWord
::getSubstIDs();
2949 $this->mVariables
= new MagicWordArray( $variableIDs );
2950 $this->mSubstWords
= new MagicWordArray( $substIDs );
2951 wfProfileOut( __METHOD__
);
2955 * Preprocess some wikitext and return the document tree.
2956 * This is the ghost of replace_variables().
2958 * @param $text String: The text to parse
2959 * @param $flags Integer: bitwise combination of:
2960 * self::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
2961 * included. Default is to assume a direct page view.
2963 * The generated DOM tree must depend only on the input text and the flags.
2964 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2966 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2967 * change in the DOM tree for a given text, must be passed through the section identifier
2968 * in the section edit link and thus back to extractSections().
2970 * The output of this function is currently only cached in process memory, but a persistent
2971 * cache may be implemented at a later date which takes further advantage of these strict
2972 * dependency requirements.
2978 function preprocessToDom( $text, $flags = 0 ) {
2979 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2984 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2990 public static function splitWhitespace( $s ) {
2991 $ltrimmed = ltrim( $s );
2992 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2993 $trimmed = rtrim( $ltrimmed );
2994 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2996 $w2 = substr( $ltrimmed, -$diff );
3000 return array( $w1, $trimmed, $w2 );
3004 * Replace magic variables, templates, and template arguments
3005 * with the appropriate text. Templates are substituted recursively,
3006 * taking care to avoid infinite loops.
3008 * Note that the substitution depends on value of $mOutputType:
3009 * self::OT_WIKI: only {{subst:}} templates
3010 * self::OT_PREPROCESS: templates but not extension tags
3011 * self::OT_HTML: all templates and extension tags
3013 * @param $text String the text to transform
3014 * @param $frame PPFrame Object describing the arguments passed to the template.
3015 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
3016 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
3017 * @param $argsOnly Boolean only do argument (triple-brace) expansion, not double-brace expansion
3022 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3023 # Is there any text? Also, Prevent too big inclusions!
3024 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3027 wfProfileIn( __METHOD__
);
3029 if ( $frame === false ) {
3030 $frame = $this->getPreprocessor()->newFrame();
3031 } elseif ( !( $frame instanceof PPFrame
) ) {
3032 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
3033 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3036 $dom = $this->preprocessToDom( $text );
3037 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3038 $text = $frame->expand( $dom, $flags );
3040 wfProfileOut( __METHOD__
);
3045 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3047 * @param $args array
3051 static function createAssocArgs( $args ) {
3052 $assocArgs = array();
3054 foreach ( $args as $arg ) {
3055 $eqpos = strpos( $arg, '=' );
3056 if ( $eqpos === false ) {
3057 $assocArgs[$index++
] = $arg;
3059 $name = trim( substr( $arg, 0, $eqpos ) );
3060 $value = trim( substr( $arg, $eqpos+
1 ) );
3061 if ( $value === false ) {
3064 if ( $name !== false ) {
3065 $assocArgs[$name] = $value;
3074 * Warn the user when a parser limitation is reached
3075 * Will warn at most once the user per limitation type
3077 * @param $limitationType String: should be one of:
3078 * 'expensive-parserfunction' (corresponding messages:
3079 * 'expensive-parserfunction-warning',
3080 * 'expensive-parserfunction-category')
3081 * 'post-expand-template-argument' (corresponding messages:
3082 * 'post-expand-template-argument-warning',
3083 * 'post-expand-template-argument-category')
3084 * 'post-expand-template-inclusion' (corresponding messages:
3085 * 'post-expand-template-inclusion-warning',
3086 * 'post-expand-template-inclusion-category')
3087 * @param $current int|null Current value
3088 * @param $max int|null Maximum allowed, when an explicit limit has been
3089 * exceeded, provide the values (optional)
3091 function limitationWarn( $limitationType, $current = '', $max = '' ) {
3092 # does no harm if $current and $max are present but are unnecessary for the message
3093 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3094 ->inContentLanguage()->escaped();
3095 $this->mOutput
->addWarning( $warning );
3096 $this->addTrackingCategory( "$limitationType-category" );
3100 * Return the text of a template, after recursively
3101 * replacing any variables or templates within the template.
3103 * @param $piece Array: the parts of the template
3104 * $piece['title']: the title, i.e. the part before the |
3105 * $piece['parts']: the parameter array
3106 * $piece['lineStart']: whether the brace was at the start of a line
3107 * @param $frame PPFrame The current frame, contains template arguments
3108 * @return String: the text of the template
3111 function braceSubstitution( $piece, $frame ) {
3113 wfProfileIn( __METHOD__
);
3114 wfProfileIn( __METHOD__
.'-setup' );
3117 $found = false; # $text has been filled
3118 $nowiki = false; # wiki markup in $text should be escaped
3119 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3120 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3121 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3122 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3124 # Title object, where $text came from
3127 # $part1 is the bit before the first |, and must contain only title characters.
3128 # Various prefixes will be stripped from it later.
3129 $titleWithSpaces = $frame->expand( $piece['title'] );
3130 $part1 = trim( $titleWithSpaces );
3133 # Original title text preserved for various purposes
3134 $originalTitle = $part1;
3136 # $args is a list of argument nodes, starting from index 0, not including $part1
3137 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3138 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3139 wfProfileOut( __METHOD__
.'-setup' );
3141 $titleProfileIn = null; // profile templates
3144 wfProfileIn( __METHOD__
.'-modifiers' );
3147 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3149 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3150 # Decide whether to expand template or keep wikitext as-is.
3151 if ( $this->ot
['wiki'] ) {
3152 if ( $substMatch === false ) {
3153 $literal = true; # literal when in PST with no prefix
3155 $literal = false; # expand when in PST with subst: or safesubst:
3158 if ( $substMatch == 'subst' ) {
3159 $literal = true; # literal when not in PST with plain subst:
3161 $literal = false; # expand when not in PST with safesubst: or no prefix
3165 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3172 if ( !$found && $args->getLength() == 0 ) {
3173 $id = $this->mVariables
->matchStartToEnd( $part1 );
3174 if ( $id !== false ) {
3175 $text = $this->getVariableValue( $id, $frame );
3176 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3177 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3183 # MSG, MSGNW and RAW
3186 $mwMsgnw = MagicWord
::get( 'msgnw' );
3187 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3190 # Remove obsolete MSG:
3191 $mwMsg = MagicWord
::get( 'msg' );
3192 $mwMsg->matchStartAndRemove( $part1 );
3196 $mwRaw = MagicWord
::get( 'raw' );
3197 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3198 $forceRawInterwiki = true;
3201 wfProfileOut( __METHOD__
.'-modifiers' );
3205 wfProfileIn( __METHOD__
. '-pfunc' );
3207 $colonPos = strpos( $part1, ':' );
3208 if ( $colonPos !== false ) {
3209 # Case sensitive functions
3210 $function = substr( $part1, 0, $colonPos );
3211 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3212 $function = $this->mFunctionSynonyms
[1][$function];
3214 # Case insensitive functions
3215 $function = $wgContLang->lc( $function );
3216 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3217 $function = $this->mFunctionSynonyms
[0][$function];
3223 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3224 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3225 $initialArgs = array( &$this );
3226 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3227 if ( $flags & SFH_OBJECT_ARGS
) {
3228 # Add a frame parameter, and pass the arguments as an array
3229 $allArgs = $initialArgs;
3230 $allArgs[] = $frame;
3231 for ( $i = 0; $i < $args->getLength(); $i++
) {
3232 $funcArgs[] = $args->item( $i );
3234 $allArgs[] = $funcArgs;
3236 # Convert arguments to plain text
3237 for ( $i = 0; $i < $args->getLength(); $i++
) {
3238 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3240 $allArgs = array_merge( $initialArgs, $funcArgs );
3243 # Workaround for PHP bug 35229 and similar
3244 if ( !is_callable( $callback ) ) {
3245 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3246 wfProfileOut( __METHOD__
. '-pfunc' );
3247 wfProfileOut( __METHOD__
);
3248 throw new MWException( "Tag hook for $function is not callable\n" );
3250 $result = call_user_func_array( $callback, $allArgs );
3253 $preprocessFlags = 0;
3255 if ( is_array( $result ) ) {
3256 if ( isset( $result[0] ) ) {
3258 unset( $result[0] );
3261 # Extract flags into the local scope
3262 # This allows callers to set flags such as nowiki, found, etc.
3268 $text = $this->preprocessToDom( $text, $preprocessFlags );
3271 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3274 wfProfileOut( __METHOD__
. '-pfunc' );
3277 # Finish mangling title and then check for loops.
3278 # Set $title to a Title object and $titleText to the PDBK
3281 # Split the title into page and subpage
3283 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3284 if ( $subpage !== '' ) {
3285 $ns = $this->mTitle
->getNamespace();
3287 $title = Title
::newFromText( $part1, $ns );
3289 $titleText = $title->getPrefixedText();
3290 # Check for language variants if the template is not found
3291 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3292 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3294 # Do recursion depth check
3295 $limit = $this->mOptions
->getMaxTemplateDepth();
3296 if ( $frame->depth
>= $limit ) {
3298 $text = '<span class="error">'
3299 . wfMessage( 'parser-template-recursion-depth-warning' )
3300 ->numParams( $limit )->inContentLanguage()->text()
3306 # Load from database
3307 if ( !$found && $title ) {
3308 if ( !Profiler
::instance()->isPersistent() ) {
3309 # Too many unique items can kill profiling DBs/collectors
3310 $titleProfileIn = __METHOD__
. "-title-" . $title->getDBKey();
3311 wfProfileIn( $titleProfileIn ); // template in
3313 wfProfileIn( __METHOD__
. '-loadtpl' );
3314 if ( !$title->isExternal() ) {
3315 if ( $title->isSpecialPage()
3316 && $this->mOptions
->getAllowSpecialInclusion()
3317 && $this->ot
['html'] )
3319 // Pass the template arguments as URL parameters.
3320 // "uselang" will have no effect since the Language object
3321 // is forced to the one defined in ParserOptions.
3322 $pageArgs = array();
3323 for ( $i = 0; $i < $args->getLength(); $i++
) {
3324 $bits = $args->item( $i )->splitArg();
3325 if ( strval( $bits['index'] ) === '' ) {
3326 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3327 $value = trim( $frame->expand( $bits['value'] ) );
3328 $pageArgs[$name] = $value;
3332 // Create a new context to execute the special page
3333 $context = new RequestContext
;
3334 $context->setTitle( $title );
3335 $context->setRequest( new FauxRequest( $pageArgs ) );
3336 $context->setUser( $this->getUser() );
3337 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3338 $ret = SpecialPageFactory
::capturePath( $title, $context );
3340 $text = $context->getOutput()->getHTML();
3341 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3344 $this->disableCache();
3346 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3347 $found = false; # access denied
3348 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3350 list( $text, $title ) = $this->getTemplateDom( $title );
3351 if ( $text !== false ) {
3357 # If the title is valid but undisplayable, make a link to it
3358 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3359 $text = "[[:$titleText]]";
3362 } elseif ( $title->isTrans() ) {
3363 # Interwiki transclusion
3364 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3365 $text = $this->interwikiTransclude( $title, 'render' );
3368 $text = $this->interwikiTransclude( $title, 'raw' );
3369 # Preprocess it like a template
3370 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3376 # Do infinite loop check
3377 # This has to be done after redirect resolution to avoid infinite loops via redirects
3378 if ( !$frame->loopCheck( $title ) ) {
3380 $text = '<span class="error">'
3381 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3383 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3385 wfProfileOut( __METHOD__
. '-loadtpl' );
3388 # If we haven't found text to substitute by now, we're done
3389 # Recover the source wikitext and return it
3391 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3392 if ( $titleProfileIn ) {
3393 wfProfileOut( $titleProfileIn ); // template out
3395 wfProfileOut( __METHOD__
);
3396 return array( 'object' => $text );
3399 # Expand DOM-style return values in a child frame
3400 if ( $isChildObj ) {
3401 # Clean up argument array
3402 $newFrame = $frame->newChild( $args, $title );
3405 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3406 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3407 # Expansion is eligible for the empty-frame cache
3408 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3409 $text = $this->mTplExpandCache
[$titleText];
3411 $text = $newFrame->expand( $text );
3412 $this->mTplExpandCache
[$titleText] = $text;
3415 # Uncached expansion
3416 $text = $newFrame->expand( $text );
3419 if ( $isLocalObj && $nowiki ) {
3420 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3421 $isLocalObj = false;
3424 if ( $titleProfileIn ) {
3425 wfProfileOut( $titleProfileIn ); // template out
3428 # Replace raw HTML by a placeholder
3430 $text = $this->insertStripItem( $text );
3431 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3432 # Escape nowiki-style return values
3433 $text = wfEscapeWikiText( $text );
3434 } elseif ( is_string( $text )
3435 && !$piece['lineStart']
3436 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3438 # Bug 529: if the template begins with a table or block-level
3439 # element, it should be treated as beginning a new line.
3440 # This behaviour is somewhat controversial.
3441 $text = "\n" . $text;
3444 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3445 # Error, oversize inclusion
3446 if ( $titleText !== false ) {
3447 # Make a working, properly escaped link if possible (bug 23588)
3448 $text = "[[:$titleText]]";
3450 # This will probably not be a working link, but at least it may
3451 # provide some hint of where the problem is
3452 preg_replace( '/^:/', '', $originalTitle );
3453 $text = "[[:$originalTitle]]";
3455 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3456 $this->limitationWarn( 'post-expand-template-inclusion' );
3459 if ( $isLocalObj ) {
3460 $ret = array( 'object' => $text );
3462 $ret = array( 'text' => $text );
3465 wfProfileOut( __METHOD__
);
3470 * Get the semi-parsed DOM representation of a template with a given title,
3471 * and its redirect destination title. Cached.
3473 * @param $title Title
3477 function getTemplateDom( $title ) {
3478 $cacheTitle = $title;
3479 $titleText = $title->getPrefixedDBkey();
3481 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3482 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3483 $title = Title
::makeTitle( $ns, $dbk );
3484 $titleText = $title->getPrefixedDBkey();
3486 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3487 return array( $this->mTplDomCache
[$titleText], $title );
3490 # Cache miss, go to the database
3491 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3493 if ( $text === false ) {
3494 $this->mTplDomCache
[$titleText] = false;
3495 return array( false, $title );
3498 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3499 $this->mTplDomCache
[ $titleText ] = $dom;
3501 if ( !$title->equals( $cacheTitle ) ) {
3502 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3503 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3506 return array( $dom, $title );
3510 * Fetch the unparsed text of a template and register a reference to it.
3511 * @param Title $title
3512 * @return Array ( string or false, Title )
3514 function fetchTemplateAndTitle( $title ) {
3515 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3516 $stuff = call_user_func( $templateCb, $title, $this );
3517 $text = $stuff['text'];
3518 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3519 if ( isset( $stuff['deps'] ) ) {
3520 foreach ( $stuff['deps'] as $dep ) {
3521 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3524 return array( $text, $finalTitle );
3528 * Fetch the unparsed text of a template and register a reference to it.
3529 * @param Title $title
3530 * @return mixed string or false
3532 function fetchTemplate( $title ) {
3533 $rv = $this->fetchTemplateAndTitle( $title );
3538 * Static function to get a template
3539 * Can be overridden via ParserOptions::setTemplateCallback().
3541 * @param $title Title
3542 * @param $parser Parser
3546 static function statelessFetchTemplate( $title, $parser = false ) {
3547 $text = $skip = false;
3548 $finalTitle = $title;
3551 # Loop to fetch the article, with up to 1 redirect
3552 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3553 # Give extensions a chance to select the revision instead
3554 $id = false; # Assume current
3555 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3556 array( $parser, $title, &$skip, &$id ) );
3562 'page_id' => $title->getArticleID(),
3569 ? Revision
::newFromId( $id )
3570 : Revision
::newFromTitle( $title, false, Revision
::READ_NORMAL
);
3571 $rev_id = $rev ?
$rev->getId() : 0;
3572 # If there is no current revision, there is no page
3573 if ( $id === false && !$rev ) {
3574 $linkCache = LinkCache
::singleton();
3575 $linkCache->addBadLinkObj( $title );
3580 'page_id' => $title->getArticleID(),
3581 'rev_id' => $rev_id );
3582 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3583 # We fetched a rev from a different title; register it too...
3585 'title' => $rev->getTitle(),
3586 'page_id' => $rev->getPage(),
3587 'rev_id' => $rev_id );
3591 $text = $rev->getText();
3592 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3594 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3595 if ( !$message->exists() ) {
3599 $text = $message->plain();
3603 if ( $text === false ) {
3607 $finalTitle = $title;
3608 $title = Title
::newFromRedirect( $text );
3612 'finalTitle' => $finalTitle,
3617 * Fetch a file and its title and register a reference to it.
3618 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3619 * @param Title $title
3620 * @param Array $options Array of options to RepoGroup::findFile
3623 function fetchFile( $title, $options = array() ) {
3624 $res = $this->fetchFileAndTitle( $title, $options );
3629 * Fetch a file and its title and register a reference to it.
3630 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3631 * @param Title $title
3632 * @param Array $options Array of options to RepoGroup::findFile
3633 * @return Array ( File or false, Title of file )
3635 function fetchFileAndTitle( $title, $options = array() ) {
3636 if ( isset( $options['broken'] ) ) {
3637 $file = false; // broken thumbnail forced by hook
3638 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3639 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3640 } else { // get by (name,timestamp)
3641 $file = wfFindFile( $title, $options );
3643 $time = $file ?
$file->getTimestamp() : false;
3644 $sha1 = $file ?
$file->getSha1() : false;
3645 # Register the file as a dependency...
3646 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3647 if ( $file && !$title->equals( $file->getTitle() ) ) {
3648 # Update fetched file title
3649 $title = $file->getTitle();
3650 if ( is_null( $file->getRedirectedTitle() ) ) {
3651 # This file was not a redirect, but the title does not match.
3652 # Register under the new name because otherwise the link will
3654 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3657 return array( $file, $title );
3661 * Transclude an interwiki link.
3663 * @param $title Title
3668 function interwikiTransclude( $title, $action ) {
3669 global $wgEnableScaryTranscluding;
3671 if ( !$wgEnableScaryTranscluding ) {
3672 return wfMessage('scarytranscludedisabled')->inContentLanguage()->text();
3675 $url = $title->getFullUrl( "action=$action" );
3677 if ( strlen( $url ) > 255 ) {
3678 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3680 return $this->fetchScaryTemplateMaybeFromCache( $url );
3684 * @param $url string
3685 * @return Mixed|String
3687 function fetchScaryTemplateMaybeFromCache( $url ) {
3688 global $wgTranscludeCacheExpiry;
3689 $dbr = wfGetDB( DB_SLAVE
);
3690 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3691 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3692 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3694 return $obj->tc_contents
;
3697 $text = Http
::get( $url );
3699 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3702 $dbw = wfGetDB( DB_MASTER
);
3703 $dbw->replace( 'transcache', array('tc_url'), array(
3705 'tc_time' => $dbw->timestamp( time() ),
3706 'tc_contents' => $text)
3712 * Triple brace replacement -- used for template arguments
3715 * @param $piece array
3716 * @param $frame PPFrame
3720 function argSubstitution( $piece, $frame ) {
3721 wfProfileIn( __METHOD__
);
3724 $parts = $piece['parts'];
3725 $nameWithSpaces = $frame->expand( $piece['title'] );
3726 $argName = trim( $nameWithSpaces );
3728 $text = $frame->getArgument( $argName );
3729 if ( $text === false && $parts->getLength() > 0
3733 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3736 # No match in frame, use the supplied default
3737 $object = $parts->item( 0 )->getChildren();
3739 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3740 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3741 $this->limitationWarn( 'post-expand-template-argument' );
3744 if ( $text === false && $object === false ) {
3746 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3748 if ( $error !== false ) {
3751 if ( $object !== false ) {
3752 $ret = array( 'object' => $object );
3754 $ret = array( 'text' => $text );
3757 wfProfileOut( __METHOD__
);
3762 * Return the text to be used for a given extension tag.
3763 * This is the ghost of strip().
3765 * @param $params array Associative array of parameters:
3766 * name PPNode for the tag name
3767 * attr PPNode for unparsed text where tag attributes are thought to be
3768 * attributes Optional associative array of parsed attributes
3769 * inner Contents of extension element
3770 * noClose Original text did not have a close tag
3771 * @param $frame PPFrame
3775 function extensionSubstitution( $params, $frame ) {
3776 $name = $frame->expand( $params['name'] );
3777 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3778 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3779 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3781 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3782 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3783 if ( $isFunctionTag ) {
3784 $markerType = 'none';
3786 $markerType = 'general';
3788 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3789 $name = strtolower( $name );
3790 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3791 if ( isset( $params['attributes'] ) ) {
3792 $attributes = $attributes +
$params['attributes'];
3795 if ( isset( $this->mTagHooks
[$name] ) ) {
3796 # Workaround for PHP bug 35229 and similar
3797 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3798 throw new MWException( "Tag hook for $name is not callable\n" );
3800 $output = call_user_func_array( $this->mTagHooks
[$name],
3801 array( $content, $attributes, $this, $frame ) );
3802 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3803 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3804 if ( !is_callable( $callback ) ) {
3805 throw new MWException( "Tag hook for $name is not callable\n" );
3808 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3810 $output = '<span class="error">Invalid tag extension name: ' .
3811 htmlspecialchars( $name ) . '</span>';
3814 if ( is_array( $output ) ) {
3815 # Extract flags to local scope (to override $markerType)
3817 $output = $flags[0];
3822 if ( is_null( $attrText ) ) {
3825 if ( isset( $params['attributes'] ) ) {
3826 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3827 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3828 htmlspecialchars( $attrValue ) . '"';
3831 if ( $content === null ) {
3832 $output = "<$name$attrText/>";
3834 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3835 $output = "<$name$attrText>$content$close";
3839 if ( $markerType === 'none' ) {
3841 } elseif ( $markerType === 'nowiki' ) {
3842 $this->mStripState
->addNoWiki( $marker, $output );
3843 } elseif ( $markerType === 'general' ) {
3844 $this->mStripState
->addGeneral( $marker, $output );
3846 throw new MWException( __METHOD__
.': invalid marker type' );
3852 * Increment an include size counter
3854 * @param $type String: the type of expansion
3855 * @param $size Integer: the size of the text
3856 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3858 function incrementIncludeSize( $type, $size ) {
3859 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3862 $this->mIncludeSizes
[$type] +
= $size;
3868 * Increment the expensive function count
3870 * @return Boolean: false if the limit has been exceeded
3872 function incrementExpensiveFunctionCount() {
3873 $this->mExpensiveFunctionCount++
;
3874 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
3878 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3879 * Fills $this->mDoubleUnderscores, returns the modified text
3881 * @param $text string
3885 function doDoubleUnderscore( $text ) {
3886 wfProfileIn( __METHOD__
);
3888 # The position of __TOC__ needs to be recorded
3889 $mw = MagicWord
::get( 'toc' );
3890 if ( $mw->match( $text ) ) {
3891 $this->mShowToc
= true;
3892 $this->mForceTocPosition
= true;
3894 # Set a placeholder. At the end we'll fill it in with the TOC.
3895 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3897 # Only keep the first one.
3898 $text = $mw->replace( '', $text );
3901 # Now match and remove the rest of them
3902 $mwa = MagicWord
::getDoubleUnderscoreArray();
3903 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3905 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3906 $this->mOutput
->mNoGallery
= true;
3908 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3909 $this->mShowToc
= false;
3911 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3912 $this->addTrackingCategory( 'hidden-category-category' );
3914 # (bug 8068) Allow control over whether robots index a page.
3916 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
3917 # is not desirable, the last one on the page should win.
3918 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3919 $this->mOutput
->setIndexPolicy( 'noindex' );
3920 $this->addTrackingCategory( 'noindex-category' );
3922 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3923 $this->mOutput
->setIndexPolicy( 'index' );
3924 $this->addTrackingCategory( 'index-category' );
3927 # Cache all double underscores in the database
3928 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
3929 $this->mOutput
->setProperty( $key, '' );
3932 wfProfileOut( __METHOD__
);
3937 * Add a tracking category, getting the title from a system message,
3938 * or print a debug message if the title is invalid.
3940 * @param $msg String: message key
3941 * @return Boolean: whether the addition was successful
3943 public function addTrackingCategory( $msg ) {
3944 if ( $this->mTitle
->getNamespace() === NS_SPECIAL
) {
3945 wfDebug( __METHOD__
.": Not adding tracking category $msg to special page!\n" );
3948 // Important to parse with correct title (bug 31469)
3949 $cat = wfMessage( $msg )
3950 ->title( $this->getTitle() )
3951 ->inContentLanguage()
3954 # Allow tracking categories to be disabled by setting them to "-"
3955 if ( $cat === '-' ) {
3959 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3960 if ( $containerCategory ) {
3961 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3964 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3970 * This function accomplishes several tasks:
3971 * 1) Auto-number headings if that option is enabled
3972 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3973 * 3) Add a Table of contents on the top for users who have enabled the option
3974 * 4) Auto-anchor headings
3976 * It loops through all headlines, collects the necessary data, then splits up the
3977 * string and re-inserts the newly formatted headlines.
3979 * @param $text String
3980 * @param $origText String: original, untouched wikitext
3981 * @param $isMain Boolean
3982 * @return mixed|string
3985 function formatHeadings( $text, $origText, $isMain=true ) {
3986 global $wgMaxTocLevel, $wgHtml5, $wgExperimentalHtmlIds;
3988 # Inhibit editsection links if requested in the page
3989 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3990 $maybeShowEditLink = $showEditLink = false;
3992 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
3993 $showEditLink = $this->mOptions
->getEditSection();
3995 if ( $showEditLink ) {
3996 $this->mOutput
->setEditSectionTokens( true );
3999 # Get all headlines for numbering them and adding funky stuff like [edit]
4000 # links - this is for later, but we need the number of headlines right now
4002 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
4004 # if there are fewer than 4 headlines in the article, do not show TOC
4005 # unless it's been explicitly enabled.
4006 $enoughToc = $this->mShowToc
&&
4007 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4009 # Allow user to stipulate that a page should have a "new section"
4010 # link added via __NEWSECTIONLINK__
4011 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4012 $this->mOutput
->setNewSection( true );
4015 # Allow user to remove the "new section"
4016 # link via __NONEWSECTIONLINK__
4017 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4018 $this->mOutput
->hideNewSection( true );
4021 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4022 # override above conditions and always show TOC above first header
4023 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4024 $this->mShowToc
= true;
4032 # Ugh .. the TOC should have neat indentation levels which can be
4033 # passed to the skin functions. These are determined here
4037 $sublevelCount = array();
4038 $levelCount = array();
4043 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4044 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4045 $oldType = $this->mOutputType
;
4046 $this->setOutputType( self
::OT_WIKI
);
4047 $frame = $this->getPreprocessor()->newFrame();
4048 $root = $this->preprocessToDom( $origText );
4049 $node = $root->getFirstChild();
4054 foreach ( $matches[3] as $headline ) {
4055 $isTemplate = false;
4057 $sectionIndex = false;
4059 $markerMatches = array();
4060 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
4061 $serial = $markerMatches[1];
4062 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4063 $isTemplate = ( $titleText != $baseTitleText );
4064 $headline = preg_replace( "/^$markerRegex/", "", $headline );
4068 $prevlevel = $level;
4070 $level = $matches[1][$headlineCount];
4072 if ( $level > $prevlevel ) {
4073 # Increase TOC level
4075 $sublevelCount[$toclevel] = 0;
4076 if ( $toclevel<$wgMaxTocLevel ) {
4077 $prevtoclevel = $toclevel;
4078 $toc .= Linker
::tocIndent();
4081 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4082 # Decrease TOC level, find level to jump to
4084 for ( $i = $toclevel; $i > 0; $i-- ) {
4085 if ( $levelCount[$i] == $level ) {
4086 # Found last matching level
4089 } elseif ( $levelCount[$i] < $level ) {
4090 # Found first matching level below current level
4098 if ( $toclevel<$wgMaxTocLevel ) {
4099 if ( $prevtoclevel < $wgMaxTocLevel ) {
4100 # Unindent only if the previous toc level was shown :p
4101 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4102 $prevtoclevel = $toclevel;
4104 $toc .= Linker
::tocLineEnd();
4108 # No change in level, end TOC line
4109 if ( $toclevel<$wgMaxTocLevel ) {
4110 $toc .= Linker
::tocLineEnd();
4114 $levelCount[$toclevel] = $level;
4116 # count number of headlines for each level
4117 @$sublevelCount[$toclevel]++
;
4119 for( $i = 1; $i <= $toclevel; $i++
) {
4120 if ( !empty( $sublevelCount[$i] ) ) {
4124 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4129 # The safe header is a version of the header text safe to use for links
4131 # Remove link placeholders by the link text.
4132 # <!--LINK number-->
4134 # link text with suffix
4135 # Do this before unstrip since link text can contain strip markers
4136 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4138 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4139 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4141 # Strip out HTML (first regex removes any tag not allowed)
4142 # Allowed tags are <sup> and <sub> (bug 8393), <i> (bug 26375) and <b> (r105284)
4143 # We strip any parameter from accepted tags (second regex)
4144 $tocline = preg_replace(
4145 array( '#<(?!/?(sup|sub|i|b)(?: [^>]*)?>).*?'.'>#', '#<(/?(sup|sub|i|b))(?: .*?)?'.'>#' ),
4146 array( '', '<$1>' ),
4149 $tocline = trim( $tocline );
4151 # For the anchor, strip out HTML-y stuff period
4152 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
4153 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4155 # Save headline for section edit hint before it's escaped
4156 $headlineHint = $safeHeadline;
4158 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
4159 # For reverse compatibility, provide an id that's
4160 # HTML4-compatible, like we used to.
4162 # It may be worth noting, academically, that it's possible for
4163 # the legacy anchor to conflict with a non-legacy headline
4164 # anchor on the page. In this case likely the "correct" thing
4165 # would be to either drop the legacy anchors or make sure
4166 # they're numbered first. However, this would require people
4167 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4168 # manually, so let's not bother worrying about it.
4169 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4170 array( 'noninitial', 'legacy' ) );
4171 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4173 if ( $legacyHeadline == $safeHeadline ) {
4174 # No reason to have both (in fact, we can't)
4175 $legacyHeadline = false;
4178 $legacyHeadline = false;
4179 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4183 # HTML names must be case-insensitively unique (bug 10721).
4184 # This does not apply to Unicode characters per
4185 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4186 # @todo FIXME: We may be changing them depending on the current locale.
4187 $arrayKey = strtolower( $safeHeadline );
4188 if ( $legacyHeadline === false ) {
4189 $legacyArrayKey = false;
4191 $legacyArrayKey = strtolower( $legacyHeadline );
4194 # count how many in assoc. array so we can track dupes in anchors
4195 if ( isset( $refers[$arrayKey] ) ) {
4196 $refers[$arrayKey]++
;
4198 $refers[$arrayKey] = 1;
4200 if ( isset( $refers[$legacyArrayKey] ) ) {
4201 $refers[$legacyArrayKey]++
;
4203 $refers[$legacyArrayKey] = 1;
4206 # Don't number the heading if it is the only one (looks silly)
4207 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4208 # the two are different if the line contains a link
4209 $headline = Html
::element( 'span', array( 'class' => 'mw-headline-number' ), $numbering ) . ' ' . $headline;
4212 # Create the anchor for linking from the TOC to the section
4213 $anchor = $safeHeadline;
4214 $legacyAnchor = $legacyHeadline;
4215 if ( $refers[$arrayKey] > 1 ) {
4216 $anchor .= '_' . $refers[$arrayKey];
4218 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4219 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4221 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4222 $toc .= Linker
::tocLine( $anchor, $tocline,
4223 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4226 # Add the section to the section tree
4227 # Find the DOM node for this header
4228 while ( $node && !$isTemplate ) {
4229 if ( $node->getName() === 'h' ) {
4230 $bits = $node->splitHeading();
4231 if ( $bits['i'] == $sectionIndex ) {
4235 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4236 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4237 $node = $node->getNextSibling();
4240 'toclevel' => $toclevel,
4243 'number' => $numbering,
4244 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4245 'fromtitle' => $titleText,
4246 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
4247 'anchor' => $anchor,
4250 # give headline the correct <h#> tag
4251 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4252 // Output edit section links as markers with styles that can be customized by skins
4253 if ( $isTemplate ) {
4254 # Put a T flag in the section identifier, to indicate to extractSections()
4255 # that sections inside <includeonly> should be counted.
4256 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4258 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
4260 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4261 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4262 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4263 // so we don't have to worry about a user trying to input one of these markers directly.
4264 // We use a page and section attribute to stop the language converter from converting these important bits
4265 // of data, but put the headline hint inside a content block because the language converter is supposed to
4266 // be able to convert that piece of data.
4267 $editlink = '<mw:editsection page="' . htmlspecialchars($editlinkArgs[0]);
4268 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"';
4269 if ( isset($editlinkArgs[2]) ) {
4270 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4277 $head[$headlineCount] = Linker
::makeHeadline( $level,
4278 $matches['attrib'][$headlineCount], $anchor, $headline,
4279 $editlink, $legacyAnchor );
4284 $this->setOutputType( $oldType );
4286 # Never ever show TOC if no headers
4287 if ( $numVisible < 1 ) {
4292 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4293 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4295 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4296 $this->mOutput
->setTOCHTML( $toc );
4300 $this->mOutput
->setSections( $tocraw );
4303 # split up and insert constructed headlines
4304 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4307 // build an array of document sections
4308 $sections = array();
4309 foreach ( $blocks as $block ) {
4310 // $head is zero-based, sections aren't.
4311 if ( empty( $head[$i - 1] ) ) {
4312 $sections[$i] = $block;
4314 $sections[$i] = $head[$i - 1] . $block;
4318 * Send a hook, one per section.
4319 * The idea here is to be able to make section-level DIVs, but to do so in a
4320 * lower-impact, more correct way than r50769
4323 * $section : the section number
4324 * &$sectionContent : ref to the content of the section
4325 * $showEditLinks : boolean describing whether this section has an edit link
4327 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4332 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4333 // append the TOC at the beginning
4334 // Top anchor now in skin
4335 $sections[0] = $sections[0] . $toc . "\n";
4338 $full .= join( '', $sections );
4340 if ( $this->mForceTocPosition
) {
4341 return str_replace( '<!--MWTOC-->', $toc, $full );
4348 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4349 * conversion, substitting signatures, {{subst:}} templates, etc.
4351 * @param $text String: the text to transform
4352 * @param $title Title: the Title object for the current article
4353 * @param $user User: the User object describing the current user
4354 * @param $options ParserOptions: parsing options
4355 * @param $clearState Boolean: whether to clear the parser state first
4356 * @return String: the altered wiki markup
4358 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4359 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4360 $this->setUser( $user );
4365 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4366 if( $options->getPreSaveTransform() ) {
4367 $text = $this->pstPass2( $text, $user );
4369 $text = $this->mStripState
->unstripBoth( $text );
4371 $this->setUser( null ); #Reset
4377 * Pre-save transform helper function
4380 * @param $text string
4385 function pstPass2( $text, $user ) {
4386 global $wgContLang, $wgLocaltimezone;
4388 # Note: This is the timestamp saved as hardcoded wikitext to
4389 # the database, we use $wgContLang here in order to give
4390 # everyone the same signature and use the default one rather
4391 # than the one selected in each user's preferences.
4392 # (see also bug 12815)
4393 $ts = $this->mOptions
->getTimestamp();
4394 if ( isset( $wgLocaltimezone ) ) {
4395 $tz = $wgLocaltimezone;
4397 $tz = date_default_timezone_get();
4400 $unixts = wfTimestamp( TS_UNIX
, $ts );
4401 $oldtz = date_default_timezone_get();
4402 date_default_timezone_set( $tz );
4403 $ts = date( 'YmdHis', $unixts );
4404 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4406 # Allow translation of timezones through wiki. date() can return
4407 # whatever crap the system uses, localised or not, so we cannot
4408 # ship premade translations.
4409 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4410 $msg = wfMessage( $key )->inContentLanguage();
4411 if ( $msg->exists() ) {
4412 $tzMsg = $msg->text();
4415 date_default_timezone_set( $oldtz );
4417 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4419 # Variable replacement
4420 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4421 $text = $this->replaceVariables( $text );
4423 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4424 # which may corrupt this parser instance via its wfMessage()->text() call-
4427 $sigText = $this->getUserSig( $user );
4428 $text = strtr( $text, array(
4430 '~~~~' => "$sigText $d",
4434 # Context links: [[|name]] and [[name (context)|]]
4435 $tc = '[' . Title
::legalChars() . ']';
4436 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4438 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4439 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]]
4440 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/"; # [[ns:page (context), context|]]
4441 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4443 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4444 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4445 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4446 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4448 $t = $this->mTitle
->getText();
4450 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4451 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4452 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4453 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4455 # if there's no context, don't bother duplicating the title
4456 $text = preg_replace( $p2, '[[\\1]]', $text );
4459 # Trim trailing whitespace
4460 $text = rtrim( $text );
4466 * Fetch the user's signature text, if any, and normalize to
4467 * validated, ready-to-insert wikitext.
4468 * If you have pre-fetched the nickname or the fancySig option, you can
4469 * specify them here to save a database query.
4470 * Do not reuse this parser instance after calling getUserSig(),
4471 * as it may have changed if it's the $wgParser.
4474 * @param $nickname String|bool nickname to use or false to use user's default nickname
4475 * @param $fancySig Boolean|null whether the nicknname is the complete signature
4476 * or null to use default value
4479 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4480 global $wgMaxSigChars;
4482 $username = $user->getName();
4484 # If not given, retrieve from the user object.
4485 if ( $nickname === false )
4486 $nickname = $user->getOption( 'nickname' );
4488 if ( is_null( $fancySig ) ) {
4489 $fancySig = $user->getBoolOption( 'fancysig' );
4492 $nickname = $nickname == null ?
$username : $nickname;
4494 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4495 $nickname = $username;
4496 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4497 } elseif ( $fancySig !== false ) {
4498 # Sig. might contain markup; validate this
4499 if ( $this->validateSig( $nickname ) !== false ) {
4500 # Validated; clean up (if needed) and return it
4501 return $this->cleanSig( $nickname, true );
4503 # Failed to validate; fall back to the default
4504 $nickname = $username;
4505 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4509 # Make sure nickname doesnt get a sig in a sig
4510 $nickname = self
::cleanSigInSig( $nickname );
4512 # If we're still here, make it a link to the user page
4513 $userText = wfEscapeWikiText( $username );
4514 $nickText = wfEscapeWikiText( $nickname );
4515 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4517 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4521 * Check that the user's signature contains no bad XML
4523 * @param $text String
4524 * @return mixed An expanded string, or false if invalid.
4526 function validateSig( $text ) {
4527 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4531 * Clean up signature text
4533 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4534 * 2) Substitute all transclusions
4536 * @param $text String
4537 * @param $parsing bool Whether we're cleaning (preferences save) or parsing
4538 * @return String: signature text
4540 public function cleanSig( $text, $parsing = false ) {
4543 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4546 # Option to disable this feature
4547 if ( !$this->mOptions
->getCleanSignatures() ) {
4551 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4552 # => Move this logic to braceSubstitution()
4553 $substWord = MagicWord
::get( 'subst' );
4554 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4555 $substText = '{{' . $substWord->getSynonym( 0 );
4557 $text = preg_replace( $substRegex, $substText, $text );
4558 $text = self
::cleanSigInSig( $text );
4559 $dom = $this->preprocessToDom( $text );
4560 $frame = $this->getPreprocessor()->newFrame();
4561 $text = $frame->expand( $dom );
4564 $text = $this->mStripState
->unstripBoth( $text );
4571 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4573 * @param $text String
4574 * @return String: signature text with /~{3,5}/ removed
4576 public static function cleanSigInSig( $text ) {
4577 $text = preg_replace( '/~{3,5}/', '', $text );
4582 * Set up some variables which are usually set up in parse()
4583 * so that an external function can call some class members with confidence
4585 * @param $title Title|null
4586 * @param $options ParserOptions
4587 * @param $outputType
4588 * @param $clearState bool
4590 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4591 $this->startParse( $title, $options, $outputType, $clearState );
4595 * @param $title Title|null
4596 * @param $options ParserOptions
4597 * @param $outputType
4598 * @param $clearState bool
4600 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4601 $this->setTitle( $title );
4602 $this->mOptions
= $options;
4603 $this->setOutputType( $outputType );
4604 if ( $clearState ) {
4605 $this->clearState();
4610 * Wrapper for preprocess()
4612 * @param $text String: the text to preprocess
4613 * @param $options ParserOptions: options
4614 * @param $title Title object or null to use $wgTitle
4617 public function transformMsg( $text, $options, $title = null ) {
4618 static $executing = false;
4620 # Guard against infinite recursion
4626 wfProfileIn( __METHOD__
);
4632 # It's not uncommon having a null $wgTitle in scripts. See r80898
4633 # Create a ghost title in such case
4634 $title = Title
::newFromText( 'Dwimmerlaik' );
4636 $text = $this->preprocess( $text, $title, $options );
4639 wfProfileOut( __METHOD__
);
4644 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4645 * The callback should have the following form:
4646 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4648 * Transform and return $text. Use $parser for any required context, e.g. use
4649 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4651 * Hooks may return extended information by returning an array, of which the
4652 * first numbered element (index 0) must be the return string, and all other
4653 * entries are extracted into local variables within an internal function
4654 * in the Parser class.
4656 * This interface (introduced r61913) appears to be undocumented, but
4657 * 'markerName' is used by some core tag hooks to override which strip
4658 * array their results are placed in. **Use great caution if attempting
4659 * this interface, as it is not documented and injudicious use could smash
4660 * private variables.**
4662 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4663 * @param $callback Mixed: the callback function (and object) to use for the tag
4664 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4666 public function setHook( $tag, $callback ) {
4667 $tag = strtolower( $tag );
4668 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4669 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4671 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4672 $this->mTagHooks
[$tag] = $callback;
4673 if ( !in_array( $tag, $this->mStripList
) ) {
4674 $this->mStripList
[] = $tag;
4681 * As setHook(), but letting the contents be parsed.
4683 * Transparent tag hooks are like regular XML-style tag hooks, except they
4684 * operate late in the transformation sequence, on HTML instead of wikitext.
4686 * This is probably obsoleted by things dealing with parser frames?
4687 * The only extension currently using it is geoserver.
4690 * @todo better document or deprecate this
4692 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4693 * @param $callback Mixed: the callback function (and object) to use for the tag
4694 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4696 function setTransparentTagHook( $tag, $callback ) {
4697 $tag = strtolower( $tag );
4698 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4699 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4701 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4702 $this->mTransparentTagHooks
[$tag] = $callback;
4708 * Remove all tag hooks
4710 function clearTagHooks() {
4711 $this->mTagHooks
= array();
4712 $this->mFunctionTagHooks
= array();
4713 $this->mStripList
= $this->mDefaultStripList
;
4717 * Create a function, e.g. {{sum:1|2|3}}
4718 * The callback function should have the form:
4719 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4721 * Or with SFH_OBJECT_ARGS:
4722 * function myParserFunction( $parser, $frame, $args ) { ... }
4724 * The callback may either return the text result of the function, or an array with the text
4725 * in element 0, and a number of flags in the other elements. The names of the flags are
4726 * specified in the keys. Valid flags are:
4727 * found The text returned is valid, stop processing the template. This
4729 * nowiki Wiki markup in the return value should be escaped
4730 * isHTML The returned text is HTML, armour it against wikitext transformation
4732 * @param $id String: The magic word ID
4733 * @param $callback Mixed: the callback function (and object) to use
4734 * @param $flags Integer: a combination of the following flags:
4735 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4737 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4738 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4739 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4740 * the arguments, and to control the way they are expanded.
4742 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4743 * arguments, for instance:
4744 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4746 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4747 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4748 * working if/when this is changed.
4750 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4753 * Please read the documentation in includes/parser/Preprocessor.php for more information
4754 * about the methods available in PPFrame and PPNode.
4756 * @return string|callback The old callback function for this name, if any
4758 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4761 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4762 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4764 # Add to function cache
4765 $mw = MagicWord
::get( $id );
4767 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4769 $synonyms = $mw->getSynonyms();
4770 $sensitive = intval( $mw->isCaseSensitive() );
4772 foreach ( $synonyms as $syn ) {
4774 if ( !$sensitive ) {
4775 $syn = $wgContLang->lc( $syn );
4778 if ( !( $flags & SFH_NO_HASH
) ) {
4781 # Remove trailing colon
4782 if ( substr( $syn, -1, 1 ) === ':' ) {
4783 $syn = substr( $syn, 0, -1 );
4785 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4791 * Get all registered function hook identifiers
4795 function getFunctionHooks() {
4796 return array_keys( $this->mFunctionHooks
);
4800 * Create a tag function, e.g. "<test>some stuff</test>".
4801 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4802 * Unlike parser functions, their content is not preprocessed.
4805 function setFunctionTagHook( $tag, $callback, $flags ) {
4806 $tag = strtolower( $tag );
4807 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4808 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4809 $this->mFunctionTagHooks
[$tag] : null;
4810 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4812 if ( !in_array( $tag, $this->mStripList
) ) {
4813 $this->mStripList
[] = $tag;
4820 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
4821 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
4822 * Placeholders created in Skin::makeLinkObj()
4824 * @param $text string
4825 * @param $options int
4827 * @return array of link CSS classes, indexed by PDBK.
4829 function replaceLinkHolders( &$text, $options = 0 ) {
4830 return $this->mLinkHolders
->replace( $text );
4834 * Replace "<!--LINK-->" link placeholders with plain text of links
4835 * (not HTML-formatted).
4837 * @param $text String
4840 function replaceLinkHoldersText( $text ) {
4841 return $this->mLinkHolders
->replaceText( $text );
4845 * Renders an image gallery from a text with one line per image.
4846 * text labels may be given by using |-style alternative text. E.g.
4847 * Image:one.jpg|The number "1"
4848 * Image:tree.jpg|A tree
4849 * given as text will return the HTML of a gallery with two images,
4850 * labeled 'The number "1"' and
4853 * @param string $text
4854 * @param array $params
4855 * @return string HTML
4857 function renderImageGallery( $text, $params ) {
4858 $ig = new ImageGallery();
4859 $ig->setContextTitle( $this->mTitle
);
4860 $ig->setShowBytes( false );
4861 $ig->setShowFilename( false );
4862 $ig->setParser( $this );
4863 $ig->setHideBadImages();
4864 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4866 if ( isset( $params['showfilename'] ) ) {
4867 $ig->setShowFilename( true );
4869 $ig->setShowFilename( false );
4871 if ( isset( $params['caption'] ) ) {
4872 $caption = $params['caption'];
4873 $caption = htmlspecialchars( $caption );
4874 $caption = $this->replaceInternalLinks( $caption );
4875 $ig->setCaptionHtml( $caption );
4877 if ( isset( $params['perrow'] ) ) {
4878 $ig->setPerRow( $params['perrow'] );
4880 if ( isset( $params['widths'] ) ) {
4881 $ig->setWidths( $params['widths'] );
4883 if ( isset( $params['heights'] ) ) {
4884 $ig->setHeights( $params['heights'] );
4887 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4889 $lines = StringUtils
::explode( "\n", $text );
4890 foreach ( $lines as $line ) {
4891 # match lines like these:
4892 # Image:someimage.jpg|This is some image
4894 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4896 if ( count( $matches ) == 0 ) {
4900 if ( strpos( $matches[0], '%' ) !== false ) {
4901 $matches[1] = rawurldecode( $matches[1] );
4903 $title = Title
::newFromText( $matches[1], NS_FILE
);
4904 if ( is_null( $title ) ) {
4905 # Bogus title. Ignore these so we don't bomb out later.
4912 if ( isset( $matches[3] ) ) {
4913 // look for an |alt= definition while trying not to break existing
4914 // captions with multiple pipes (|) in it, until a more sensible grammar
4915 // is defined for images in galleries
4917 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
4918 $parameterMatches = StringUtils
::explode('|', $matches[3]);
4919 $magicWordAlt = MagicWord
::get( 'img_alt' );
4920 $magicWordLink = MagicWord
::get( 'img_link' );
4922 foreach ( $parameterMatches as $parameterMatch ) {
4923 if ( $match = $magicWordAlt->matchVariableStartToEnd( $parameterMatch ) ) {
4924 $alt = $this->stripAltText( $match, false );
4926 elseif( $match = $magicWordLink->matchVariableStartToEnd( $parameterMatch ) ){
4927 $link = strip_tags($this->replaceLinkHoldersText($match));
4928 $chars = self
::EXT_LINK_URL_CLASS
;
4929 $prots = $this->mUrlProtocols
;
4930 //check to see if link matches an absolute url, if not then it must be a wiki link.
4931 if(!preg_match( "/^($prots)$chars+$/u", $link)){
4932 $localLinkTitle = Title
::newFromText($link);
4933 $link = $localLinkTitle->getLocalURL();
4937 // concatenate all other pipes
4938 $label .= '|' . $parameterMatch;
4941 // remove the first pipe
4942 $label = substr( $label, 1 );
4945 $ig->add( $title, $label, $alt ,$link);
4947 return $ig->toHTML();
4954 function getImageParams( $handler ) {
4956 $handlerClass = get_class( $handler );
4960 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4961 # Initialise static lists
4962 static $internalParamNames = array(
4963 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4964 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4965 'bottom', 'text-bottom' ),
4966 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4967 'upright', 'border', 'link', 'alt', 'class' ),
4969 static $internalParamMap;
4970 if ( !$internalParamMap ) {
4971 $internalParamMap = array();
4972 foreach ( $internalParamNames as $type => $names ) {
4973 foreach ( $names as $name ) {
4974 $magicName = str_replace( '-', '_', "img_$name" );
4975 $internalParamMap[$magicName] = array( $type, $name );
4980 # Add handler params
4981 $paramMap = $internalParamMap;
4983 $handlerParamMap = $handler->getParamMap();
4984 foreach ( $handlerParamMap as $magic => $paramName ) {
4985 $paramMap[$magic] = array( 'handler', $paramName );
4988 $this->mImageParams
[$handlerClass] = $paramMap;
4989 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4991 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4995 * Parse image options text and use it to make an image
4997 * @param $title Title
4998 * @param $options String
4999 * @param $holders LinkHolderArray|bool
5000 * @return string HTML
5002 function makeImage( $title, $options, $holders = false ) {
5003 # Check if the options text is of the form "options|alt text"
5005 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5006 # * left no resizing, just left align. label is used for alt= only
5007 # * right same, but right aligned
5008 # * none same, but not aligned
5009 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5010 # * center center the image
5011 # * frame Keep original image size, no magnify-button.
5012 # * framed Same as "frame"
5013 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5014 # * upright reduce width for upright images, rounded to full __0 px
5015 # * border draw a 1px border around the image
5016 # * alt Text for HTML alt attribute (defaults to empty)
5017 # * class Set a class for img node
5018 # * link Set the target of the image link. Can be external, interwiki, or local
5019 # vertical-align values (no % or length right now):
5029 $parts = StringUtils
::explode( "|", $options );
5031 # Give extensions a chance to select the file revision for us
5034 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5035 array( $this, $title, &$options, &$descQuery ) );
5036 # Fetch and register the file (file title may be different via hooks)
5037 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5040 $handler = $file ?
$file->getHandler() : false;
5042 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5045 $this->addTrackingCategory( 'broken-file-category' );
5048 # Process the input parameters
5050 $params = array( 'frame' => array(), 'handler' => array(),
5051 'horizAlign' => array(), 'vertAlign' => array() );
5052 foreach ( $parts as $part ) {
5053 $part = trim( $part );
5054 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5056 if ( isset( $paramMap[$magicName] ) ) {
5057 list( $type, $paramName ) = $paramMap[$magicName];
5059 # Special case; width and height come in one variable together
5060 if ( $type === 'handler' && $paramName === 'width' ) {
5061 $parsedWidthParam = $this->parseWidthParam( $value );
5062 if( isset( $parsedWidthParam['width'] ) ) {
5063 $width = $parsedWidthParam['width'];
5064 if ( $handler->validateParam( 'width', $width ) ) {
5065 $params[$type]['width'] = $width;
5069 if( isset( $parsedWidthParam['height'] ) ) {
5070 $height = $parsedWidthParam['height'];
5071 if ( $handler->validateParam( 'height', $height ) ) {
5072 $params[$type]['height'] = $height;
5076 # else no validation -- bug 13436
5078 if ( $type === 'handler' ) {
5079 # Validate handler parameter
5080 $validated = $handler->validateParam( $paramName, $value );
5082 # Validate internal parameters
5083 switch( $paramName ) {
5087 # @todo FIXME: Possibly check validity here for
5088 # manualthumb? downstream behavior seems odd with
5089 # missing manual thumbs.
5091 $value = $this->stripAltText( $value, $holders );
5094 $chars = self
::EXT_LINK_URL_CLASS
;
5095 $prots = $this->mUrlProtocols
;
5096 if ( $value === '' ) {
5097 $paramName = 'no-link';
5100 } elseif ( preg_match( "/^(?i)$prots/", $value ) ) {
5101 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5102 $paramName = 'link-url';
5103 $this->mOutput
->addExternalLink( $value );
5104 if ( $this->mOptions
->getExternalLinkTarget() ) {
5105 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5110 $linkTitle = Title
::newFromText( $value );
5112 $paramName = 'link-title';
5113 $value = $linkTitle;
5114 $this->mOutput
->addLink( $linkTitle );
5120 # Most other things appear to be empty or numeric...
5121 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5126 $params[$type][$paramName] = $value;
5130 if ( !$validated ) {
5135 # Process alignment parameters
5136 if ( $params['horizAlign'] ) {
5137 $params['frame']['align'] = key( $params['horizAlign'] );
5139 if ( $params['vertAlign'] ) {
5140 $params['frame']['valign'] = key( $params['vertAlign'] );
5143 $params['frame']['caption'] = $caption;
5145 # Will the image be presented in a frame, with the caption below?
5146 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5147 isset( $params['frame']['framed'] ) ||
5148 isset( $params['frame']['thumbnail'] ) ||
5149 isset( $params['frame']['manualthumb'] );
5151 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5152 # came to also set the caption, ordinary text after the image -- which
5153 # makes no sense, because that just repeats the text multiple times in
5154 # screen readers. It *also* came to set the title attribute.
5156 # Now that we have an alt attribute, we should not set the alt text to
5157 # equal the caption: that's worse than useless, it just repeats the
5158 # text. This is the framed/thumbnail case. If there's no caption, we
5159 # use the unnamed parameter for alt text as well, just for the time be-
5160 # ing, if the unnamed param is set and the alt param is not.
5162 # For the future, we need to figure out if we want to tweak this more,
5163 # e.g., introducing a title= parameter for the title; ignoring the un-
5164 # named parameter entirely for images without a caption; adding an ex-
5165 # plicit caption= parameter and preserving the old magic unnamed para-
5167 if ( $imageIsFramed ) { # Framed image
5168 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5169 # No caption or alt text, add the filename as the alt text so
5170 # that screen readers at least get some description of the image
5171 $params['frame']['alt'] = $title->getText();
5173 # Do not set $params['frame']['title'] because tooltips don't make sense
5175 } else { # Inline image
5176 if ( !isset( $params['frame']['alt'] ) ) {
5177 # No alt text, use the "caption" for the alt text
5178 if ( $caption !== '') {
5179 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5181 # No caption, fall back to using the filename for the
5183 $params['frame']['alt'] = $title->getText();
5186 # Use the "caption" for the tooltip text
5187 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5190 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5192 # Linker does the rest
5193 $time = isset( $options['time'] ) ?
$options['time'] : false;
5194 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5195 $time, $descQuery, $this->mOptions
->getThumbSize() );
5197 # Give the handler a chance to modify the parser object
5199 $handler->parserTransformHook( $this, $file );
5207 * @param $holders LinkHolderArray
5208 * @return mixed|String
5210 protected function stripAltText( $caption, $holders ) {
5211 # Strip bad stuff out of the title (tooltip). We can't just use
5212 # replaceLinkHoldersText() here, because if this function is called
5213 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5215 $tooltip = $holders->replaceText( $caption );
5217 $tooltip = $this->replaceLinkHoldersText( $caption );
5220 # make sure there are no placeholders in thumbnail attributes
5221 # that are later expanded to html- so expand them now and
5223 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5224 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5230 * Set a flag in the output object indicating that the content is dynamic and
5231 * shouldn't be cached.
5233 function disableCache() {
5234 wfDebug( "Parser output marked as uncacheable.\n" );
5235 if ( !$this->mOutput
) {
5236 throw new MWException( __METHOD__
.
5237 " can only be called when actually parsing something" );
5239 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5240 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5244 * Callback from the Sanitizer for expanding items found in HTML attribute
5245 * values, so they can be safely tested and escaped.
5247 * @param $text String
5248 * @param $frame PPFrame
5251 function attributeStripCallback( &$text, $frame = false ) {
5252 $text = $this->replaceVariables( $text, $frame );
5253 $text = $this->mStripState
->unstripBoth( $text );
5262 function getTags() {
5263 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
), array_keys( $this->mFunctionTagHooks
) );
5267 * Replace transparent tags in $text with the values given by the callbacks.
5269 * Transparent tag hooks are like regular XML-style tag hooks, except they
5270 * operate late in the transformation sequence, on HTML instead of wikitext.
5272 * @param $text string
5276 function replaceTransparentTags( $text ) {
5278 $elements = array_keys( $this->mTransparentTagHooks
);
5279 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5280 $replacements = array();
5282 foreach ( $matches as $marker => $data ) {
5283 list( $element, $content, $params, $tag ) = $data;
5284 $tagName = strtolower( $element );
5285 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5286 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
5290 $replacements[$marker] = $output;
5292 return strtr( $text, $replacements );
5296 * Break wikitext input into sections, and either pull or replace
5297 * some particular section's text.
5299 * External callers should use the getSection and replaceSection methods.
5301 * @param $text String: Page wikitext
5302 * @param $section String: a section identifier string of the form:
5303 * "<flag1> - <flag2> - ... - <section number>"
5305 * Currently the only recognised flag is "T", which means the target section number
5306 * was derived during a template inclusion parse, in other words this is a template
5307 * section edit link. If no flags are given, it was an ordinary section edit link.
5308 * This flag is required to avoid a section numbering mismatch when a section is
5309 * enclosed by "<includeonly>" (bug 6563).
5311 * The section number 0 pulls the text before the first heading; other numbers will
5312 * pull the given section along with its lower-level subsections. If the section is
5313 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5315 * Section 0 is always considered to exist, even if it only contains the empty
5316 * string. If $text is the empty string and section 0 is replaced, $newText is
5319 * @param $mode String: one of "get" or "replace"
5320 * @param $newText String: replacement text for section data.
5321 * @return String: for "get", the extracted section text.
5322 * for "replace", the whole page with the section replaced.
5324 private function extractSections( $text, $section, $mode, $newText='' ) {
5325 global $wgTitle; # not generally used but removes an ugly failure mode
5326 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5328 $frame = $this->getPreprocessor()->newFrame();
5330 # Process section extraction flags
5332 $sectionParts = explode( '-', $section );
5333 $sectionIndex = array_pop( $sectionParts );
5334 foreach ( $sectionParts as $part ) {
5335 if ( $part === 'T' ) {
5336 $flags |
= self
::PTD_FOR_INCLUSION
;
5340 # Check for empty input
5341 if ( strval( $text ) === '' ) {
5342 # Only sections 0 and T-0 exist in an empty document
5343 if ( $sectionIndex == 0 ) {
5344 if ( $mode === 'get' ) {
5350 if ( $mode === 'get' ) {
5358 # Preprocess the text
5359 $root = $this->preprocessToDom( $text, $flags );
5361 # <h> nodes indicate section breaks
5362 # They can only occur at the top level, so we can find them by iterating the root's children
5363 $node = $root->getFirstChild();
5365 # Find the target section
5366 if ( $sectionIndex == 0 ) {
5367 # Section zero doesn't nest, level=big
5368 $targetLevel = 1000;
5371 if ( $node->getName() === 'h' ) {
5372 $bits = $node->splitHeading();
5373 if ( $bits['i'] == $sectionIndex ) {
5374 $targetLevel = $bits['level'];
5378 if ( $mode === 'replace' ) {
5379 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5381 $node = $node->getNextSibling();
5387 if ( $mode === 'get' ) {
5394 # Find the end of the section, including nested sections
5396 if ( $node->getName() === 'h' ) {
5397 $bits = $node->splitHeading();
5398 $curLevel = $bits['level'];
5399 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5403 if ( $mode === 'get' ) {
5404 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5406 $node = $node->getNextSibling();
5409 # Write out the remainder (in replace mode only)
5410 if ( $mode === 'replace' ) {
5411 # Output the replacement text
5412 # Add two newlines on -- trailing whitespace in $newText is conventionally
5413 # stripped by the editor, so we need both newlines to restore the paragraph gap
5414 # Only add trailing whitespace if there is newText
5415 if ( $newText != "" ) {
5416 $outText .= $newText . "\n\n";
5420 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5421 $node = $node->getNextSibling();
5425 if ( is_string( $outText ) ) {
5426 # Re-insert stripped tags
5427 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5434 * This function returns the text of a section, specified by a number ($section).
5435 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5436 * the first section before any such heading (section 0).
5438 * If a section contains subsections, these are also returned.
5440 * @param $text String: text to look in
5441 * @param $section String: section identifier
5442 * @param $deftext String: default to return if section is not found
5443 * @return string text of the requested section
5445 public function getSection( $text, $section, $deftext='' ) {
5446 return $this->extractSections( $text, $section, "get", $deftext );
5450 * This function returns $oldtext after the content of the section
5451 * specified by $section has been replaced with $text. If the target
5452 * section does not exist, $oldtext is returned unchanged.
5454 * @param $oldtext String: former text of the article
5455 * @param $section int section identifier
5456 * @param $text String: replacing text
5457 * @return String: modified text
5459 public function replaceSection( $oldtext, $section, $text ) {
5460 return $this->extractSections( $oldtext, $section, "replace", $text );
5464 * Get the ID of the revision we are parsing
5466 * @return Mixed: integer or null
5468 function getRevisionId() {
5469 return $this->mRevisionId
;
5473 * Get the revision object for $this->mRevisionId
5475 * @return Revision|null either a Revision object or null
5477 protected function getRevisionObject() {
5478 if ( !is_null( $this->mRevisionObject
) ) {
5479 return $this->mRevisionObject
;
5481 if ( is_null( $this->mRevisionId
) ) {
5485 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5486 return $this->mRevisionObject
;
5490 * Get the timestamp associated with the current revision, adjusted for
5491 * the default server-local timestamp
5493 function getRevisionTimestamp() {
5494 if ( is_null( $this->mRevisionTimestamp
) ) {
5495 wfProfileIn( __METHOD__
);
5499 $revObject = $this->getRevisionObject();
5500 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5502 # The cryptic '' timezone parameter tells to use the site-default
5503 # timezone offset instead of the user settings.
5505 # Since this value will be saved into the parser cache, served
5506 # to other users, and potentially even used inside links and such,
5507 # it needs to be consistent for all visitors.
5508 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5510 wfProfileOut( __METHOD__
);
5512 return $this->mRevisionTimestamp
;
5516 * Get the name of the user that edited the last revision
5518 * @return String: user name
5520 function getRevisionUser() {
5521 if( is_null( $this->mRevisionUser
) ) {
5522 $revObject = $this->getRevisionObject();
5524 # if this template is subst: the revision id will be blank,
5525 # so just use the current user's name
5527 $this->mRevisionUser
= $revObject->getUserText();
5528 } elseif( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5529 $this->mRevisionUser
= $this->getUser()->getName();
5532 return $this->mRevisionUser
;
5536 * Mutator for $mDefaultSort
5538 * @param $sort string New value
5540 public function setDefaultSort( $sort ) {
5541 $this->mDefaultSort
= $sort;
5542 $this->mOutput
->setProperty( 'defaultsort', $sort );
5546 * Accessor for $mDefaultSort
5547 * Will use the empty string if none is set.
5549 * This value is treated as a prefix, so the
5550 * empty string is equivalent to sorting by
5555 public function getDefaultSort() {
5556 if ( $this->mDefaultSort
!== false ) {
5557 return $this->mDefaultSort
;
5564 * Accessor for $mDefaultSort
5565 * Unlike getDefaultSort(), will return false if none is set
5567 * @return string or false
5569 public function getCustomDefaultSort() {
5570 return $this->mDefaultSort
;
5574 * Try to guess the section anchor name based on a wikitext fragment
5575 * presumably extracted from a heading, for example "Header" from
5578 * @param $text string
5582 public function guessSectionNameFromWikiText( $text ) {
5583 # Strip out wikitext links(they break the anchor)
5584 $text = $this->stripSectionName( $text );
5585 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5586 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5590 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5591 * instead. For use in redirects, since IE6 interprets Redirect: headers
5592 * as something other than UTF-8 (apparently?), resulting in breakage.
5594 * @param $text String: The section name
5595 * @return string An anchor
5597 public function guessLegacySectionNameFromWikiText( $text ) {
5598 # Strip out wikitext links(they break the anchor)
5599 $text = $this->stripSectionName( $text );
5600 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5601 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5605 * Strips a text string of wikitext for use in a section anchor
5607 * Accepts a text string and then removes all wikitext from the
5608 * string and leaves only the resultant text (i.e. the result of
5609 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5610 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5611 * to create valid section anchors by mimicing the output of the
5612 * parser when headings are parsed.
5614 * @param $text String: text string to be stripped of wikitext
5615 * for use in a Section anchor
5616 * @return string Filtered text string
5618 public function stripSectionName( $text ) {
5619 # Strip internal link markup
5620 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5621 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5623 # Strip external link markup
5624 # @todo FIXME: Not tolerant to blank link text
5625 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5626 # on how many empty links there are on the page - need to figure that out.
5627 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5629 # Parse wikitext quotes (italics & bold)
5630 $text = $this->doQuotes( $text );
5633 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5638 * strip/replaceVariables/unstrip for preprocessor regression testing
5640 * @param $text string
5641 * @param $title Title
5642 * @param $options ParserOptions
5643 * @param $outputType int
5647 function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5648 $this->startParse( $title, $options, $outputType, true );
5650 $text = $this->replaceVariables( $text );
5651 $text = $this->mStripState
->unstripBoth( $text );
5652 $text = Sanitizer
::removeHTMLtags( $text );
5657 * @param $text string
5658 * @param $title Title
5659 * @param $options ParserOptions
5662 function testPst( $text, Title
$title, ParserOptions
$options ) {
5663 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5668 * @param $title Title
5669 * @param $options ParserOptions
5672 function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5673 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5677 * Call a callback function on all regions of the given text that are not
5678 * inside strip markers, and replace those regions with the return value
5679 * of the callback. For example, with input:
5683 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5684 * two strings will be replaced with the value returned by the callback in
5692 function markerSkipCallback( $s, $callback ) {
5695 while ( $i < strlen( $s ) ) {
5696 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5697 if ( $markerStart === false ) {
5698 $out .= call_user_func( $callback, substr( $s, $i ) );
5701 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5702 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5703 if ( $markerEnd === false ) {
5704 $out .= substr( $s, $markerStart );
5707 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5708 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5717 * Remove any strip markers found in the given text.
5719 * @param $text Input string
5722 function killMarkers( $text ) {
5723 return $this->mStripState
->killMarkers( $text );
5727 * Save the parser state required to convert the given half-parsed text to
5728 * HTML. "Half-parsed" in this context means the output of
5729 * recursiveTagParse() or internalParse(). This output has strip markers
5730 * from replaceVariables (extensionSubstitution() etc.), and link
5731 * placeholders from replaceLinkHolders().
5733 * Returns an array which can be serialized and stored persistently. This
5734 * array can later be loaded into another parser instance with
5735 * unserializeHalfParsedText(). The text can then be safely incorporated into
5736 * the return value of a parser hook.
5738 * @param $text string
5742 function serializeHalfParsedText( $text ) {
5743 wfProfileIn( __METHOD__
);
5746 'version' => self
::HALF_PARSED_VERSION
,
5747 'stripState' => $this->mStripState
->getSubState( $text ),
5748 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
5750 wfProfileOut( __METHOD__
);
5755 * Load the parser state given in the $data array, which is assumed to
5756 * have been generated by serializeHalfParsedText(). The text contents is
5757 * extracted from the array, and its markers are transformed into markers
5758 * appropriate for the current Parser instance. This transformed text is
5759 * returned, and can be safely included in the return value of a parser
5762 * If the $data array has been stored persistently, the caller should first
5763 * check whether it is still valid, by calling isValidHalfParsedText().
5765 * @param $data array Serialized data
5768 function unserializeHalfParsedText( $data ) {
5769 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
5770 throw new MWException( __METHOD__
.': invalid version' );
5773 # First, extract the strip state.
5774 $texts = array( $data['text'] );
5775 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
5777 # Now renumber links
5778 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
5780 # Should be good to go.
5785 * Returns true if the given array, presumed to be generated by
5786 * serializeHalfParsedText(), is compatible with the current version of the
5789 * @param $data Array
5793 function isValidHalfParsedText( $data ) {
5794 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
5798 * Parsed a width param of imagelink like 300px or 200x300px
5800 * @param $value String
5805 public function parseWidthParam( $value ) {
5806 $parsedWidthParam = array();
5807 if( $value === '' ) {
5808 return $parsedWidthParam;
5811 # (bug 13500) In both cases (width/height and width only),
5812 # permit trailing "px" for backward compatibility.
5813 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
5814 $width = intval( $m[1] );
5815 $height = intval( $m[2] );
5816 $parsedWidthParam['width'] = $width;
5817 $parsedWidthParam['height'] = $height;
5818 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
5819 $width = intval( $value );
5820 $parsedWidthParam['width'] = $width;
5822 return $parsedWidthParam;