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
204 * @var Array with the language name of each language link (i.e. the
205 * interwiki prefix) in the key, value arbitrary. Used to avoid sending
206 * duplicate language links to the ParserOutput.
208 var $mLangLinkLanguages;
215 public function __construct( $conf = array() ) {
216 $this->mConf
= $conf;
217 $this->mUrlProtocols
= wfUrlProtocols();
218 $this->mExtLinkBracketedRegex
= '/\[(((?i)' . $this->mUrlProtocols
. ')'.
219 self
::EXT_LINK_URL_CLASS
.'+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
220 if ( isset( $conf['preprocessorClass'] ) ) {
221 $this->mPreprocessorClass
= $conf['preprocessorClass'];
222 } elseif ( defined( 'MW_COMPILED' ) ) {
223 # Preprocessor_Hash is much faster than Preprocessor_DOM in compiled mode
224 $this->mPreprocessorClass
= 'Preprocessor_Hash';
225 } elseif ( extension_loaded( 'domxml' ) ) {
226 # PECL extension that conflicts with the core DOM extension (bug 13770)
227 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
228 $this->mPreprocessorClass
= 'Preprocessor_Hash';
229 } elseif ( extension_loaded( 'dom' ) ) {
230 $this->mPreprocessorClass
= 'Preprocessor_DOM';
232 $this->mPreprocessorClass
= 'Preprocessor_Hash';
234 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
238 * Reduce memory usage to reduce the impact of circular references
240 function __destruct() {
241 if ( isset( $this->mLinkHolders
) ) {
242 unset( $this->mLinkHolders
);
244 foreach ( $this as $name => $value ) {
245 unset( $this->$name );
250 * Do various kinds of initialisation on the first call of the parser
252 function firstCallInit() {
253 if ( !$this->mFirstCall
) {
256 $this->mFirstCall
= false;
258 wfProfileIn( __METHOD__
);
260 CoreParserFunctions
::register( $this );
261 CoreTagHooks
::register( $this );
262 $this->initialiseVariables();
264 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
265 wfProfileOut( __METHOD__
);
273 function clearState() {
274 wfProfileIn( __METHOD__
);
275 if ( $this->mFirstCall
) {
276 $this->firstCallInit();
278 $this->mOutput
= new ParserOutput
;
279 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
280 $this->mAutonumber
= 0;
281 $this->mLastSection
= '';
282 $this->mDTopen
= false;
283 $this->mIncludeCount
= array();
284 $this->mArgStack
= false;
285 $this->mInPre
= false;
286 $this->mLinkHolders
= new LinkHolderArray( $this );
288 $this->mRevisionObject
= $this->mRevisionTimestamp
=
289 $this->mRevisionId
= $this->mRevisionUser
= null;
290 $this->mVarCache
= array();
292 $this->mLangLinkLanguages
= array();
295 * Prefix for temporary replacement strings for the multipass parser.
296 * \x07 should never appear in input as it's disallowed in XML.
297 * Using it at the front also gives us a little extra robustness
298 * since it shouldn't match when butted up against identifier-like
301 * Must not consist of all title characters, or else it will change
302 * the behaviour of <nowiki> in a link.
304 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
305 $this->mStripState
= new StripState( $this->mUniqPrefix
);
308 # Clear these on every parse, bug 4549
309 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
311 $this->mShowToc
= true;
312 $this->mForceTocPosition
= false;
313 $this->mIncludeSizes
= array(
317 $this->mPPNodeCount
= 0;
318 $this->mGeneratedPPNodeCount
= 0;
319 $this->mHighestExpansionDepth
= 0;
320 $this->mDefaultSort
= false;
321 $this->mHeadings
= array();
322 $this->mDoubleUnderscores
= array();
323 $this->mExpensiveFunctionCount
= 0;
326 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
327 $this->mPreprocessor
= null;
330 wfRunHooks( 'ParserClearState', array( &$this ) );
331 wfProfileOut( __METHOD__
);
335 * Convert wikitext to HTML
336 * Do not call this function recursively.
338 * @param $text String: text we want to parse
339 * @param $title Title object
340 * @param $options ParserOptions
341 * @param $linestart boolean
342 * @param $clearState boolean
343 * @param $revid Int: number to pass in {{REVISIONID}}
344 * @return ParserOutput a ParserOutput
346 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
348 * First pass--just handle <nowiki> sections, pass the rest off
349 * to internalParse() which does all the real work.
352 global $wgUseTidy, $wgAlwaysUseTidy;
353 $fname = __METHOD__
.'-' . wfGetCaller();
354 wfProfileIn( __METHOD__
);
355 wfProfileIn( $fname );
357 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
359 # Remove the strip marker tag prefix from the input, if present.
361 $text = str_replace( $this->mUniqPrefix
, '', $text );
364 $oldRevisionId = $this->mRevisionId
;
365 $oldRevisionObject = $this->mRevisionObject
;
366 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
367 $oldRevisionUser = $this->mRevisionUser
;
368 if ( $revid !== null ) {
369 $this->mRevisionId
= $revid;
370 $this->mRevisionObject
= null;
371 $this->mRevisionTimestamp
= null;
372 $this->mRevisionUser
= null;
375 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
377 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
378 $text = $this->internalParse( $text );
379 wfRunHooks( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
381 $text = $this->mStripState
->unstripGeneral( $text );
383 # Clean up special characters, only run once, next-to-last before doBlockLevels
385 # french spaces, last one Guillemet-left
386 # only if there is something before the space
387 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
388 # french spaces, Guillemet-right
389 '/(\\302\\253) /' => '\\1 ',
390 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
392 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
394 $text = $this->doBlockLevels( $text, $linestart );
396 $this->replaceLinkHolders( $text );
399 * The input doesn't get language converted if
401 * b) Content isn't converted
402 * c) It's a conversion table
403 * d) it is an interface message (which is in the user language)
405 if ( !( $options->getDisableContentConversion()
406 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] ) ) )
408 # Run convert unconditionally in 1.18-compatible mode
409 global $wgBug34832TransitionalRollback;
410 if ( $wgBug34832TransitionalRollback ||
!$this->mOptions
->getInterfaceMessage() ) {
411 # The position of the convert() call should not be changed. it
412 # assumes that the links are all replaced and the only thing left
413 # is the <nowiki> mark.
414 $text = $this->getConverterLanguage()->convert( $text );
419 * A converted title will be provided in the output object if title and
420 * content conversion are enabled, the article text does not contain
421 * a conversion-suppressing double-underscore tag, and no
422 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
423 * automatic link conversion.
425 if ( !( $options->getDisableTitleConversion()
426 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
427 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
428 ||
$this->mOutput
->getDisplayTitle() !== false ) )
430 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
431 if ( $convruletitle ) {
432 $this->mOutput
->setTitleText( $convruletitle );
434 $titleText = $this->getConverterLanguage()->convertTitle( $title );
435 $this->mOutput
->setTitleText( $titleText );
439 $text = $this->mStripState
->unstripNoWiki( $text );
441 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
443 $text = $this->replaceTransparentTags( $text );
444 $text = $this->mStripState
->unstripGeneral( $text );
446 $text = Sanitizer
::normalizeCharReferences( $text );
448 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
449 $text = MWTidy
::tidy( $text );
451 # attempt to sanitize at least some nesting problems
452 # (bug #2702 and quite a few others)
454 # ''Something [http://www.cool.com cool''] -->
455 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
456 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
457 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
458 # fix up an anchor inside another anchor, only
459 # at least for a single single nested link (bug 3695)
460 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
461 '\\1\\2</a>\\3</a>\\1\\4</a>',
462 # fix div inside inline elements- doBlockLevels won't wrap a line which
463 # contains a div, so fix it up here; replace
464 # div with escaped text
465 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
466 '\\1\\3<div\\5>\\6</div>\\8\\9',
467 # remove empty italic or bold tag pairs, some
468 # introduced by rules above
469 '/<([bi])><\/\\1>/' => '',
472 $text = preg_replace(
473 array_keys( $tidyregs ),
474 array_values( $tidyregs ),
478 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
479 $this->limitationWarn( 'expensive-parserfunction',
480 $this->mExpensiveFunctionCount
,
481 $this->mOptions
->getExpensiveParserFunctionLimit()
485 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
487 # Information on include size limits, for the benefit of users who try to skirt them
488 if ( $this->mOptions
->getEnableLimitReport() ) {
489 $max = $this->mOptions
->getMaxIncludeSize();
490 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/{$this->mOptions->getExpensiveParserFunctionLimit()}\n";
492 "NewPP limit report\n" .
493 "Preprocessor visited node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
494 "Preprocessor generated node count: " .
495 "{$this->mGeneratedPPNodeCount}/{$this->mOptions->getMaxGeneratedPPNodeCount()}\n" .
496 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
497 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
498 "Highest expansion depth: {$this->mHighestExpansionDepth}/{$this->mOptions->getMaxPPExpandDepth()}\n".
500 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
501 $text .= "\n<!-- \n$limitReport-->\n";
503 if ( $this->mGeneratedPPNodeCount
> $this->mOptions
->getMaxGeneratedPPNodeCount() / 10 ) {
504 wfDebugLog( 'generated-pp-node-count', $this->mGeneratedPPNodeCount
. ' ' .
505 $this->mTitle
->getPrefixedDBkey() );
508 $this->mOutput
->setText( $text );
510 $this->mRevisionId
= $oldRevisionId;
511 $this->mRevisionObject
= $oldRevisionObject;
512 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
513 $this->mRevisionUser
= $oldRevisionUser;
514 wfProfileOut( $fname );
515 wfProfileOut( __METHOD__
);
517 return $this->mOutput
;
521 * Recursive parser entry point that can be called from an extension tag
524 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
526 * @param $text String: text extension wants to have parsed
527 * @param $frame PPFrame: The frame to use for expanding any template variables
531 function recursiveTagParse( $text, $frame=false ) {
532 wfProfileIn( __METHOD__
);
533 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
534 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
535 $text = $this->internalParse( $text, false, $frame );
536 wfProfileOut( __METHOD__
);
541 * Expand templates and variables in the text, producing valid, static wikitext.
542 * Also removes comments.
543 * @return mixed|string
545 function preprocess( $text, Title
$title, ParserOptions
$options, $revid = null ) {
546 wfProfileIn( __METHOD__
);
547 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
548 if ( $revid !== null ) {
549 $this->mRevisionId
= $revid;
551 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
552 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
553 $text = $this->replaceVariables( $text );
554 $text = $this->mStripState
->unstripBoth( $text );
555 wfProfileOut( __METHOD__
);
560 * Recursive parser entry point that can be called from an extension tag
563 * @param $text String: text to be expanded
564 * @param $frame PPFrame: The frame to use for expanding any template variables
568 public function recursivePreprocess( $text, $frame = false ) {
569 wfProfileIn( __METHOD__
);
570 $text = $this->replaceVariables( $text, $frame );
571 $text = $this->mStripState
->unstripBoth( $text );
572 wfProfileOut( __METHOD__
);
577 * Process the wikitext for the "?preload=" feature. (bug 5210)
579 * "<noinclude>", "<includeonly>" etc. are parsed as for template
580 * transclusion, comments, templates, arguments, tags hooks and parser
581 * functions are untouched.
583 * @param $text String
584 * @param $title Title
585 * @param $options ParserOptions
588 public function getPreloadText( $text, Title
$title, ParserOptions
$options ) {
589 # Parser (re)initialisation
590 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
592 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
593 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
594 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
595 $text = $this->mStripState
->unstripBoth( $text );
600 * Get a random string
604 static public function getRandomString() {
605 return wfRandomString( 16 );
609 * Set the current user.
610 * Should only be used when doing pre-save transform.
612 * @param $user Mixed: User object or null (to reset)
614 function setUser( $user ) {
615 $this->mUser
= $user;
619 * Accessor for mUniqPrefix.
623 public function uniqPrefix() {
624 if ( !isset( $this->mUniqPrefix
) ) {
625 # @todo FIXME: This is probably *horribly wrong*
626 # LanguageConverter seems to want $wgParser's uniqPrefix, however
627 # if this is called for a parser cache hit, the parser may not
628 # have ever been initialized in the first place.
629 # Not really sure what the heck is supposed to be going on here.
631 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
633 return $this->mUniqPrefix
;
637 * Set the context title
641 function setTitle( $t ) {
642 if ( !$t ||
$t instanceof FakeTitle
) {
643 $t = Title
::newFromText( 'NO TITLE' );
646 if ( strval( $t->getFragment() ) !== '' ) {
647 # Strip the fragment to avoid various odd effects
648 $this->mTitle
= clone $t;
649 $this->mTitle
->setFragment( '' );
656 * Accessor for the Title object
658 * @return Title object
660 function getTitle() {
661 return $this->mTitle
;
665 * Accessor/mutator for the Title object
667 * @param $x Title object or null to just get the current one
668 * @return Title object
670 function Title( $x = null ) {
671 return wfSetVar( $this->mTitle
, $x );
675 * Set the output type
677 * @param $ot Integer: new value
679 function setOutputType( $ot ) {
680 $this->mOutputType
= $ot;
683 'html' => $ot == self
::OT_HTML
,
684 'wiki' => $ot == self
::OT_WIKI
,
685 'pre' => $ot == self
::OT_PREPROCESS
,
686 'plain' => $ot == self
::OT_PLAIN
,
691 * Accessor/mutator for the output type
693 * @param $x int|null New value or null to just get the current one
696 function OutputType( $x = null ) {
697 return wfSetVar( $this->mOutputType
, $x );
701 * Get the ParserOutput object
703 * @return ParserOutput object
705 function getOutput() {
706 return $this->mOutput
;
710 * Get the ParserOptions object
712 * @return ParserOptions object
714 function getOptions() {
715 return $this->mOptions
;
719 * Accessor/mutator for the ParserOptions object
721 * @param $x ParserOptions New value or null to just get the current one
722 * @return ParserOptions Current ParserOptions object
724 function Options( $x = null ) {
725 return wfSetVar( $this->mOptions
, $x );
731 function nextLinkID() {
732 return $this->mLinkID++
;
738 function setLinkID( $id ) {
739 $this->mLinkID
= $id;
743 * Get a language object for use in parser functions such as {{FORMATNUM:}}
746 function getFunctionLang() {
747 return $this->getTargetLanguage();
751 * Get the target language for the content being parsed. This is usually the
752 * language that the content is in.
756 * @return Language|null
758 public function getTargetLanguage() {
759 $target = $this->mOptions
->getTargetLanguage();
761 if ( $target !== null ) {
763 } elseif( $this->mOptions
->getInterfaceMessage() ) {
764 return $this->mOptions
->getUserLangObj();
765 } elseif( is_null( $this->mTitle
) ) {
766 throw new MWException( __METHOD__
. ': $this->mTitle is null' );
769 return $this->mTitle
->getPageLanguage();
773 * Get the language object for language conversion
775 function getConverterLanguage() {
776 global $wgBug34832TransitionalRollback, $wgContLang;
777 if ( $wgBug34832TransitionalRollback ) {
780 return $this->getTargetLanguage();
785 * Get a User object either from $this->mUser, if set, or from the
786 * ParserOptions object otherwise
788 * @return User object
791 if ( !is_null( $this->mUser
) ) {
794 return $this->mOptions
->getUser();
798 * Get a preprocessor object
800 * @return Preprocessor instance
802 function getPreprocessor() {
803 if ( !isset( $this->mPreprocessor
) ) {
804 $class = $this->mPreprocessorClass
;
805 $this->mPreprocessor
= new $class( $this );
807 return $this->mPreprocessor
;
811 * Replaces all occurrences of HTML-style comments and the given tags
812 * in the text with a random marker and returns the next text. The output
813 * parameter $matches will be an associative array filled with data in
817 * 'UNIQ-xxxxx' => array(
820 * array( 'param' => 'x' ),
821 * '<element param="x">tag content</element>' ) )
824 * @param $elements array list of element names. Comments are always extracted.
825 * @param $text string Source text string.
826 * @param $matches array Out parameter, Array: extracted tags
827 * @param $uniq_prefix string
828 * @return String: stripped text
830 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
835 $taglist = implode( '|', $elements );
836 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
838 while ( $text != '' ) {
839 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
841 if ( count( $p ) < 5 ) {
844 if ( count( $p ) > 5 ) {
858 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
859 $stripped .= $marker;
861 if ( $close === '/>' ) {
862 # Empty element tag, <tag />
867 if ( $element === '!--' ) {
870 $end = "/(<\\/$element\\s*>)/i";
872 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
874 if ( count( $q ) < 3 ) {
875 # No end tag -- let it run out to the end of the text.
884 $matches[$marker] = array( $element,
886 Sanitizer
::decodeTagAttributes( $attributes ),
887 "<$element$attributes$close$content$tail" );
893 * Get a list of strippable XML-like elements
897 function getStripList() {
898 return $this->mStripList
;
902 * Add an item to the strip state
903 * Returns the unique tag which must be inserted into the stripped text
904 * The tag will be replaced with the original text in unstrip()
906 * @param $text string
910 function insertStripItem( $text ) {
911 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
912 $this->mMarkerIndex++
;
913 $this->mStripState
->addGeneral( $rnd, $text );
918 * parse the wiki syntax used to render tables
923 function doTableStuff( $text ) {
924 wfProfileIn( __METHOD__
);
926 $lines = StringUtils
::explode( "\n", $text );
928 $td_history = array(); # Is currently a td tag open?
929 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
930 $tr_history = array(); # Is currently a tr tag open?
931 $tr_attributes = array(); # history of tr attributes
932 $has_opened_tr = array(); # Did this table open a <tr> element?
933 $indent_level = 0; # indent level of the table
935 foreach ( $lines as $outLine ) {
936 $line = trim( $outLine );
938 if ( $line === '' ) { # empty line, go to next line
939 $out .= $outLine."\n";
943 $first_character = $line[0];
946 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
947 # First check if we are starting a new table
948 $indent_level = strlen( $matches[1] );
950 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
951 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
953 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
954 array_push( $td_history , false );
955 array_push( $last_tag_history , '' );
956 array_push( $tr_history , false );
957 array_push( $tr_attributes , '' );
958 array_push( $has_opened_tr , false );
959 } elseif ( count( $td_history ) == 0 ) {
960 # Don't do any of the following
961 $out .= $outLine."\n";
963 } elseif ( substr( $line , 0 , 2 ) === '|}' ) {
964 # We are ending a table
965 $line = '</table>' . substr( $line , 2 );
966 $last_tag = array_pop( $last_tag_history );
968 if ( !array_pop( $has_opened_tr ) ) {
969 $line = "<tr><td></td></tr>{$line}";
972 if ( array_pop( $tr_history ) ) {
973 $line = "</tr>{$line}";
976 if ( array_pop( $td_history ) ) {
977 $line = "</{$last_tag}>{$line}";
979 array_pop( $tr_attributes );
980 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
981 } elseif ( substr( $line , 0 , 2 ) === '|-' ) {
982 # Now we have a table row
983 $line = preg_replace( '#^\|-+#', '', $line );
985 # Whats after the tag is now only attributes
986 $attributes = $this->mStripState
->unstripBoth( $line );
987 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
988 array_pop( $tr_attributes );
989 array_push( $tr_attributes, $attributes );
992 $last_tag = array_pop( $last_tag_history );
993 array_pop( $has_opened_tr );
994 array_push( $has_opened_tr , true );
996 if ( array_pop( $tr_history ) ) {
1000 if ( array_pop( $td_history ) ) {
1001 $line = "</{$last_tag}>{$line}";
1005 array_push( $tr_history , false );
1006 array_push( $td_history , false );
1007 array_push( $last_tag_history , '' );
1008 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line , 0 , 2 ) === '|+' ) {
1009 # This might be cell elements, td, th or captions
1010 if ( substr( $line , 0 , 2 ) === '|+' ) {
1011 $first_character = '+';
1012 $line = substr( $line , 1 );
1015 $line = substr( $line , 1 );
1017 if ( $first_character === '!' ) {
1018 $line = str_replace( '!!' , '||' , $line );
1021 # Split up multiple cells on the same line.
1022 # FIXME : This can result in improper nesting of tags processed
1023 # by earlier parser steps, but should avoid splitting up eg
1024 # attribute values containing literal "||".
1025 $cells = StringUtils
::explodeMarkup( '||' , $line );
1029 # Loop through each table cell
1030 foreach ( $cells as $cell ) {
1032 if ( $first_character !== '+' ) {
1033 $tr_after = array_pop( $tr_attributes );
1034 if ( !array_pop( $tr_history ) ) {
1035 $previous = "<tr{$tr_after}>\n";
1037 array_push( $tr_history , true );
1038 array_push( $tr_attributes , '' );
1039 array_pop( $has_opened_tr );
1040 array_push( $has_opened_tr , true );
1043 $last_tag = array_pop( $last_tag_history );
1045 if ( array_pop( $td_history ) ) {
1046 $previous = "</{$last_tag}>\n{$previous}";
1049 if ( $first_character === '|' ) {
1051 } elseif ( $first_character === '!' ) {
1053 } elseif ( $first_character === '+' ) {
1054 $last_tag = 'caption';
1059 array_push( $last_tag_history , $last_tag );
1061 # A cell could contain both parameters and data
1062 $cell_data = explode( '|' , $cell , 2 );
1064 # Bug 553: Note that a '|' inside an invalid link should not
1065 # be mistaken as delimiting cell parameters
1066 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1067 $cell = "{$previous}<{$last_tag}>{$cell}";
1068 } elseif ( count( $cell_data ) == 1 ) {
1069 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1071 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1072 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
1073 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1077 array_push( $td_history , true );
1080 $out .= $outLine . "\n";
1083 # Closing open td, tr && table
1084 while ( count( $td_history ) > 0 ) {
1085 if ( array_pop( $td_history ) ) {
1088 if ( array_pop( $tr_history ) ) {
1091 if ( !array_pop( $has_opened_tr ) ) {
1092 $out .= "<tr><td></td></tr>\n" ;
1095 $out .= "</table>\n";
1098 # Remove trailing line-ending (b/c)
1099 if ( substr( $out, -1 ) === "\n" ) {
1100 $out = substr( $out, 0, -1 );
1103 # special case: don't return empty table
1104 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1108 wfProfileOut( __METHOD__
);
1114 * Helper function for parse() that transforms wiki markup into
1115 * HTML. Only called for $mOutputType == self::OT_HTML.
1119 * @param $text string
1120 * @param $isMain bool
1121 * @param $frame bool
1125 function internalParse( $text, $isMain = true, $frame = false ) {
1126 wfProfileIn( __METHOD__
);
1130 # Hook to suspend the parser in this state
1131 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1132 wfProfileOut( __METHOD__
);
1136 # if $frame is provided, then use $frame for replacing any variables
1138 # use frame depth to infer how include/noinclude tags should be handled
1139 # depth=0 means this is the top-level document; otherwise it's an included document
1140 if ( !$frame->depth
) {
1143 $flag = Parser
::PTD_FOR_INCLUSION
;
1145 $dom = $this->preprocessToDom( $text, $flag );
1146 $text = $frame->expand( $dom );
1148 # if $frame is not provided, then use old-style replaceVariables
1149 $text = $this->replaceVariables( $text );
1152 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1153 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1154 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1156 # Tables need to come after variable replacement for things to work
1157 # properly; putting them before other transformations should keep
1158 # exciting things like link expansions from showing up in surprising
1160 $text = $this->doTableStuff( $text );
1162 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1164 $text = $this->doDoubleUnderscore( $text );
1166 $text = $this->doHeadings( $text );
1167 if ( $this->mOptions
->getUseDynamicDates() ) {
1168 $df = DateFormatter
::getInstance();
1169 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1171 $text = $this->replaceInternalLinks( $text );
1172 $text = $this->doAllQuotes( $text );
1173 $text = $this->replaceExternalLinks( $text );
1175 # replaceInternalLinks may sometimes leave behind
1176 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1177 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
1179 $text = $this->doMagicLinks( $text );
1180 $text = $this->formatHeadings( $text, $origText, $isMain );
1182 wfProfileOut( __METHOD__
);
1187 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1188 * magic external links.
1193 * @param $text string
1197 function doMagicLinks( $text ) {
1198 wfProfileIn( __METHOD__
);
1199 $prots = wfUrlProtocolsWithoutProtRel();
1200 $urlChar = self
::EXT_LINK_URL_CLASS
;
1201 $text = preg_replace_callback(
1203 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1204 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1205 (\\b(?i:$prots)$urlChar+) | # m[3]: Free external links" . '
1206 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1207 ISBN\s+(\b # m[5]: ISBN, capture number
1208 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1209 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1210 [0-9Xx] # check digit
1212 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1213 wfProfileOut( __METHOD__
);
1218 * @throws MWException
1220 * @return HTML|string
1222 function magicLinkCallback( $m ) {
1223 if ( isset( $m[1] ) && $m[1] !== '' ) {
1226 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1229 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1230 # Free external link
1231 return $this->makeFreeExternalLink( $m[0] );
1232 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1234 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1237 $CssClass = 'mw-magiclink-rfc';
1239 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1241 $urlmsg = 'pubmedurl';
1242 $CssClass = 'mw-magiclink-pmid';
1245 throw new MWException( __METHOD__
.': unrecognised match type "' .
1246 substr( $m[0], 0, 20 ) . '"' );
1248 $url = wfMessage( $urlmsg, $id )->inContentLanguage()->text();
1249 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1250 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1253 $num = strtr( $isbn, array(
1258 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1260 htmlspecialchars( $titleObj->getLocalUrl() ) .
1261 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1268 * Make a free external link, given a user-supplied URL
1270 * @param $url string
1272 * @return string HTML
1275 function makeFreeExternalLink( $url ) {
1276 wfProfileIn( __METHOD__
);
1280 # The characters '<' and '>' (which were escaped by
1281 # removeHTMLtags()) should not be included in
1282 # URLs, per RFC 2396.
1284 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1285 $trail = substr( $url, $m2[0][1] ) . $trail;
1286 $url = substr( $url, 0, $m2[0][1] );
1289 # Move trailing punctuation to $trail
1291 # If there is no left bracket, then consider right brackets fair game too
1292 if ( strpos( $url, '(' ) === false ) {
1296 $numSepChars = strspn( strrev( $url ), $sep );
1297 if ( $numSepChars ) {
1298 $trail = substr( $url, -$numSepChars ) . $trail;
1299 $url = substr( $url, 0, -$numSepChars );
1302 $url = Sanitizer
::cleanUrl( $url );
1304 # Is this an external image?
1305 $text = $this->maybeMakeExternalImage( $url );
1306 if ( $text === false ) {
1307 # Not an image, make a link
1308 $text = Linker
::makeExternalLink( $url,
1309 $this->getConverterLanguage()->markNoConversion($url), true, 'free',
1310 $this->getExternalLinkAttribs( $url ) );
1311 # Register it in the output object...
1312 # Replace unnecessary URL escape codes with their equivalent characters
1313 $pasteurized = self
::replaceUnusualEscapes( $url );
1314 $this->mOutput
->addExternalLink( $pasteurized );
1316 wfProfileOut( __METHOD__
);
1317 return $text . $trail;
1322 * Parse headers and return html
1326 * @param $text string
1330 function doHeadings( $text ) {
1331 wfProfileIn( __METHOD__
);
1332 for ( $i = 6; $i >= 1; --$i ) {
1333 $h = str_repeat( '=', $i );
1334 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1335 "<h$i>\\1</h$i>", $text );
1337 wfProfileOut( __METHOD__
);
1342 * Replace single quotes with HTML markup
1345 * @param $text string
1347 * @return string the altered text
1349 function doAllQuotes( $text ) {
1350 wfProfileIn( __METHOD__
);
1352 $lines = StringUtils
::explode( "\n", $text );
1353 foreach ( $lines as $line ) {
1354 $outtext .= $this->doQuotes( $line ) . "\n";
1356 $outtext = substr( $outtext, 0,-1 );
1357 wfProfileOut( __METHOD__
);
1362 * Helper function for doAllQuotes()
1364 * @param $text string
1368 public function doQuotes( $text ) {
1369 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1370 if ( count( $arr ) == 1 ) {
1373 # First, do some preliminary work. This may shift some apostrophes from
1374 # being mark-up to being text. It also counts the number of occurrences
1375 # of bold and italics mark-ups.
1378 for ( $i = 0; $i < count( $arr ); $i++
) {
1379 if ( ( $i %
2 ) == 1 ) {
1380 # If there are ever four apostrophes, assume the first is supposed to
1381 # be text, and the remaining three constitute mark-up for bold text.
1382 if ( strlen( $arr[$i] ) == 4 ) {
1385 } elseif ( strlen( $arr[$i] ) > 5 ) {
1386 # If there are more than 5 apostrophes in a row, assume they're all
1387 # text except for the last 5.
1388 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1391 # Count the number of occurrences of bold and italics mark-ups.
1392 # We are not counting sequences of five apostrophes.
1393 if ( strlen( $arr[$i] ) == 2 ) {
1395 } elseif ( strlen( $arr[$i] ) == 3 ) {
1397 } elseif ( strlen( $arr[$i] ) == 5 ) {
1404 # If there is an odd number of both bold and italics, it is likely
1405 # that one of the bold ones was meant to be an apostrophe followed
1406 # by italics. Which one we cannot know for certain, but it is more
1407 # likely to be one that has a single-letter word before it.
1408 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1410 $firstsingleletterword = -1;
1411 $firstmultiletterword = -1;
1413 foreach ( $arr as $r ) {
1414 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1415 $x1 = substr( $arr[$i-1], -1 );
1416 $x2 = substr( $arr[$i-1], -2, 1 );
1417 if ( $x1 === ' ' ) {
1418 if ( $firstspace == -1 ) {
1421 } elseif ( $x2 === ' ') {
1422 if ( $firstsingleletterword == -1 ) {
1423 $firstsingleletterword = $i;
1426 if ( $firstmultiletterword == -1 ) {
1427 $firstmultiletterword = $i;
1434 # If there is a single-letter word, use it!
1435 if ( $firstsingleletterword > -1 ) {
1436 $arr[$firstsingleletterword] = "''";
1437 $arr[$firstsingleletterword-1] .= "'";
1438 } elseif ( $firstmultiletterword > -1 ) {
1439 # If not, but there's a multi-letter word, use that one.
1440 $arr[$firstmultiletterword] = "''";
1441 $arr[$firstmultiletterword-1] .= "'";
1442 } elseif ( $firstspace > -1 ) {
1443 # ... otherwise use the first one that has neither.
1444 # (notice that it is possible for all three to be -1 if, for example,
1445 # there is only one pentuple-apostrophe in the line)
1446 $arr[$firstspace] = "''";
1447 $arr[$firstspace-1] .= "'";
1451 # Now let's actually convert our apostrophic mush to HTML!
1456 foreach ( $arr as $r ) {
1457 if ( ( $i %
2 ) == 0 ) {
1458 if ( $state === 'both' ) {
1464 if ( strlen( $r ) == 2 ) {
1465 if ( $state === 'i' ) {
1466 $output .= '</i>'; $state = '';
1467 } elseif ( $state === 'bi' ) {
1468 $output .= '</i>'; $state = 'b';
1469 } elseif ( $state === 'ib' ) {
1470 $output .= '</b></i><b>'; $state = 'b';
1471 } elseif ( $state === 'both' ) {
1472 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1473 } else { # $state can be 'b' or ''
1474 $output .= '<i>'; $state .= 'i';
1476 } elseif ( strlen( $r ) == 3 ) {
1477 if ( $state === 'b' ) {
1478 $output .= '</b>'; $state = '';
1479 } elseif ( $state === 'bi' ) {
1480 $output .= '</i></b><i>'; $state = 'i';
1481 } elseif ( $state === 'ib' ) {
1482 $output .= '</b>'; $state = 'i';
1483 } elseif ( $state === 'both' ) {
1484 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1485 } else { # $state can be 'i' or ''
1486 $output .= '<b>'; $state .= 'b';
1488 } elseif ( strlen( $r ) == 5 ) {
1489 if ( $state === 'b' ) {
1490 $output .= '</b><i>'; $state = 'i';
1491 } elseif ( $state === 'i' ) {
1492 $output .= '</i><b>'; $state = 'b';
1493 } elseif ( $state === 'bi' ) {
1494 $output .= '</i></b>'; $state = '';
1495 } elseif ( $state === 'ib' ) {
1496 $output .= '</b></i>'; $state = '';
1497 } elseif ( $state === 'both' ) {
1498 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1499 } else { # ($state == '')
1500 $buffer = ''; $state = 'both';
1506 # Now close all remaining tags. Notice that the order is important.
1507 if ( $state === 'b' ||
$state === 'ib' ) {
1510 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1513 if ( $state === 'bi' ) {
1516 # There might be lonely ''''', so make sure we have a buffer
1517 if ( $state === 'both' && $buffer ) {
1518 $output .= '<b><i>'.$buffer.'</i></b>';
1525 * Replace external links (REL)
1527 * Note: this is all very hackish and the order of execution matters a lot.
1528 * Make sure to run maintenance/parserTests.php if you change this code.
1532 * @param $text string
1536 function replaceExternalLinks( $text ) {
1537 wfProfileIn( __METHOD__
);
1539 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1540 if ( $bits === false ) {
1541 throw new MWException( "PCRE needs to be compiled with --enable-unicode-properties in order for MediaWiki to function" );
1543 $s = array_shift( $bits );
1546 while ( $i<count( $bits ) ) {
1548 $protocol = $bits[$i++
];
1549 $text = $bits[$i++
];
1550 $trail = $bits[$i++
];
1552 # The characters '<' and '>' (which were escaped by
1553 # removeHTMLtags()) should not be included in
1554 # URLs, per RFC 2396.
1556 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1557 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1558 $url = substr( $url, 0, $m2[0][1] );
1561 # If the link text is an image URL, replace it with an <img> tag
1562 # This happened by accident in the original parser, but some people used it extensively
1563 $img = $this->maybeMakeExternalImage( $text );
1564 if ( $img !== false ) {
1570 # Set linktype for CSS - if URL==text, link is essentially free
1571 $linktype = ( $text === $url ) ?
'free' : 'text';
1573 # No link text, e.g. [http://domain.tld/some.link]
1574 if ( $text == '' ) {
1576 $langObj = $this->getTargetLanguage();
1577 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1578 $linktype = 'autonumber';
1580 # Have link text, e.g. [http://domain.tld/some.link text]s
1582 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1585 $text = $this->getConverterLanguage()->markNoConversion( $text );
1587 $url = Sanitizer
::cleanUrl( $url );
1589 # Use the encoded URL
1590 # This means that users can paste URLs directly into the text
1591 # Funny characters like ö aren't valid in URLs anyway
1592 # This was changed in August 2004
1593 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1594 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1596 # Register link in the output object.
1597 # Replace unnecessary URL escape codes with the referenced character
1598 # This prevents spammers from hiding links from the filters
1599 $pasteurized = self
::replaceUnusualEscapes( $url );
1600 $this->mOutput
->addExternalLink( $pasteurized );
1603 wfProfileOut( __METHOD__
);
1608 * Get an associative array of additional HTML attributes appropriate for a
1609 * particular external link. This currently may include rel => nofollow
1610 * (depending on configuration, namespace, and the URL's domain) and/or a
1611 * target attribute (depending on configuration).
1613 * @param $url String|bool optional URL, to extract the domain from for rel =>
1614 * nofollow if appropriate
1615 * @return Array associative array of HTML attributes
1617 function getExternalLinkAttribs( $url = false ) {
1619 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1620 $ns = $this->mTitle
->getNamespace();
1621 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) &&
1622 !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions ) )
1624 $attribs['rel'] = 'nofollow';
1626 if ( $this->mOptions
->getExternalLinkTarget() ) {
1627 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1633 * Replace unusual URL escape codes with their equivalent characters
1635 * @param $url String
1638 * @todo This can merge genuinely required bits in the path or query string,
1639 * breaking legit URLs. A proper fix would treat the various parts of
1640 * the URL differently; as a workaround, just use the output for
1641 * statistical records, not for actual linking/output.
1643 static function replaceUnusualEscapes( $url ) {
1644 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1645 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1649 * Callback function used in replaceUnusualEscapes().
1650 * Replaces unusual URL escape codes with their equivalent character
1652 * @param $matches array
1656 private static function replaceUnusualEscapesCallback( $matches ) {
1657 $char = urldecode( $matches[0] );
1658 $ord = ord( $char );
1659 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1660 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1661 # No, shouldn't be escaped
1664 # Yes, leave it escaped
1670 * make an image if it's allowed, either through the global
1671 * option, through the exception, or through the on-wiki whitelist
1674 * $param $url string
1678 function maybeMakeExternalImage( $url ) {
1679 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1680 $imagesexception = !empty( $imagesfrom );
1682 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1683 if ( $imagesexception && is_array( $imagesfrom ) ) {
1684 $imagematch = false;
1685 foreach ( $imagesfrom as $match ) {
1686 if ( strpos( $url, $match ) === 0 ) {
1691 } elseif ( $imagesexception ) {
1692 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1694 $imagematch = false;
1696 if ( $this->mOptions
->getAllowExternalImages()
1697 ||
( $imagesexception && $imagematch ) ) {
1698 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1700 $text = Linker
::makeExternalImage( $url );
1703 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1704 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1705 $whitelist = explode( "\n", wfMessage( 'external_image_whitelist' )->inContentLanguage()->text() );
1706 foreach ( $whitelist as $entry ) {
1707 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1708 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1711 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1712 # Image matches a whitelist entry
1713 $text = Linker
::makeExternalImage( $url );
1722 * Process [[ ]] wikilinks
1726 * @return String: processed text
1730 function replaceInternalLinks( $s ) {
1731 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1736 * Process [[ ]] wikilinks (RIL)
1737 * @return LinkHolderArray
1741 function replaceInternalLinks2( &$s ) {
1742 wfProfileIn( __METHOD__
);
1744 wfProfileIn( __METHOD__
.'-setup' );
1745 static $tc = FALSE, $e1, $e1_img;
1746 # the % is needed to support urlencoded titles as well
1748 $tc = Title
::legalChars() . '#%';
1749 # Match a link having the form [[namespace:link|alternate]]trail
1750 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1751 # Match cases where there is no "]]", which might still be images
1752 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1755 $holders = new LinkHolderArray( $this );
1757 # split the entire text string on occurrences of [[
1758 $a = StringUtils
::explode( '[[', ' ' . $s );
1759 # get the first element (all text up to first [[), and remove the space we added
1762 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1763 $s = substr( $s, 1 );
1765 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1767 if ( $useLinkPrefixExtension ) {
1768 # Match the end of a line for a word that's not followed by whitespace,
1769 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1770 $e2 = wfMessage( 'linkprefix' )->inContentLanguage()->text();
1773 if ( is_null( $this->mTitle
) ) {
1774 wfProfileOut( __METHOD__
.'-setup' );
1775 wfProfileOut( __METHOD__
);
1776 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1778 $nottalk = !$this->mTitle
->isTalkPage();
1780 if ( $useLinkPrefixExtension ) {
1782 if ( preg_match( $e2, $s, $m ) ) {
1783 $first_prefix = $m[2];
1785 $first_prefix = false;
1791 if ( $this->getConverterLanguage()->hasVariants() ) {
1792 $selflink = $this->getConverterLanguage()->autoConvertToAllVariants(
1793 $this->mTitle
->getPrefixedText() );
1795 $selflink = array( $this->mTitle
->getPrefixedText() );
1797 $useSubpages = $this->areSubpagesAllowed();
1798 wfProfileOut( __METHOD__
.'-setup' );
1800 # Loop for each link
1801 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1802 # Check for excessive memory usage
1803 if ( $holders->isBig() ) {
1805 # Do the existence check, replace the link holders and clear the array
1806 $holders->replace( $s );
1810 if ( $useLinkPrefixExtension ) {
1811 wfProfileIn( __METHOD__
.'-prefixhandling' );
1812 if ( preg_match( $e2, $s, $m ) ) {
1819 if ( $first_prefix ) {
1820 $prefix = $first_prefix;
1821 $first_prefix = false;
1823 wfProfileOut( __METHOD__
.'-prefixhandling' );
1826 $might_be_img = false;
1828 wfProfileIn( __METHOD__
."-e1" );
1829 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1831 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1832 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1833 # the real problem is with the $e1 regex
1836 # Still some problems for cases where the ] is meant to be outside punctuation,
1837 # and no image is in sight. See bug 2095.
1839 if ( $text !== '' &&
1840 substr( $m[3], 0, 1 ) === ']' &&
1841 strpos( $text, '[' ) !== false
1844 $text .= ']'; # so that replaceExternalLinks($text) works later
1845 $m[3] = substr( $m[3], 1 );
1847 # fix up urlencoded title texts
1848 if ( strpos( $m[1], '%' ) !== false ) {
1849 # Should anchors '#' also be rejected?
1850 $m[1] = str_replace( array('<', '>'), array('<', '>'), rawurldecode( $m[1] ) );
1853 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1854 $might_be_img = true;
1856 if ( strpos( $m[1], '%' ) !== false ) {
1857 $m[1] = rawurldecode( $m[1] );
1860 } else { # Invalid form; output directly
1861 $s .= $prefix . '[[' . $line ;
1862 wfProfileOut( __METHOD__
."-e1" );
1865 wfProfileOut( __METHOD__
."-e1" );
1866 wfProfileIn( __METHOD__
."-misc" );
1868 # Don't allow internal links to pages containing
1869 # PROTO: where PROTO is a valid URL protocol; these
1870 # should be external links.
1871 if ( preg_match( '/^(?i:' . $this->mUrlProtocols
. ')/', $m[1] ) ) {
1872 $s .= $prefix . '[[' . $line ;
1873 wfProfileOut( __METHOD__
."-misc" );
1877 # Make subpage if necessary
1878 if ( $useSubpages ) {
1879 $link = $this->maybeDoSubpageLink( $m[1], $text );
1884 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1886 # Strip off leading ':'
1887 $link = substr( $link, 1 );
1890 wfProfileOut( __METHOD__
."-misc" );
1891 wfProfileIn( __METHOD__
."-title" );
1892 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1893 if ( $nt === null ) {
1894 $s .= $prefix . '[[' . $line;
1895 wfProfileOut( __METHOD__
."-title" );
1899 $ns = $nt->getNamespace();
1900 $iw = $nt->getInterWiki();
1901 wfProfileOut( __METHOD__
."-title" );
1903 if ( $might_be_img ) { # if this is actually an invalid link
1904 wfProfileIn( __METHOD__
."-might_be_img" );
1905 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1908 # look at the next 'line' to see if we can close it there
1910 $next_line = $a->current();
1911 if ( $next_line === false ||
$next_line === null ) {
1914 $m = explode( ']]', $next_line, 3 );
1915 if ( count( $m ) == 3 ) {
1916 # the first ]] closes the inner link, the second the image
1918 $text .= "[[{$m[0]}]]{$m[1]}";
1921 } elseif ( count( $m ) == 2 ) {
1922 # if there's exactly one ]] that's fine, we'll keep looking
1923 $text .= "[[{$m[0]}]]{$m[1]}";
1925 # if $next_line is invalid too, we need look no further
1926 $text .= '[[' . $next_line;
1931 # we couldn't find the end of this imageLink, so output it raw
1932 # but don't ignore what might be perfectly normal links in the text we've examined
1933 $holders->merge( $this->replaceInternalLinks2( $text ) );
1934 $s .= "{$prefix}[[$link|$text";
1935 # note: no $trail, because without an end, there *is* no trail
1936 wfProfileOut( __METHOD__
."-might_be_img" );
1939 } else { # it's not an image, so output it raw
1940 $s .= "{$prefix}[[$link|$text";
1941 # note: no $trail, because without an end, there *is* no trail
1942 wfProfileOut( __METHOD__
."-might_be_img" );
1945 wfProfileOut( __METHOD__
."-might_be_img" );
1948 $wasblank = ( $text == '' );
1952 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1953 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1954 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1955 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1956 $text = $this->doQuotes( $text );
1959 # Link not escaped by : , create the various objects
1962 wfProfileIn( __METHOD__
."-interwiki" );
1963 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && Language
::fetchLanguageName( $iw, null, 'mw' ) ) {
1964 # Bug 24502: filter duplicates
1965 if ( !isset( $this->mLangLinkLanguages
[$iw] ) ) {
1966 $this->mLangLinkLanguages
[$iw] = true;
1967 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1969 $s = rtrim( $s . $prefix );
1970 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1971 wfProfileOut( __METHOD__
."-interwiki" );
1974 wfProfileOut( __METHOD__
."-interwiki" );
1976 if ( $ns == NS_FILE
) {
1977 wfProfileIn( __METHOD__
."-image" );
1978 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1980 # if no parameters were passed, $text
1981 # becomes something like "File:Foo.png",
1982 # which we don't want to pass on to the
1986 # recursively parse links inside the image caption
1987 # actually, this will parse them in any other parameters, too,
1988 # but it might be hard to fix that, and it doesn't matter ATM
1989 $text = $this->replaceExternalLinks( $text );
1990 $holders->merge( $this->replaceInternalLinks2( $text ) );
1992 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1993 $s .= $prefix . $this->armorLinks(
1994 $this->makeImage( $nt, $text, $holders ) ) . $trail;
1996 $s .= $prefix . $trail;
1998 wfProfileOut( __METHOD__
."-image" );
2002 if ( $ns == NS_CATEGORY
) {
2003 wfProfileIn( __METHOD__
."-category" );
2004 $s = rtrim( $s . "\n" ); # bug 87
2007 $sortkey = $this->getDefaultSort();
2011 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
2012 $sortkey = str_replace( "\n", '', $sortkey );
2013 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
2014 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
2017 * Strip the whitespace Category links produce, see bug 87
2018 * @todo We might want to use trim($tmp, "\n") here.
2020 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
2022 wfProfileOut( __METHOD__
."-category" );
2027 # Self-link checking
2028 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
2029 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
2030 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2035 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2036 # @todo FIXME: Should do batch file existence checks, see comment below
2037 if ( $ns == NS_MEDIA
) {
2038 wfProfileIn( __METHOD__
."-media" );
2039 # Give extensions a chance to select the file revision for us
2042 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2043 array( $this, $nt, &$options, &$descQuery ) );
2044 # Fetch and register the file (file title may be different via hooks)
2045 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2046 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2047 $s .= $prefix . $this->armorLinks(
2048 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2049 wfProfileOut( __METHOD__
."-media" );
2053 wfProfileIn( __METHOD__
."-always_known" );
2054 # Some titles, such as valid special pages or files in foreign repos, should
2055 # be shown as bluelinks even though they're not included in the page table
2057 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2058 # batch file existence checks for NS_FILE and NS_MEDIA
2059 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2060 $this->mOutput
->addLink( $nt );
2061 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2063 # Links will be added to the output link list after checking
2064 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2066 wfProfileOut( __METHOD__
."-always_known" );
2068 wfProfileOut( __METHOD__
);
2073 * Render a forced-blue link inline; protect against double expansion of
2074 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2075 * Since this little disaster has to split off the trail text to avoid
2076 * breaking URLs in the following text without breaking trails on the
2077 * wiki links, it's been made into a horrible function.
2080 * @param $text String
2081 * @param $query Array or String
2082 * @param $trail String
2083 * @param $prefix String
2084 * @return String: HTML-wikitext mix oh yuck
2086 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2087 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2089 if ( is_string( $query ) ) {
2090 $query = wfCgiToArray( $query );
2092 if ( $text == '' ) {
2093 $text = htmlspecialchars( $nt->getPrefixedText() );
2096 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2098 return $this->armorLinks( $link ) . $trail;
2102 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2103 * going to go through further parsing steps before inline URL expansion.
2105 * Not needed quite as much as it used to be since free links are a bit
2106 * more sensible these days. But bracketed links are still an issue.
2108 * @param $text String: more-or-less HTML
2109 * @return String: less-or-more HTML with NOPARSE bits
2111 function armorLinks( $text ) {
2112 return preg_replace( '/\b((?i)' . $this->mUrlProtocols
. ')/',
2113 "{$this->mUniqPrefix}NOPARSE$1", $text );
2117 * Return true if subpage links should be expanded on this page.
2120 function areSubpagesAllowed() {
2121 # Some namespaces don't allow subpages
2122 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2126 * Handle link to subpage if necessary
2128 * @param $target String: the source of the link
2129 * @param &$text String: the link text, modified as necessary
2130 * @return string the full name of the link
2133 function maybeDoSubpageLink( $target, &$text ) {
2134 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2138 * Used by doBlockLevels()
2143 function closeParagraph() {
2145 if ( $this->mLastSection
!= '' ) {
2146 $result = '</' . $this->mLastSection
. ">\n";
2148 $this->mInPre
= false;
2149 $this->mLastSection
= '';
2154 * getCommon() returns the length of the longest common substring
2155 * of both arguments, starting at the beginning of both.
2158 * @param $st1 string
2159 * @param $st2 string
2163 function getCommon( $st1, $st2 ) {
2164 $fl = strlen( $st1 );
2165 $shorter = strlen( $st2 );
2166 if ( $fl < $shorter ) {
2170 for ( $i = 0; $i < $shorter; ++
$i ) {
2171 if ( $st1[$i] != $st2[$i] ) {
2179 * These next three functions open, continue, and close the list
2180 * element appropriate to the prefix character passed into them.
2183 * @param $char string
2187 function openList( $char ) {
2188 $result = $this->closeParagraph();
2190 if ( '*' === $char ) {
2191 $result .= '<ul><li>';
2192 } elseif ( '#' === $char ) {
2193 $result .= '<ol><li>';
2194 } elseif ( ':' === $char ) {
2195 $result .= '<dl><dd>';
2196 } elseif ( ';' === $char ) {
2197 $result .= '<dl><dt>';
2198 $this->mDTopen
= true;
2200 $result = '<!-- ERR 1 -->';
2208 * @param $char String
2213 function nextItem( $char ) {
2214 if ( '*' === $char ||
'#' === $char ) {
2216 } elseif ( ':' === $char ||
';' === $char ) {
2218 if ( $this->mDTopen
) {
2221 if ( ';' === $char ) {
2222 $this->mDTopen
= true;
2223 return $close . '<dt>';
2225 $this->mDTopen
= false;
2226 return $close . '<dd>';
2229 return '<!-- ERR 2 -->';
2234 * @param $char String
2239 function closeList( $char ) {
2240 if ( '*' === $char ) {
2241 $text = '</li></ul>';
2242 } elseif ( '#' === $char ) {
2243 $text = '</li></ol>';
2244 } elseif ( ':' === $char ) {
2245 if ( $this->mDTopen
) {
2246 $this->mDTopen
= false;
2247 $text = '</dt></dl>';
2249 $text = '</dd></dl>';
2252 return '<!-- ERR 3 -->';
2259 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2261 * @param $text String
2262 * @param $linestart Boolean: whether or not this is at the start of a line.
2264 * @return string the lists rendered as HTML
2266 function doBlockLevels( $text, $linestart ) {
2267 wfProfileIn( __METHOD__
);
2269 # Parsing through the text line by line. The main thing
2270 # happening here is handling of block-level elements p, pre,
2271 # and making lists from lines starting with * # : etc.
2273 $textLines = StringUtils
::explode( "\n", $text );
2275 $lastPrefix = $output = '';
2276 $this->mDTopen
= $inBlockElem = false;
2278 $paragraphStack = false;
2280 foreach ( $textLines as $oLine ) {
2282 if ( !$linestart ) {
2292 $lastPrefixLength = strlen( $lastPrefix );
2293 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2294 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2295 # If not in a <pre> element, scan for and figure out what prefixes are there.
2296 if ( !$this->mInPre
) {
2297 # Multiple prefixes may abut each other for nested lists.
2298 $prefixLength = strspn( $oLine, '*#:;' );
2299 $prefix = substr( $oLine, 0, $prefixLength );
2302 # ; and : are both from definition-lists, so they're equivalent
2303 # for the purposes of determining whether or not we need to open/close
2305 $prefix2 = str_replace( ';', ':', $prefix );
2306 $t = substr( $oLine, $prefixLength );
2307 $this->mInPre
= (bool)$preOpenMatch;
2309 # Don't interpret any other prefixes in preformatted text
2311 $prefix = $prefix2 = '';
2316 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2317 # Same as the last item, so no need to deal with nesting or opening stuff
2318 $output .= $this->nextItem( substr( $prefix, -1 ) );
2319 $paragraphStack = false;
2321 if ( substr( $prefix, -1 ) === ';') {
2322 # The one nasty exception: definition lists work like this:
2323 # ; title : definition text
2324 # So we check for : in the remainder text to split up the
2325 # title and definition, without b0rking links.
2327 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2329 $output .= $term . $this->nextItem( ':' );
2332 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2333 # We need to open or close prefixes, or both.
2335 # Either open or close a level...
2336 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2337 $paragraphStack = false;
2339 # Close all the prefixes which aren't shared.
2340 while ( $commonPrefixLength < $lastPrefixLength ) {
2341 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2342 --$lastPrefixLength;
2345 # Continue the current prefix if appropriate.
2346 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2347 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2350 # Open prefixes where appropriate.
2351 while ( $prefixLength > $commonPrefixLength ) {
2352 $char = substr( $prefix, $commonPrefixLength, 1 );
2353 $output .= $this->openList( $char );
2355 if ( ';' === $char ) {
2356 # @todo FIXME: This is dupe of code above
2357 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2359 $output .= $term . $this->nextItem( ':' );
2362 ++
$commonPrefixLength;
2364 $lastPrefix = $prefix2;
2367 # If we have no prefixes, go to paragraph mode.
2368 if ( 0 == $prefixLength ) {
2369 wfProfileIn( __METHOD__
."-paragraph" );
2370 # No prefix (not in list)--go to paragraph mode
2371 # XXX: use a stack for nestable elements like span, table and div
2372 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2373 $closematch = preg_match(
2374 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2375 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2376 if ( $openmatch or $closematch ) {
2377 $paragraphStack = false;
2378 # TODO bug 5718: paragraph closed
2379 $output .= $this->closeParagraph();
2380 if ( $preOpenMatch and !$preCloseMatch ) {
2381 $this->mInPre
= true;
2383 $inBlockElem = !$closematch;
2384 } elseif ( !$inBlockElem && !$this->mInPre
) {
2385 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2387 if ( $this->mLastSection
!== 'pre' ) {
2388 $paragraphStack = false;
2389 $output .= $this->closeParagraph().'<pre>';
2390 $this->mLastSection
= 'pre';
2392 $t = substr( $t, 1 );
2395 if ( trim( $t ) === '' ) {
2396 if ( $paragraphStack ) {
2397 $output .= $paragraphStack.'<br />';
2398 $paragraphStack = false;
2399 $this->mLastSection
= 'p';
2401 if ( $this->mLastSection
!== 'p' ) {
2402 $output .= $this->closeParagraph();
2403 $this->mLastSection
= '';
2404 $paragraphStack = '<p>';
2406 $paragraphStack = '</p><p>';
2410 if ( $paragraphStack ) {
2411 $output .= $paragraphStack;
2412 $paragraphStack = false;
2413 $this->mLastSection
= 'p';
2414 } elseif ( $this->mLastSection
!== 'p' ) {
2415 $output .= $this->closeParagraph().'<p>';
2416 $this->mLastSection
= 'p';
2421 wfProfileOut( __METHOD__
."-paragraph" );
2423 # somewhere above we forget to get out of pre block (bug 785)
2424 if ( $preCloseMatch && $this->mInPre
) {
2425 $this->mInPre
= false;
2427 if ( $paragraphStack === false ) {
2431 while ( $prefixLength ) {
2432 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2435 if ( $this->mLastSection
!= '' ) {
2436 $output .= '</' . $this->mLastSection
. '>';
2437 $this->mLastSection
= '';
2440 wfProfileOut( __METHOD__
);
2445 * Split up a string on ':', ignoring any occurrences inside tags
2446 * to prevent illegal overlapping.
2448 * @param $str String the string to split
2449 * @param &$before String set to everything before the ':'
2450 * @param &$after String set to everything after the ':'
2451 * @return String the position of the ':', or false if none found
2453 function findColonNoLinks( $str, &$before, &$after ) {
2454 wfProfileIn( __METHOD__
);
2456 $pos = strpos( $str, ':' );
2457 if ( $pos === false ) {
2459 wfProfileOut( __METHOD__
);
2463 $lt = strpos( $str, '<' );
2464 if ( $lt === false ||
$lt > $pos ) {
2465 # Easy; no tag nesting to worry about
2466 $before = substr( $str, 0, $pos );
2467 $after = substr( $str, $pos+
1 );
2468 wfProfileOut( __METHOD__
);
2472 # Ugly state machine to walk through avoiding tags.
2473 $state = self
::COLON_STATE_TEXT
;
2475 $len = strlen( $str );
2476 for( $i = 0; $i < $len; $i++
) {
2480 # (Using the number is a performance hack for common cases)
2481 case 0: # self::COLON_STATE_TEXT:
2484 # Could be either a <start> tag or an </end> tag
2485 $state = self
::COLON_STATE_TAGSTART
;
2488 if ( $stack == 0 ) {
2490 $before = substr( $str, 0, $i );
2491 $after = substr( $str, $i +
1 );
2492 wfProfileOut( __METHOD__
);
2495 # Embedded in a tag; don't break it.
2498 # Skip ahead looking for something interesting
2499 $colon = strpos( $str, ':', $i );
2500 if ( $colon === false ) {
2501 # Nothing else interesting
2502 wfProfileOut( __METHOD__
);
2505 $lt = strpos( $str, '<', $i );
2506 if ( $stack === 0 ) {
2507 if ( $lt === false ||
$colon < $lt ) {
2509 $before = substr( $str, 0, $colon );
2510 $after = substr( $str, $colon +
1 );
2511 wfProfileOut( __METHOD__
);
2515 if ( $lt === false ) {
2516 # Nothing else interesting to find; abort!
2517 # We're nested, but there's no close tags left. Abort!
2520 # Skip ahead to next tag start
2522 $state = self
::COLON_STATE_TAGSTART
;
2525 case 1: # self::COLON_STATE_TAG:
2530 $state = self
::COLON_STATE_TEXT
;
2533 # Slash may be followed by >?
2534 $state = self
::COLON_STATE_TAGSLASH
;
2540 case 2: # self::COLON_STATE_TAGSTART:
2543 $state = self
::COLON_STATE_CLOSETAG
;
2546 $state = self
::COLON_STATE_COMMENT
;
2549 # Illegal early close? This shouldn't happen D:
2550 $state = self
::COLON_STATE_TEXT
;
2553 $state = self
::COLON_STATE_TAG
;
2556 case 3: # self::COLON_STATE_CLOSETAG:
2561 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2562 wfProfileOut( __METHOD__
);
2565 $state = self
::COLON_STATE_TEXT
;
2568 case self
::COLON_STATE_TAGSLASH
:
2570 # Yes, a self-closed tag <blah/>
2571 $state = self
::COLON_STATE_TEXT
;
2573 # Probably we're jumping the gun, and this is an attribute
2574 $state = self
::COLON_STATE_TAG
;
2577 case 5: # self::COLON_STATE_COMMENT:
2579 $state = self
::COLON_STATE_COMMENTDASH
;
2582 case self
::COLON_STATE_COMMENTDASH
:
2584 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2586 $state = self
::COLON_STATE_COMMENT
;
2589 case self
::COLON_STATE_COMMENTDASHDASH
:
2591 $state = self
::COLON_STATE_TEXT
;
2593 $state = self
::COLON_STATE_COMMENT
;
2597 throw new MWException( "State machine error in " . __METHOD__
);
2601 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2602 wfProfileOut( __METHOD__
);
2605 wfProfileOut( __METHOD__
);
2610 * Return value of a magic variable (like PAGENAME)
2614 * @param $index integer
2615 * @param $frame PPFrame
2619 function getVariableValue( $index, $frame = false ) {
2620 global $wgContLang, $wgSitename, $wgServer;
2621 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2623 if ( is_null( $this->mTitle
) ) {
2624 // If no title set, bad things are going to happen
2625 // later. Title should always be set since this
2626 // should only be called in the middle of a parse
2627 // operation (but the unit-tests do funky stuff)
2628 throw new MWException( __METHOD__
. ' Should only be '
2629 . ' called while parsing (no title set)' );
2633 * Some of these require message or data lookups and can be
2634 * expensive to check many times.
2636 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2637 if ( isset( $this->mVarCache
[$index] ) ) {
2638 return $this->mVarCache
[$index];
2642 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2643 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2646 global $wgLocaltimezone;
2647 if ( isset( $wgLocaltimezone ) ) {
2648 $oldtz = date_default_timezone_get();
2649 date_default_timezone_set( $wgLocaltimezone );
2652 $localTimestamp = date( 'YmdHis', $ts );
2653 $localMonth = date( 'm', $ts );
2654 $localMonth1 = date( 'n', $ts );
2655 $localMonthName = date( 'n', $ts );
2656 $localDay = date( 'j', $ts );
2657 $localDay2 = date( 'd', $ts );
2658 $localDayOfWeek = date( 'w', $ts );
2659 $localWeek = date( 'W', $ts );
2660 $localYear = date( 'Y', $ts );
2661 $localHour = date( 'H', $ts );
2662 if ( isset( $wgLocaltimezone ) ) {
2663 date_default_timezone_set( $oldtz );
2666 $pageLang = $this->getFunctionLang();
2669 case 'currentmonth':
2670 $value = $pageLang->formatNum( gmdate( 'm', $ts ) );
2672 case 'currentmonth1':
2673 $value = $pageLang->formatNum( gmdate( 'n', $ts ) );
2675 case 'currentmonthname':
2676 $value = $pageLang->getMonthName( gmdate( 'n', $ts ) );
2678 case 'currentmonthnamegen':
2679 $value = $pageLang->getMonthNameGen( gmdate( 'n', $ts ) );
2681 case 'currentmonthabbrev':
2682 $value = $pageLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2685 $value = $pageLang->formatNum( gmdate( 'j', $ts ) );
2688 $value = $pageLang->formatNum( gmdate( 'd', $ts ) );
2691 $value = $pageLang->formatNum( $localMonth );
2694 $value = $pageLang->formatNum( $localMonth1 );
2696 case 'localmonthname':
2697 $value = $pageLang->getMonthName( $localMonthName );
2699 case 'localmonthnamegen':
2700 $value = $pageLang->getMonthNameGen( $localMonthName );
2702 case 'localmonthabbrev':
2703 $value = $pageLang->getMonthAbbreviation( $localMonthName );
2706 $value = $pageLang->formatNum( $localDay );
2709 $value = $pageLang->formatNum( $localDay2 );
2712 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2715 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2717 case 'fullpagename':
2718 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2720 case 'fullpagenamee':
2721 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2724 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2726 case 'subpagenamee':
2727 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2729 case 'basepagename':
2730 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2732 case 'basepagenamee':
2733 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2735 case 'talkpagename':
2736 if ( $this->mTitle
->canTalk() ) {
2737 $talkPage = $this->mTitle
->getTalkPage();
2738 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2743 case 'talkpagenamee':
2744 if ( $this->mTitle
->canTalk() ) {
2745 $talkPage = $this->mTitle
->getTalkPage();
2746 $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() );
2751 case 'subjectpagename':
2752 $subjPage = $this->mTitle
->getSubjectPage();
2753 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2755 case 'subjectpagenamee':
2756 $subjPage = $this->mTitle
->getSubjectPage();
2757 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() );
2759 case 'pageid': // requested in bug 23427
2760 $pageid = $this->getTitle()->getArticleId();
2761 if( $pageid == 0 ) {
2762 # 0 means the page doesn't exist in the database,
2763 # which means the user is previewing a new page.
2764 # The vary-revision flag must be set, because the magic word
2765 # will have a different value once the page is saved.
2766 $this->mOutput
->setFlag( 'vary-revision' );
2767 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2769 $value = $pageid ?
$pageid : null;
2772 # Let the edit saving system know we should parse the page
2773 # *after* a revision ID has been assigned.
2774 $this->mOutput
->setFlag( 'vary-revision' );
2775 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2776 $value = $this->mRevisionId
;
2779 # Let the edit saving system know we should parse the page
2780 # *after* a revision ID has been assigned. This is for null edits.
2781 $this->mOutput
->setFlag( 'vary-revision' );
2782 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2783 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2785 case 'revisionday2':
2786 # Let the edit saving system know we should parse the page
2787 # *after* a revision ID has been assigned. This is for null edits.
2788 $this->mOutput
->setFlag( 'vary-revision' );
2789 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2790 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2792 case 'revisionmonth':
2793 # Let the edit saving system know we should parse the page
2794 # *after* a revision ID has been assigned. This is for null edits.
2795 $this->mOutput
->setFlag( 'vary-revision' );
2796 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2797 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2799 case 'revisionmonth1':
2800 # Let the edit saving system know we should parse the page
2801 # *after* a revision ID has been assigned. This is for null edits.
2802 $this->mOutput
->setFlag( 'vary-revision' );
2803 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2804 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2806 case 'revisionyear':
2807 # Let the edit saving system know we should parse the page
2808 # *after* a revision ID has been assigned. This is for null edits.
2809 $this->mOutput
->setFlag( 'vary-revision' );
2810 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2811 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2813 case 'revisiontimestamp':
2814 # Let the edit saving system know we should parse the page
2815 # *after* a revision ID has been assigned. This is for null edits.
2816 $this->mOutput
->setFlag( 'vary-revision' );
2817 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2818 $value = $this->getRevisionTimestamp();
2820 case 'revisionuser':
2821 # Let the edit saving system know we should parse the page
2822 # *after* a revision ID has been assigned. This is for null edits.
2823 $this->mOutput
->setFlag( 'vary-revision' );
2824 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2825 $value = $this->getRevisionUser();
2828 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2831 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2833 case 'namespacenumber':
2834 $value = $this->mTitle
->getNamespace();
2837 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2840 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2842 case 'subjectspace':
2843 $value = $this->mTitle
->getSubjectNsText();
2845 case 'subjectspacee':
2846 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2848 case 'currentdayname':
2849 $value = $pageLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2852 $value = $pageLang->formatNum( gmdate( 'Y', $ts ), true );
2855 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2858 $value = $pageLang->formatNum( gmdate( 'H', $ts ), true );
2861 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2862 # int to remove the padding
2863 $value = $pageLang->formatNum( (int)gmdate( 'W', $ts ) );
2866 $value = $pageLang->formatNum( gmdate( 'w', $ts ) );
2868 case 'localdayname':
2869 $value = $pageLang->getWeekdayName( $localDayOfWeek +
1 );
2872 $value = $pageLang->formatNum( $localYear, true );
2875 $value = $pageLang->time( $localTimestamp, false, false );
2878 $value = $pageLang->formatNum( $localHour, true );
2881 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2882 # int to remove the padding
2883 $value = $pageLang->formatNum( (int)$localWeek );
2886 $value = $pageLang->formatNum( $localDayOfWeek );
2888 case 'numberofarticles':
2889 $value = $pageLang->formatNum( SiteStats
::articles() );
2891 case 'numberoffiles':
2892 $value = $pageLang->formatNum( SiteStats
::images() );
2894 case 'numberofusers':
2895 $value = $pageLang->formatNum( SiteStats
::users() );
2897 case 'numberofactiveusers':
2898 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2900 case 'numberofpages':
2901 $value = $pageLang->formatNum( SiteStats
::pages() );
2903 case 'numberofadmins':
2904 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2906 case 'numberofedits':
2907 $value = $pageLang->formatNum( SiteStats
::edits() );
2909 case 'numberofviews':
2910 global $wgDisableCounters;
2911 $value = !$wgDisableCounters ?
$pageLang->formatNum( SiteStats
::views() ) : '';
2913 case 'currenttimestamp':
2914 $value = wfTimestamp( TS_MW
, $ts );
2916 case 'localtimestamp':
2917 $value = $localTimestamp;
2919 case 'currentversion':
2920 $value = SpecialVersion
::getVersion();
2923 return $wgArticlePath;
2929 $serverParts = wfParseUrl( $wgServer );
2930 return $serverParts && isset( $serverParts['host'] ) ?
$serverParts['host'] : $wgServer;
2932 return $wgScriptPath;
2934 return $wgStylePath;
2935 case 'directionmark':
2936 return $pageLang->getDirMark();
2937 case 'contentlanguage':
2938 global $wgLanguageCode;
2939 return $wgLanguageCode;
2942 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2950 $this->mVarCache
[$index] = $value;
2957 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2961 function initialiseVariables() {
2962 wfProfileIn( __METHOD__
);
2963 $variableIDs = MagicWord
::getVariableIDs();
2964 $substIDs = MagicWord
::getSubstIDs();
2966 $this->mVariables
= new MagicWordArray( $variableIDs );
2967 $this->mSubstWords
= new MagicWordArray( $substIDs );
2968 wfProfileOut( __METHOD__
);
2972 * Preprocess some wikitext and return the document tree.
2973 * This is the ghost of replace_variables().
2975 * @param $text String: The text to parse
2976 * @param $flags Integer: bitwise combination of:
2977 * self::PTD_FOR_INCLUSION Handle "<noinclude>" and "<includeonly>" as if the text is being
2978 * included. Default is to assume a direct page view.
2980 * The generated DOM tree must depend only on the input text and the flags.
2981 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2983 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2984 * change in the DOM tree for a given text, must be passed through the section identifier
2985 * in the section edit link and thus back to extractSections().
2987 * The output of this function is currently only cached in process memory, but a persistent
2988 * cache may be implemented at a later date which takes further advantage of these strict
2989 * dependency requirements.
2995 function preprocessToDom( $text, $flags = 0 ) {
2996 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
3001 * Return a three-element array: leading whitespace, string contents, trailing whitespace
3007 public static function splitWhitespace( $s ) {
3008 $ltrimmed = ltrim( $s );
3009 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
3010 $trimmed = rtrim( $ltrimmed );
3011 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
3013 $w2 = substr( $ltrimmed, -$diff );
3017 return array( $w1, $trimmed, $w2 );
3021 * Replace magic variables, templates, and template arguments
3022 * with the appropriate text. Templates are substituted recursively,
3023 * taking care to avoid infinite loops.
3025 * Note that the substitution depends on value of $mOutputType:
3026 * self::OT_WIKI: only {{subst:}} templates
3027 * self::OT_PREPROCESS: templates but not extension tags
3028 * self::OT_HTML: all templates and extension tags
3030 * @param $text String the text to transform
3031 * @param $frame PPFrame Object describing the arguments passed to the template.
3032 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
3033 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
3034 * @param $argsOnly Boolean only do argument (triple-brace) expansion, not double-brace expansion
3039 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3040 # Is there any text? Also, Prevent too big inclusions!
3041 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3044 wfProfileIn( __METHOD__
);
3046 if ( $frame === false ) {
3047 $frame = $this->getPreprocessor()->newFrame();
3048 } elseif ( !( $frame instanceof PPFrame
) ) {
3049 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
3050 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3053 $dom = $this->preprocessToDom( $text );
3054 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3055 $text = $frame->expand( $dom, $flags );
3057 wfProfileOut( __METHOD__
);
3062 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3064 * @param $args array
3068 static function createAssocArgs( $args ) {
3069 $assocArgs = array();
3071 foreach ( $args as $arg ) {
3072 $eqpos = strpos( $arg, '=' );
3073 if ( $eqpos === false ) {
3074 $assocArgs[$index++
] = $arg;
3076 $name = trim( substr( $arg, 0, $eqpos ) );
3077 $value = trim( substr( $arg, $eqpos+
1 ) );
3078 if ( $value === false ) {
3081 if ( $name !== false ) {
3082 $assocArgs[$name] = $value;
3091 * Warn the user when a parser limitation is reached
3092 * Will warn at most once the user per limitation type
3094 * @param $limitationType String: should be one of:
3095 * 'expensive-parserfunction' (corresponding messages:
3096 * 'expensive-parserfunction-warning',
3097 * 'expensive-parserfunction-category')
3098 * 'post-expand-template-argument' (corresponding messages:
3099 * 'post-expand-template-argument-warning',
3100 * 'post-expand-template-argument-category')
3101 * 'post-expand-template-inclusion' (corresponding messages:
3102 * 'post-expand-template-inclusion-warning',
3103 * 'post-expand-template-inclusion-category')
3104 * @param $current int|null Current value
3105 * @param $max int|null Maximum allowed, when an explicit limit has been
3106 * exceeded, provide the values (optional)
3108 function limitationWarn( $limitationType, $current = '', $max = '' ) {
3109 # does no harm if $current and $max are present but are unnecessary for the message
3110 $warning = wfMessage( "$limitationType-warning" )->numParams( $current, $max )
3111 ->inContentLanguage()->escaped();
3112 $this->mOutput
->addWarning( $warning );
3113 $this->addTrackingCategory( "$limitationType-category" );
3117 * Return the text of a template, after recursively
3118 * replacing any variables or templates within the template.
3120 * @param $piece Array: the parts of the template
3121 * $piece['title']: the title, i.e. the part before the |
3122 * $piece['parts']: the parameter array
3123 * $piece['lineStart']: whether the brace was at the start of a line
3124 * @param $frame PPFrame The current frame, contains template arguments
3125 * @return String: the text of the template
3128 function braceSubstitution( $piece, $frame ) {
3130 wfProfileIn( __METHOD__
);
3131 wfProfileIn( __METHOD__
.'-setup' );
3134 $found = false; # $text has been filled
3135 $nowiki = false; # wiki markup in $text should be escaped
3136 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3137 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3138 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3139 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3141 # Title object, where $text came from
3144 # $part1 is the bit before the first |, and must contain only title characters.
3145 # Various prefixes will be stripped from it later.
3146 $titleWithSpaces = $frame->expand( $piece['title'] );
3147 $part1 = trim( $titleWithSpaces );
3150 # Original title text preserved for various purposes
3151 $originalTitle = $part1;
3153 # $args is a list of argument nodes, starting from index 0, not including $part1
3154 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3155 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3156 wfProfileOut( __METHOD__
.'-setup' );
3158 $titleProfileIn = null; // profile templates
3161 wfProfileIn( __METHOD__
.'-modifiers' );
3164 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3166 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3167 # Decide whether to expand template or keep wikitext as-is.
3168 if ( $this->ot
['wiki'] ) {
3169 if ( $substMatch === false ) {
3170 $literal = true; # literal when in PST with no prefix
3172 $literal = false; # expand when in PST with subst: or safesubst:
3175 if ( $substMatch == 'subst' ) {
3176 $literal = true; # literal when not in PST with plain subst:
3178 $literal = false; # expand when not in PST with safesubst: or no prefix
3182 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3189 if ( !$found && $args->getLength() == 0 ) {
3190 $id = $this->mVariables
->matchStartToEnd( $part1 );
3191 if ( $id !== false ) {
3192 $text = $this->getVariableValue( $id, $frame );
3193 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3194 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3200 # MSG, MSGNW and RAW
3203 $mwMsgnw = MagicWord
::get( 'msgnw' );
3204 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3207 # Remove obsolete MSG:
3208 $mwMsg = MagicWord
::get( 'msg' );
3209 $mwMsg->matchStartAndRemove( $part1 );
3213 $mwRaw = MagicWord
::get( 'raw' );
3214 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3215 $forceRawInterwiki = true;
3218 wfProfileOut( __METHOD__
.'-modifiers' );
3222 wfProfileIn( __METHOD__
. '-pfunc' );
3224 $colonPos = strpos( $part1, ':' );
3225 if ( $colonPos !== false ) {
3226 # Case sensitive functions
3227 $function = substr( $part1, 0, $colonPos );
3228 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3229 $function = $this->mFunctionSynonyms
[1][$function];
3231 # Case insensitive functions
3232 $function = $wgContLang->lc( $function );
3233 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3234 $function = $this->mFunctionSynonyms
[0][$function];
3240 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3241 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3242 $initialArgs = array( &$this );
3243 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3244 if ( $flags & SFH_OBJECT_ARGS
) {
3245 # Add a frame parameter, and pass the arguments as an array
3246 $allArgs = $initialArgs;
3247 $allArgs[] = $frame;
3248 for ( $i = 0; $i < $args->getLength(); $i++
) {
3249 $funcArgs[] = $args->item( $i );
3251 $allArgs[] = $funcArgs;
3253 # Convert arguments to plain text
3254 for ( $i = 0; $i < $args->getLength(); $i++
) {
3255 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3257 $allArgs = array_merge( $initialArgs, $funcArgs );
3260 # Workaround for PHP bug 35229 and similar
3261 if ( !is_callable( $callback ) ) {
3262 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3263 wfProfileOut( __METHOD__
. '-pfunc' );
3264 wfProfileOut( __METHOD__
);
3265 throw new MWException( "Tag hook for $function is not callable\n" );
3267 $result = call_user_func_array( $callback, $allArgs );
3270 $preprocessFlags = 0;
3272 if ( is_array( $result ) ) {
3273 if ( isset( $result[0] ) ) {
3275 unset( $result[0] );
3278 # Extract flags into the local scope
3279 # This allows callers to set flags such as nowiki, found, etc.
3285 $text = $this->preprocessToDom( $text, $preprocessFlags );
3288 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3291 wfProfileOut( __METHOD__
. '-pfunc' );
3294 # Finish mangling title and then check for loops.
3295 # Set $title to a Title object and $titleText to the PDBK
3298 # Split the title into page and subpage
3300 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3301 if ( $subpage !== '' ) {
3302 $ns = $this->mTitle
->getNamespace();
3304 $title = Title
::newFromText( $part1, $ns );
3306 $titleText = $title->getPrefixedText();
3307 # Check for language variants if the template is not found
3308 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3309 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3311 # Do recursion depth check
3312 $limit = $this->mOptions
->getMaxTemplateDepth();
3313 if ( $frame->depth
>= $limit ) {
3315 $text = '<span class="error">'
3316 . wfMessage( 'parser-template-recursion-depth-warning' )
3317 ->numParams( $limit )->inContentLanguage()->text()
3323 # Load from database
3324 if ( !$found && $title ) {
3325 if ( !Profiler
::instance()->isPersistent() ) {
3326 # Too many unique items can kill profiling DBs/collectors
3327 $titleProfileIn = __METHOD__
. "-title-" . $title->getDBKey();
3328 wfProfileIn( $titleProfileIn ); // template in
3330 wfProfileIn( __METHOD__
. '-loadtpl' );
3331 if ( !$title->isExternal() ) {
3332 if ( $title->isSpecialPage()
3333 && $this->mOptions
->getAllowSpecialInclusion()
3334 && $this->ot
['html'] )
3336 // Pass the template arguments as URL parameters.
3337 // "uselang" will have no effect since the Language object
3338 // is forced to the one defined in ParserOptions.
3339 $pageArgs = array();
3340 for ( $i = 0; $i < $args->getLength(); $i++
) {
3341 $bits = $args->item( $i )->splitArg();
3342 if ( strval( $bits['index'] ) === '' ) {
3343 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3344 $value = trim( $frame->expand( $bits['value'] ) );
3345 $pageArgs[$name] = $value;
3349 // Create a new context to execute the special page
3350 $context = new RequestContext
;
3351 $context->setTitle( $title );
3352 $context->setRequest( new FauxRequest( $pageArgs ) );
3353 $context->setUser( $this->getUser() );
3354 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3355 $ret = SpecialPageFactory
::capturePath( $title, $context );
3357 $text = $context->getOutput()->getHTML();
3358 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3361 $this->disableCache();
3363 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3364 $found = false; # access denied
3365 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3367 list( $text, $title ) = $this->getTemplateDom( $title );
3368 if ( $text !== false ) {
3374 # If the title is valid but undisplayable, make a link to it
3375 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3376 $text = "[[:$titleText]]";
3379 } elseif ( $title->isTrans() ) {
3380 # Interwiki transclusion
3381 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3382 $text = $this->interwikiTransclude( $title, 'render' );
3385 $text = $this->interwikiTransclude( $title, 'raw' );
3386 # Preprocess it like a template
3387 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3393 # Do infinite loop check
3394 # This has to be done after redirect resolution to avoid infinite loops via redirects
3395 if ( !$frame->loopCheck( $title ) ) {
3397 $text = '<span class="error">'
3398 . wfMessage( 'parser-template-loop-warning', $titleText )->inContentLanguage()->text()
3400 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3402 wfProfileOut( __METHOD__
. '-loadtpl' );
3405 # If we haven't found text to substitute by now, we're done
3406 # Recover the source wikitext and return it
3408 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3409 if ( $titleProfileIn ) {
3410 wfProfileOut( $titleProfileIn ); // template out
3412 wfProfileOut( __METHOD__
);
3413 return array( 'object' => $text );
3416 # Expand DOM-style return values in a child frame
3417 if ( $isChildObj ) {
3418 # Clean up argument array
3419 $newFrame = $frame->newChild( $args, $title );
3422 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3423 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3424 # Expansion is eligible for the empty-frame cache
3425 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3426 $text = $this->mTplExpandCache
[$titleText];
3428 $text = $newFrame->expand( $text );
3429 $this->mTplExpandCache
[$titleText] = $text;
3432 # Uncached expansion
3433 $text = $newFrame->expand( $text );
3436 if ( $isLocalObj && $nowiki ) {
3437 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3438 $isLocalObj = false;
3441 if ( $titleProfileIn ) {
3442 wfProfileOut( $titleProfileIn ); // template out
3445 # Replace raw HTML by a placeholder
3447 $text = $this->insertStripItem( $text );
3448 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3449 # Escape nowiki-style return values
3450 $text = wfEscapeWikiText( $text );
3451 } elseif ( is_string( $text )
3452 && !$piece['lineStart']
3453 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3455 # Bug 529: if the template begins with a table or block-level
3456 # element, it should be treated as beginning a new line.
3457 # This behaviour is somewhat controversial.
3458 $text = "\n" . $text;
3461 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3462 # Error, oversize inclusion
3463 if ( $titleText !== false ) {
3464 # Make a working, properly escaped link if possible (bug 23588)
3465 $text = "[[:$titleText]]";
3467 # This will probably not be a working link, but at least it may
3468 # provide some hint of where the problem is
3469 preg_replace( '/^:/', '', $originalTitle );
3470 $text = "[[:$originalTitle]]";
3472 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3473 $this->limitationWarn( 'post-expand-template-inclusion' );
3476 if ( $isLocalObj ) {
3477 $ret = array( 'object' => $text );
3479 $ret = array( 'text' => $text );
3482 wfProfileOut( __METHOD__
);
3487 * Get the semi-parsed DOM representation of a template with a given title,
3488 * and its redirect destination title. Cached.
3490 * @param $title Title
3494 function getTemplateDom( $title ) {
3495 $cacheTitle = $title;
3496 $titleText = $title->getPrefixedDBkey();
3498 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3499 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3500 $title = Title
::makeTitle( $ns, $dbk );
3501 $titleText = $title->getPrefixedDBkey();
3503 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3504 return array( $this->mTplDomCache
[$titleText], $title );
3507 # Cache miss, go to the database
3508 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3510 if ( $text === false ) {
3511 $this->mTplDomCache
[$titleText] = false;
3512 return array( false, $title );
3515 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3516 $this->mTplDomCache
[ $titleText ] = $dom;
3518 if ( !$title->equals( $cacheTitle ) ) {
3519 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3520 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3523 return array( $dom, $title );
3527 * Fetch the unparsed text of a template and register a reference to it.
3528 * @param Title $title
3529 * @return Array ( string or false, Title )
3531 function fetchTemplateAndTitle( $title ) {
3532 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3533 $stuff = call_user_func( $templateCb, $title, $this );
3534 $text = $stuff['text'];
3535 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3536 if ( isset( $stuff['deps'] ) ) {
3537 foreach ( $stuff['deps'] as $dep ) {
3538 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3541 return array( $text, $finalTitle );
3545 * Fetch the unparsed text of a template and register a reference to it.
3546 * @param Title $title
3547 * @return mixed string or false
3549 function fetchTemplate( $title ) {
3550 $rv = $this->fetchTemplateAndTitle( $title );
3555 * Static function to get a template
3556 * Can be overridden via ParserOptions::setTemplateCallback().
3558 * @param $title Title
3559 * @param $parser Parser
3563 static function statelessFetchTemplate( $title, $parser = false ) {
3564 $text = $skip = false;
3565 $finalTitle = $title;
3568 # Loop to fetch the article, with up to 1 redirect
3569 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3570 # Give extensions a chance to select the revision instead
3571 $id = false; # Assume current
3572 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3573 array( $parser, $title, &$skip, &$id ) );
3579 'page_id' => $title->getArticleID(),
3586 ? Revision
::newFromId( $id )
3587 : Revision
::newFromTitle( $title, false, Revision
::READ_NORMAL
);
3588 $rev_id = $rev ?
$rev->getId() : 0;
3589 # If there is no current revision, there is no page
3590 if ( $id === false && !$rev ) {
3591 $linkCache = LinkCache
::singleton();
3592 $linkCache->addBadLinkObj( $title );
3597 'page_id' => $title->getArticleID(),
3598 'rev_id' => $rev_id );
3599 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3600 # We fetched a rev from a different title; register it too...
3602 'title' => $rev->getTitle(),
3603 'page_id' => $rev->getPage(),
3604 'rev_id' => $rev_id );
3608 $text = $rev->getText();
3609 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3611 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3612 if ( !$message->exists() ) {
3616 $text = $message->plain();
3620 if ( $text === false ) {
3624 $finalTitle = $title;
3625 $title = Title
::newFromRedirect( $text );
3629 'finalTitle' => $finalTitle,
3634 * Fetch a file and its title and register a reference to it.
3635 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3636 * @param Title $title
3637 * @param Array $options Array of options to RepoGroup::findFile
3640 function fetchFile( $title, $options = array() ) {
3641 $res = $this->fetchFileAndTitle( $title, $options );
3646 * Fetch a file and its title and register a reference to it.
3647 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3648 * @param Title $title
3649 * @param Array $options Array of options to RepoGroup::findFile
3650 * @return Array ( File or false, Title of file )
3652 function fetchFileAndTitle( $title, $options = array() ) {
3653 if ( isset( $options['broken'] ) ) {
3654 $file = false; // broken thumbnail forced by hook
3655 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3656 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3657 } else { // get by (name,timestamp)
3658 $file = wfFindFile( $title, $options );
3660 $time = $file ?
$file->getTimestamp() : false;
3661 $sha1 = $file ?
$file->getSha1() : false;
3662 # Register the file as a dependency...
3663 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3664 if ( $file && !$title->equals( $file->getTitle() ) ) {
3665 # Update fetched file title
3666 $title = $file->getTitle();
3667 if ( is_null( $file->getRedirectedTitle() ) ) {
3668 # This file was not a redirect, but the title does not match.
3669 # Register under the new name because otherwise the link will
3671 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3674 return array( $file, $title );
3678 * Transclude an interwiki link.
3680 * @param $title Title
3685 function interwikiTransclude( $title, $action ) {
3686 global $wgEnableScaryTranscluding;
3688 if ( !$wgEnableScaryTranscluding ) {
3689 return wfMessage('scarytranscludedisabled')->inContentLanguage()->text();
3692 $url = $title->getFullUrl( "action=$action" );
3694 if ( strlen( $url ) > 255 ) {
3695 return wfMessage( 'scarytranscludetoolong' )->inContentLanguage()->text();
3697 return $this->fetchScaryTemplateMaybeFromCache( $url );
3701 * @param $url string
3702 * @return Mixed|String
3704 function fetchScaryTemplateMaybeFromCache( $url ) {
3705 global $wgTranscludeCacheExpiry;
3706 $dbr = wfGetDB( DB_SLAVE
);
3707 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3708 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3709 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3711 return $obj->tc_contents
;
3714 $text = Http
::get( $url );
3716 return wfMessage( 'scarytranscludefailed', $url )->inContentLanguage()->text();
3719 $dbw = wfGetDB( DB_MASTER
);
3720 $dbw->replace( 'transcache', array('tc_url'), array(
3722 'tc_time' => $dbw->timestamp( time() ),
3723 'tc_contents' => $text)
3729 * Triple brace replacement -- used for template arguments
3732 * @param $piece array
3733 * @param $frame PPFrame
3737 function argSubstitution( $piece, $frame ) {
3738 wfProfileIn( __METHOD__
);
3741 $parts = $piece['parts'];
3742 $nameWithSpaces = $frame->expand( $piece['title'] );
3743 $argName = trim( $nameWithSpaces );
3745 $text = $frame->getArgument( $argName );
3746 if ( $text === false && $parts->getLength() > 0
3750 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3753 # No match in frame, use the supplied default
3754 $object = $parts->item( 0 )->getChildren();
3756 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3757 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3758 $this->limitationWarn( 'post-expand-template-argument' );
3761 if ( $text === false && $object === false ) {
3763 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3765 if ( $error !== false ) {
3768 if ( $object !== false ) {
3769 $ret = array( 'object' => $object );
3771 $ret = array( 'text' => $text );
3774 wfProfileOut( __METHOD__
);
3779 * Return the text to be used for a given extension tag.
3780 * This is the ghost of strip().
3782 * @param $params array Associative array of parameters:
3783 * name PPNode for the tag name
3784 * attr PPNode for unparsed text where tag attributes are thought to be
3785 * attributes Optional associative array of parsed attributes
3786 * inner Contents of extension element
3787 * noClose Original text did not have a close tag
3788 * @param $frame PPFrame
3792 function extensionSubstitution( $params, $frame ) {
3793 $name = $frame->expand( $params['name'] );
3794 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3795 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3796 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3798 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3799 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3800 if ( $isFunctionTag ) {
3801 $markerType = 'none';
3803 $markerType = 'general';
3805 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3806 $name = strtolower( $name );
3807 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3808 if ( isset( $params['attributes'] ) ) {
3809 $attributes = $attributes +
$params['attributes'];
3812 if ( isset( $this->mTagHooks
[$name] ) ) {
3813 # Workaround for PHP bug 35229 and similar
3814 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3815 throw new MWException( "Tag hook for $name is not callable\n" );
3817 $output = call_user_func_array( $this->mTagHooks
[$name],
3818 array( $content, $attributes, $this, $frame ) );
3819 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3820 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3821 if ( !is_callable( $callback ) ) {
3822 throw new MWException( "Tag hook for $name is not callable\n" );
3825 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3827 $output = '<span class="error">Invalid tag extension name: ' .
3828 htmlspecialchars( $name ) . '</span>';
3831 if ( is_array( $output ) ) {
3832 # Extract flags to local scope (to override $markerType)
3834 $output = $flags[0];
3839 if ( is_null( $attrText ) ) {
3842 if ( isset( $params['attributes'] ) ) {
3843 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3844 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3845 htmlspecialchars( $attrValue ) . '"';
3848 if ( $content === null ) {
3849 $output = "<$name$attrText/>";
3851 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3852 $output = "<$name$attrText>$content$close";
3856 if ( $markerType === 'none' ) {
3858 } elseif ( $markerType === 'nowiki' ) {
3859 $this->mStripState
->addNoWiki( $marker, $output );
3860 } elseif ( $markerType === 'general' ) {
3861 $this->mStripState
->addGeneral( $marker, $output );
3863 throw new MWException( __METHOD__
.': invalid marker type' );
3869 * Increment an include size counter
3871 * @param $type String: the type of expansion
3872 * @param $size Integer: the size of the text
3873 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3875 function incrementIncludeSize( $type, $size ) {
3876 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3879 $this->mIncludeSizes
[$type] +
= $size;
3885 * Increment the expensive function count
3887 * @return Boolean: false if the limit has been exceeded
3889 function incrementExpensiveFunctionCount() {
3890 $this->mExpensiveFunctionCount++
;
3891 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
3895 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3896 * Fills $this->mDoubleUnderscores, returns the modified text
3898 * @param $text string
3902 function doDoubleUnderscore( $text ) {
3903 wfProfileIn( __METHOD__
);
3905 # The position of __TOC__ needs to be recorded
3906 $mw = MagicWord
::get( 'toc' );
3907 if ( $mw->match( $text ) ) {
3908 $this->mShowToc
= true;
3909 $this->mForceTocPosition
= true;
3911 # Set a placeholder. At the end we'll fill it in with the TOC.
3912 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3914 # Only keep the first one.
3915 $text = $mw->replace( '', $text );
3918 # Now match and remove the rest of them
3919 $mwa = MagicWord
::getDoubleUnderscoreArray();
3920 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3922 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3923 $this->mOutput
->mNoGallery
= true;
3925 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3926 $this->mShowToc
= false;
3928 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3929 $this->addTrackingCategory( 'hidden-category-category' );
3931 # (bug 8068) Allow control over whether robots index a page.
3933 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
3934 # is not desirable, the last one on the page should win.
3935 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3936 $this->mOutput
->setIndexPolicy( 'noindex' );
3937 $this->addTrackingCategory( 'noindex-category' );
3939 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3940 $this->mOutput
->setIndexPolicy( 'index' );
3941 $this->addTrackingCategory( 'index-category' );
3944 # Cache all double underscores in the database
3945 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
3946 $this->mOutput
->setProperty( $key, '' );
3949 wfProfileOut( __METHOD__
);
3954 * Add a tracking category, getting the title from a system message,
3955 * or print a debug message if the title is invalid.
3957 * @param $msg String: message key
3958 * @return Boolean: whether the addition was successful
3960 public function addTrackingCategory( $msg ) {
3961 if ( $this->mTitle
->getNamespace() === NS_SPECIAL
) {
3962 wfDebug( __METHOD__
.": Not adding tracking category $msg to special page!\n" );
3965 // Important to parse with correct title (bug 31469)
3966 $cat = wfMessage( $msg )
3967 ->title( $this->getTitle() )
3968 ->inContentLanguage()
3971 # Allow tracking categories to be disabled by setting them to "-"
3972 if ( $cat === '-' ) {
3976 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3977 if ( $containerCategory ) {
3978 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3981 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3987 * This function accomplishes several tasks:
3988 * 1) Auto-number headings if that option is enabled
3989 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3990 * 3) Add a Table of contents on the top for users who have enabled the option
3991 * 4) Auto-anchor headings
3993 * It loops through all headlines, collects the necessary data, then splits up the
3994 * string and re-inserts the newly formatted headlines.
3996 * @param $text String
3997 * @param $origText String: original, untouched wikitext
3998 * @param $isMain Boolean
3999 * @return mixed|string
4002 function formatHeadings( $text, $origText, $isMain=true ) {
4003 global $wgMaxTocLevel, $wgHtml5, $wgExperimentalHtmlIds;
4005 # Inhibit editsection links if requested in the page
4006 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
4007 $maybeShowEditLink = $showEditLink = false;
4009 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
4010 $showEditLink = $this->mOptions
->getEditSection();
4012 if ( $showEditLink ) {
4013 $this->mOutput
->setEditSectionTokens( true );
4016 # Get all headlines for numbering them and adding funky stuff like [edit]
4017 # links - this is for later, but we need the number of headlines right now
4019 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
4021 # if there are fewer than 4 headlines in the article, do not show TOC
4022 # unless it's been explicitly enabled.
4023 $enoughToc = $this->mShowToc
&&
4024 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
4026 # Allow user to stipulate that a page should have a "new section"
4027 # link added via __NEWSECTIONLINK__
4028 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
4029 $this->mOutput
->setNewSection( true );
4032 # Allow user to remove the "new section"
4033 # link via __NONEWSECTIONLINK__
4034 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
4035 $this->mOutput
->hideNewSection( true );
4038 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4039 # override above conditions and always show TOC above first header
4040 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4041 $this->mShowToc
= true;
4049 # Ugh .. the TOC should have neat indentation levels which can be
4050 # passed to the skin functions. These are determined here
4054 $sublevelCount = array();
4055 $levelCount = array();
4060 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4061 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4062 $oldType = $this->mOutputType
;
4063 $this->setOutputType( self
::OT_WIKI
);
4064 $frame = $this->getPreprocessor()->newFrame();
4065 $root = $this->preprocessToDom( $origText );
4066 $node = $root->getFirstChild();
4071 foreach ( $matches[3] as $headline ) {
4072 $isTemplate = false;
4074 $sectionIndex = false;
4076 $markerMatches = array();
4077 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
4078 $serial = $markerMatches[1];
4079 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4080 $isTemplate = ( $titleText != $baseTitleText );
4081 $headline = preg_replace( "/^$markerRegex/", "", $headline );
4085 $prevlevel = $level;
4087 $level = $matches[1][$headlineCount];
4089 if ( $level > $prevlevel ) {
4090 # Increase TOC level
4092 $sublevelCount[$toclevel] = 0;
4093 if ( $toclevel<$wgMaxTocLevel ) {
4094 $prevtoclevel = $toclevel;
4095 $toc .= Linker
::tocIndent();
4098 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4099 # Decrease TOC level, find level to jump to
4101 for ( $i = $toclevel; $i > 0; $i-- ) {
4102 if ( $levelCount[$i] == $level ) {
4103 # Found last matching level
4106 } elseif ( $levelCount[$i] < $level ) {
4107 # Found first matching level below current level
4115 if ( $toclevel<$wgMaxTocLevel ) {
4116 if ( $prevtoclevel < $wgMaxTocLevel ) {
4117 # Unindent only if the previous toc level was shown :p
4118 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4119 $prevtoclevel = $toclevel;
4121 $toc .= Linker
::tocLineEnd();
4125 # No change in level, end TOC line
4126 if ( $toclevel<$wgMaxTocLevel ) {
4127 $toc .= Linker
::tocLineEnd();
4131 $levelCount[$toclevel] = $level;
4133 # count number of headlines for each level
4134 @$sublevelCount[$toclevel]++
;
4136 for( $i = 1; $i <= $toclevel; $i++
) {
4137 if ( !empty( $sublevelCount[$i] ) ) {
4141 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4146 # The safe header is a version of the header text safe to use for links
4148 # Remove link placeholders by the link text.
4149 # <!--LINK number-->
4151 # link text with suffix
4152 # Do this before unstrip since link text can contain strip markers
4153 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4155 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4156 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4158 # Strip out HTML (first regex removes any tag not allowed)
4159 # Allowed tags are <sup> and <sub> (bug 8393), <i> (bug 26375) and <b> (r105284)
4160 # We strip any parameter from accepted tags (second regex)
4161 $tocline = preg_replace(
4162 array( '#<(?!/?(sup|sub|i|b)(?: [^>]*)?>).*?'.'>#', '#<(/?(sup|sub|i|b))(?: .*?)?'.'>#' ),
4163 array( '', '<$1>' ),
4166 $tocline = trim( $tocline );
4168 # For the anchor, strip out HTML-y stuff period
4169 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
4170 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4172 # Save headline for section edit hint before it's escaped
4173 $headlineHint = $safeHeadline;
4175 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
4176 # For reverse compatibility, provide an id that's
4177 # HTML4-compatible, like we used to.
4179 # It may be worth noting, academically, that it's possible for
4180 # the legacy anchor to conflict with a non-legacy headline
4181 # anchor on the page. In this case likely the "correct" thing
4182 # would be to either drop the legacy anchors or make sure
4183 # they're numbered first. However, this would require people
4184 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4185 # manually, so let's not bother worrying about it.
4186 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4187 array( 'noninitial', 'legacy' ) );
4188 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4190 if ( $legacyHeadline == $safeHeadline ) {
4191 # No reason to have both (in fact, we can't)
4192 $legacyHeadline = false;
4195 $legacyHeadline = false;
4196 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4200 # HTML names must be case-insensitively unique (bug 10721).
4201 # This does not apply to Unicode characters per
4202 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4203 # @todo FIXME: We may be changing them depending on the current locale.
4204 $arrayKey = strtolower( $safeHeadline );
4205 if ( $legacyHeadline === false ) {
4206 $legacyArrayKey = false;
4208 $legacyArrayKey = strtolower( $legacyHeadline );
4211 # count how many in assoc. array so we can track dupes in anchors
4212 if ( isset( $refers[$arrayKey] ) ) {
4213 $refers[$arrayKey]++
;
4215 $refers[$arrayKey] = 1;
4217 if ( isset( $refers[$legacyArrayKey] ) ) {
4218 $refers[$legacyArrayKey]++
;
4220 $refers[$legacyArrayKey] = 1;
4223 # Don't number the heading if it is the only one (looks silly)
4224 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4225 # the two are different if the line contains a link
4226 $headline = Html
::element( 'span', array( 'class' => 'mw-headline-number' ), $numbering ) . ' ' . $headline;
4229 # Create the anchor for linking from the TOC to the section
4230 $anchor = $safeHeadline;
4231 $legacyAnchor = $legacyHeadline;
4232 if ( $refers[$arrayKey] > 1 ) {
4233 $anchor .= '_' . $refers[$arrayKey];
4235 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4236 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4238 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4239 $toc .= Linker
::tocLine( $anchor, $tocline,
4240 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4243 # Add the section to the section tree
4244 # Find the DOM node for this header
4245 while ( $node && !$isTemplate ) {
4246 if ( $node->getName() === 'h' ) {
4247 $bits = $node->splitHeading();
4248 if ( $bits['i'] == $sectionIndex ) {
4252 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4253 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4254 $node = $node->getNextSibling();
4257 'toclevel' => $toclevel,
4260 'number' => $numbering,
4261 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4262 'fromtitle' => $titleText,
4263 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
4264 'anchor' => $anchor,
4267 # give headline the correct <h#> tag
4268 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4269 // Output edit section links as markers with styles that can be customized by skins
4270 if ( $isTemplate ) {
4271 # Put a T flag in the section identifier, to indicate to extractSections()
4272 # that sections inside <includeonly> should be counted.
4273 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4275 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
4277 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4278 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4279 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4280 // so we don't have to worry about a user trying to input one of these markers directly.
4281 // We use a page and section attribute to stop the language converter from converting these important bits
4282 // of data, but put the headline hint inside a content block because the language converter is supposed to
4283 // be able to convert that piece of data.
4284 $editlink = '<mw:editsection page="' . htmlspecialchars($editlinkArgs[0]);
4285 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"';
4286 if ( isset($editlinkArgs[2]) ) {
4287 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4294 $head[$headlineCount] = Linker
::makeHeadline( $level,
4295 $matches['attrib'][$headlineCount], $anchor, $headline,
4296 $editlink, $legacyAnchor );
4301 $this->setOutputType( $oldType );
4303 # Never ever show TOC if no headers
4304 if ( $numVisible < 1 ) {
4309 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4310 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4312 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4313 $this->mOutput
->setTOCHTML( $toc );
4317 $this->mOutput
->setSections( $tocraw );
4320 # split up and insert constructed headlines
4321 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4324 // build an array of document sections
4325 $sections = array();
4326 foreach ( $blocks as $block ) {
4327 // $head is zero-based, sections aren't.
4328 if ( empty( $head[$i - 1] ) ) {
4329 $sections[$i] = $block;
4331 $sections[$i] = $head[$i - 1] . $block;
4335 * Send a hook, one per section.
4336 * The idea here is to be able to make section-level DIVs, but to do so in a
4337 * lower-impact, more correct way than r50769
4340 * $section : the section number
4341 * &$sectionContent : ref to the content of the section
4342 * $showEditLinks : boolean describing whether this section has an edit link
4344 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4349 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4350 // append the TOC at the beginning
4351 // Top anchor now in skin
4352 $sections[0] = $sections[0] . $toc . "\n";
4355 $full .= join( '', $sections );
4357 if ( $this->mForceTocPosition
) {
4358 return str_replace( '<!--MWTOC-->', $toc, $full );
4365 * Transform wiki markup when saving a page by doing "\r\n" -> "\n"
4366 * conversion, substitting signatures, {{subst:}} templates, etc.
4368 * @param $text String: the text to transform
4369 * @param $title Title: the Title object for the current article
4370 * @param $user User: the User object describing the current user
4371 * @param $options ParserOptions: parsing options
4372 * @param $clearState Boolean: whether to clear the parser state first
4373 * @return String: the altered wiki markup
4375 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4376 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4377 $this->setUser( $user );
4382 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4383 if( $options->getPreSaveTransform() ) {
4384 $text = $this->pstPass2( $text, $user );
4386 $text = $this->mStripState
->unstripBoth( $text );
4388 $this->setUser( null ); #Reset
4394 * Pre-save transform helper function
4397 * @param $text string
4402 function pstPass2( $text, $user ) {
4403 global $wgContLang, $wgLocaltimezone;
4405 # Note: This is the timestamp saved as hardcoded wikitext to
4406 # the database, we use $wgContLang here in order to give
4407 # everyone the same signature and use the default one rather
4408 # than the one selected in each user's preferences.
4409 # (see also bug 12815)
4410 $ts = $this->mOptions
->getTimestamp();
4411 if ( isset( $wgLocaltimezone ) ) {
4412 $tz = $wgLocaltimezone;
4414 $tz = date_default_timezone_get();
4417 $unixts = wfTimestamp( TS_UNIX
, $ts );
4418 $oldtz = date_default_timezone_get();
4419 date_default_timezone_set( $tz );
4420 $ts = date( 'YmdHis', $unixts );
4421 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4423 # Allow translation of timezones through wiki. date() can return
4424 # whatever crap the system uses, localised or not, so we cannot
4425 # ship premade translations.
4426 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4427 $msg = wfMessage( $key )->inContentLanguage();
4428 if ( $msg->exists() ) {
4429 $tzMsg = $msg->text();
4432 date_default_timezone_set( $oldtz );
4434 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4436 # Variable replacement
4437 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4438 $text = $this->replaceVariables( $text );
4440 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4441 # which may corrupt this parser instance via its wfMessage()->text() call-
4444 $sigText = $this->getUserSig( $user );
4445 $text = strtr( $text, array(
4447 '~~~~' => "$sigText $d",
4451 # Context links: [[|name]] and [[name (context)|]]
4452 $tc = '[' . Title
::legalChars() . ']';
4453 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4455 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4456 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]]
4457 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/"; # [[ns:page (context), context|]]
4458 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4460 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4461 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4462 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4463 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4465 $t = $this->mTitle
->getText();
4467 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4468 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4469 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4470 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4472 # if there's no context, don't bother duplicating the title
4473 $text = preg_replace( $p2, '[[\\1]]', $text );
4476 # Trim trailing whitespace
4477 $text = rtrim( $text );
4483 * Fetch the user's signature text, if any, and normalize to
4484 * validated, ready-to-insert wikitext.
4485 * If you have pre-fetched the nickname or the fancySig option, you can
4486 * specify them here to save a database query.
4487 * Do not reuse this parser instance after calling getUserSig(),
4488 * as it may have changed if it's the $wgParser.
4491 * @param $nickname String|bool nickname to use or false to use user's default nickname
4492 * @param $fancySig Boolean|null whether the nicknname is the complete signature
4493 * or null to use default value
4496 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4497 global $wgMaxSigChars;
4499 $username = $user->getName();
4501 # If not given, retrieve from the user object.
4502 if ( $nickname === false )
4503 $nickname = $user->getOption( 'nickname' );
4505 if ( is_null( $fancySig ) ) {
4506 $fancySig = $user->getBoolOption( 'fancysig' );
4509 $nickname = $nickname == null ?
$username : $nickname;
4511 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4512 $nickname = $username;
4513 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4514 } elseif ( $fancySig !== false ) {
4515 # Sig. might contain markup; validate this
4516 if ( $this->validateSig( $nickname ) !== false ) {
4517 # Validated; clean up (if needed) and return it
4518 return $this->cleanSig( $nickname, true );
4520 # Failed to validate; fall back to the default
4521 $nickname = $username;
4522 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4526 # Make sure nickname doesnt get a sig in a sig
4527 $nickname = self
::cleanSigInSig( $nickname );
4529 # If we're still here, make it a link to the user page
4530 $userText = wfEscapeWikiText( $username );
4531 $nickText = wfEscapeWikiText( $nickname );
4532 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4534 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4538 * Check that the user's signature contains no bad XML
4540 * @param $text String
4541 * @return mixed An expanded string, or false if invalid.
4543 function validateSig( $text ) {
4544 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4548 * Clean up signature text
4550 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4551 * 2) Substitute all transclusions
4553 * @param $text String
4554 * @param $parsing bool Whether we're cleaning (preferences save) or parsing
4555 * @return String: signature text
4557 public function cleanSig( $text, $parsing = false ) {
4560 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4563 # Option to disable this feature
4564 if ( !$this->mOptions
->getCleanSignatures() ) {
4568 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4569 # => Move this logic to braceSubstitution()
4570 $substWord = MagicWord
::get( 'subst' );
4571 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4572 $substText = '{{' . $substWord->getSynonym( 0 );
4574 $text = preg_replace( $substRegex, $substText, $text );
4575 $text = self
::cleanSigInSig( $text );
4576 $dom = $this->preprocessToDom( $text );
4577 $frame = $this->getPreprocessor()->newFrame();
4578 $text = $frame->expand( $dom );
4581 $text = $this->mStripState
->unstripBoth( $text );
4588 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4590 * @param $text String
4591 * @return String: signature text with /~{3,5}/ removed
4593 public static function cleanSigInSig( $text ) {
4594 $text = preg_replace( '/~{3,5}/', '', $text );
4599 * Set up some variables which are usually set up in parse()
4600 * so that an external function can call some class members with confidence
4602 * @param $title Title|null
4603 * @param $options ParserOptions
4604 * @param $outputType
4605 * @param $clearState bool
4607 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4608 $this->startParse( $title, $options, $outputType, $clearState );
4612 * @param $title Title|null
4613 * @param $options ParserOptions
4614 * @param $outputType
4615 * @param $clearState bool
4617 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4618 $this->setTitle( $title );
4619 $this->mOptions
= $options;
4620 $this->setOutputType( $outputType );
4621 if ( $clearState ) {
4622 $this->clearState();
4627 * Wrapper for preprocess()
4629 * @param $text String: the text to preprocess
4630 * @param $options ParserOptions: options
4631 * @param $title Title object or null to use $wgTitle
4634 public function transformMsg( $text, $options, $title = null ) {
4635 static $executing = false;
4637 # Guard against infinite recursion
4643 wfProfileIn( __METHOD__
);
4649 # It's not uncommon having a null $wgTitle in scripts. See r80898
4650 # Create a ghost title in such case
4651 $title = Title
::newFromText( 'Dwimmerlaik' );
4653 $text = $this->preprocess( $text, $title, $options );
4656 wfProfileOut( __METHOD__
);
4661 * Create an HTML-style tag, e.g. "<yourtag>special text</yourtag>"
4662 * The callback should have the following form:
4663 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4665 * Transform and return $text. Use $parser for any required context, e.g. use
4666 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4668 * Hooks may return extended information by returning an array, of which the
4669 * first numbered element (index 0) must be the return string, and all other
4670 * entries are extracted into local variables within an internal function
4671 * in the Parser class.
4673 * This interface (introduced r61913) appears to be undocumented, but
4674 * 'markerName' is used by some core tag hooks to override which strip
4675 * array their results are placed in. **Use great caution if attempting
4676 * this interface, as it is not documented and injudicious use could smash
4677 * private variables.**
4679 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4680 * @param $callback Mixed: the callback function (and object) to use for the tag
4681 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4683 public function setHook( $tag, $callback ) {
4684 $tag = strtolower( $tag );
4685 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4686 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4688 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4689 $this->mTagHooks
[$tag] = $callback;
4690 if ( !in_array( $tag, $this->mStripList
) ) {
4691 $this->mStripList
[] = $tag;
4698 * As setHook(), but letting the contents be parsed.
4700 * Transparent tag hooks are like regular XML-style tag hooks, except they
4701 * operate late in the transformation sequence, on HTML instead of wikitext.
4703 * This is probably obsoleted by things dealing with parser frames?
4704 * The only extension currently using it is geoserver.
4707 * @todo better document or deprecate this
4709 * @param $tag Mixed: the tag to use, e.g. 'hook' for "<hook>"
4710 * @param $callback Mixed: the callback function (and object) to use for the tag
4711 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4713 function setTransparentTagHook( $tag, $callback ) {
4714 $tag = strtolower( $tag );
4715 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4716 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4718 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4719 $this->mTransparentTagHooks
[$tag] = $callback;
4725 * Remove all tag hooks
4727 function clearTagHooks() {
4728 $this->mTagHooks
= array();
4729 $this->mFunctionTagHooks
= array();
4730 $this->mStripList
= $this->mDefaultStripList
;
4734 * Create a function, e.g. {{sum:1|2|3}}
4735 * The callback function should have the form:
4736 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4738 * Or with SFH_OBJECT_ARGS:
4739 * function myParserFunction( $parser, $frame, $args ) { ... }
4741 * The callback may either return the text result of the function, or an array with the text
4742 * in element 0, and a number of flags in the other elements. The names of the flags are
4743 * specified in the keys. Valid flags are:
4744 * found The text returned is valid, stop processing the template. This
4746 * nowiki Wiki markup in the return value should be escaped
4747 * isHTML The returned text is HTML, armour it against wikitext transformation
4749 * @param $id String: The magic word ID
4750 * @param $callback Mixed: the callback function (and object) to use
4751 * @param $flags Integer: a combination of the following flags:
4752 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4754 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4755 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4756 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4757 * the arguments, and to control the way they are expanded.
4759 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4760 * arguments, for instance:
4761 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4763 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4764 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4765 * working if/when this is changed.
4767 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4770 * Please read the documentation in includes/parser/Preprocessor.php for more information
4771 * about the methods available in PPFrame and PPNode.
4773 * @return string|callback The old callback function for this name, if any
4775 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4778 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4779 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4781 # Add to function cache
4782 $mw = MagicWord
::get( $id );
4784 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4786 $synonyms = $mw->getSynonyms();
4787 $sensitive = intval( $mw->isCaseSensitive() );
4789 foreach ( $synonyms as $syn ) {
4791 if ( !$sensitive ) {
4792 $syn = $wgContLang->lc( $syn );
4795 if ( !( $flags & SFH_NO_HASH
) ) {
4798 # Remove trailing colon
4799 if ( substr( $syn, -1, 1 ) === ':' ) {
4800 $syn = substr( $syn, 0, -1 );
4802 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4808 * Get all registered function hook identifiers
4812 function getFunctionHooks() {
4813 return array_keys( $this->mFunctionHooks
);
4817 * Create a tag function, e.g. "<test>some stuff</test>".
4818 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4819 * Unlike parser functions, their content is not preprocessed.
4822 function setFunctionTagHook( $tag, $callback, $flags ) {
4823 $tag = strtolower( $tag );
4824 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4825 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4826 $this->mFunctionTagHooks
[$tag] : null;
4827 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4829 if ( !in_array( $tag, $this->mStripList
) ) {
4830 $this->mStripList
[] = $tag;
4837 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
4838 * Replace "<!--LINK-->" link placeholders with actual links, in the buffer
4839 * Placeholders created in Skin::makeLinkObj()
4841 * @param $text string
4842 * @param $options int
4844 * @return array of link CSS classes, indexed by PDBK.
4846 function replaceLinkHolders( &$text, $options = 0 ) {
4847 return $this->mLinkHolders
->replace( $text );
4851 * Replace "<!--LINK-->" link placeholders with plain text of links
4852 * (not HTML-formatted).
4854 * @param $text String
4857 function replaceLinkHoldersText( $text ) {
4858 return $this->mLinkHolders
->replaceText( $text );
4862 * Renders an image gallery from a text with one line per image.
4863 * text labels may be given by using |-style alternative text. E.g.
4864 * Image:one.jpg|The number "1"
4865 * Image:tree.jpg|A tree
4866 * given as text will return the HTML of a gallery with two images,
4867 * labeled 'The number "1"' and
4870 * @param string $text
4871 * @param array $params
4872 * @return string HTML
4874 function renderImageGallery( $text, $params ) {
4875 $ig = new ImageGallery();
4876 $ig->setContextTitle( $this->mTitle
);
4877 $ig->setShowBytes( false );
4878 $ig->setShowFilename( false );
4879 $ig->setParser( $this );
4880 $ig->setHideBadImages();
4881 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4883 if ( isset( $params['showfilename'] ) ) {
4884 $ig->setShowFilename( true );
4886 $ig->setShowFilename( false );
4888 if ( isset( $params['caption'] ) ) {
4889 $caption = $params['caption'];
4890 $caption = htmlspecialchars( $caption );
4891 $caption = $this->replaceInternalLinks( $caption );
4892 $ig->setCaptionHtml( $caption );
4894 if ( isset( $params['perrow'] ) ) {
4895 $ig->setPerRow( $params['perrow'] );
4897 if ( isset( $params['widths'] ) ) {
4898 $ig->setWidths( $params['widths'] );
4900 if ( isset( $params['heights'] ) ) {
4901 $ig->setHeights( $params['heights'] );
4904 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4906 $lines = StringUtils
::explode( "\n", $text );
4907 foreach ( $lines as $line ) {
4908 # match lines like these:
4909 # Image:someimage.jpg|This is some image
4911 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4913 if ( count( $matches ) == 0 ) {
4917 if ( strpos( $matches[0], '%' ) !== false ) {
4918 $matches[1] = rawurldecode( $matches[1] );
4920 $title = Title
::newFromText( $matches[1], NS_FILE
);
4921 if ( is_null( $title ) ) {
4922 # Bogus title. Ignore these so we don't bomb out later.
4929 if ( isset( $matches[3] ) ) {
4930 // look for an |alt= definition while trying not to break existing
4931 // captions with multiple pipes (|) in it, until a more sensible grammar
4932 // is defined for images in galleries
4934 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
4935 $parameterMatches = StringUtils
::explode('|', $matches[3]);
4936 $magicWordAlt = MagicWord
::get( 'img_alt' );
4937 $magicWordLink = MagicWord
::get( 'img_link' );
4939 foreach ( $parameterMatches as $parameterMatch ) {
4940 if ( $match = $magicWordAlt->matchVariableStartToEnd( $parameterMatch ) ) {
4941 $alt = $this->stripAltText( $match, false );
4943 elseif( $match = $magicWordLink->matchVariableStartToEnd( $parameterMatch ) ){
4944 $link = strip_tags($this->replaceLinkHoldersText($match));
4945 $chars = self
::EXT_LINK_URL_CLASS
;
4946 $prots = $this->mUrlProtocols
;
4947 //check to see if link matches an absolute url, if not then it must be a wiki link.
4948 if(!preg_match( "/^($prots)$chars+$/u", $link)){
4949 $localLinkTitle = Title
::newFromText($link);
4950 $link = $localLinkTitle->getLocalURL();
4954 // concatenate all other pipes
4955 $label .= '|' . $parameterMatch;
4958 // remove the first pipe
4959 $label = substr( $label, 1 );
4962 $ig->add( $title, $label, $alt ,$link);
4964 return $ig->toHTML();
4971 function getImageParams( $handler ) {
4973 $handlerClass = get_class( $handler );
4977 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4978 # Initialise static lists
4979 static $internalParamNames = array(
4980 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4981 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4982 'bottom', 'text-bottom' ),
4983 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4984 'upright', 'border', 'link', 'alt', 'class' ),
4986 static $internalParamMap;
4987 if ( !$internalParamMap ) {
4988 $internalParamMap = array();
4989 foreach ( $internalParamNames as $type => $names ) {
4990 foreach ( $names as $name ) {
4991 $magicName = str_replace( '-', '_', "img_$name" );
4992 $internalParamMap[$magicName] = array( $type, $name );
4997 # Add handler params
4998 $paramMap = $internalParamMap;
5000 $handlerParamMap = $handler->getParamMap();
5001 foreach ( $handlerParamMap as $magic => $paramName ) {
5002 $paramMap[$magic] = array( 'handler', $paramName );
5005 $this->mImageParams
[$handlerClass] = $paramMap;
5006 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
5008 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
5012 * Parse image options text and use it to make an image
5014 * @param $title Title
5015 * @param $options String
5016 * @param $holders LinkHolderArray|bool
5017 * @return string HTML
5019 function makeImage( $title, $options, $holders = false ) {
5020 # Check if the options text is of the form "options|alt text"
5022 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
5023 # * left no resizing, just left align. label is used for alt= only
5024 # * right same, but right aligned
5025 # * none same, but not aligned
5026 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
5027 # * center center the image
5028 # * frame Keep original image size, no magnify-button.
5029 # * framed Same as "frame"
5030 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
5031 # * upright reduce width for upright images, rounded to full __0 px
5032 # * border draw a 1px border around the image
5033 # * alt Text for HTML alt attribute (defaults to empty)
5034 # * class Set a class for img node
5035 # * link Set the target of the image link. Can be external, interwiki, or local
5036 # vertical-align values (no % or length right now):
5046 $parts = StringUtils
::explode( "|", $options );
5048 # Give extensions a chance to select the file revision for us
5051 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5052 array( $this, $title, &$options, &$descQuery ) );
5053 # Fetch and register the file (file title may be different via hooks)
5054 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5057 $handler = $file ?
$file->getHandler() : false;
5059 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5062 $this->addTrackingCategory( 'broken-file-category' );
5065 # Process the input parameters
5067 $params = array( 'frame' => array(), 'handler' => array(),
5068 'horizAlign' => array(), 'vertAlign' => array() );
5069 foreach ( $parts as $part ) {
5070 $part = trim( $part );
5071 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5073 if ( isset( $paramMap[$magicName] ) ) {
5074 list( $type, $paramName ) = $paramMap[$magicName];
5076 # Special case; width and height come in one variable together
5077 if ( $type === 'handler' && $paramName === 'width' ) {
5078 $parsedWidthParam = $this->parseWidthParam( $value );
5079 if( isset( $parsedWidthParam['width'] ) ) {
5080 $width = $parsedWidthParam['width'];
5081 if ( $handler->validateParam( 'width', $width ) ) {
5082 $params[$type]['width'] = $width;
5086 if( isset( $parsedWidthParam['height'] ) ) {
5087 $height = $parsedWidthParam['height'];
5088 if ( $handler->validateParam( 'height', $height ) ) {
5089 $params[$type]['height'] = $height;
5093 # else no validation -- bug 13436
5095 if ( $type === 'handler' ) {
5096 # Validate handler parameter
5097 $validated = $handler->validateParam( $paramName, $value );
5099 # Validate internal parameters
5100 switch( $paramName ) {
5104 # @todo FIXME: Possibly check validity here for
5105 # manualthumb? downstream behavior seems odd with
5106 # missing manual thumbs.
5108 $value = $this->stripAltText( $value, $holders );
5111 $chars = self
::EXT_LINK_URL_CLASS
;
5112 $prots = $this->mUrlProtocols
;
5113 if ( $value === '' ) {
5114 $paramName = 'no-link';
5117 } elseif ( preg_match( "/^(?i)$prots/", $value ) ) {
5118 if ( preg_match( "/^((?i)$prots)$chars+$/u", $value, $m ) ) {
5119 $paramName = 'link-url';
5120 $this->mOutput
->addExternalLink( $value );
5121 if ( $this->mOptions
->getExternalLinkTarget() ) {
5122 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5127 $linkTitle = Title
::newFromText( $value );
5129 $paramName = 'link-title';
5130 $value = $linkTitle;
5131 $this->mOutput
->addLink( $linkTitle );
5137 # Most other things appear to be empty or numeric...
5138 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5143 $params[$type][$paramName] = $value;
5147 if ( !$validated ) {
5152 # Process alignment parameters
5153 if ( $params['horizAlign'] ) {
5154 $params['frame']['align'] = key( $params['horizAlign'] );
5156 if ( $params['vertAlign'] ) {
5157 $params['frame']['valign'] = key( $params['vertAlign'] );
5160 $params['frame']['caption'] = $caption;
5162 # Will the image be presented in a frame, with the caption below?
5163 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5164 isset( $params['frame']['framed'] ) ||
5165 isset( $params['frame']['thumbnail'] ) ||
5166 isset( $params['frame']['manualthumb'] );
5168 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5169 # came to also set the caption, ordinary text after the image -- which
5170 # makes no sense, because that just repeats the text multiple times in
5171 # screen readers. It *also* came to set the title attribute.
5173 # Now that we have an alt attribute, we should not set the alt text to
5174 # equal the caption: that's worse than useless, it just repeats the
5175 # text. This is the framed/thumbnail case. If there's no caption, we
5176 # use the unnamed parameter for alt text as well, just for the time be-
5177 # ing, if the unnamed param is set and the alt param is not.
5179 # For the future, we need to figure out if we want to tweak this more,
5180 # e.g., introducing a title= parameter for the title; ignoring the un-
5181 # named parameter entirely for images without a caption; adding an ex-
5182 # plicit caption= parameter and preserving the old magic unnamed para-
5184 if ( $imageIsFramed ) { # Framed image
5185 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5186 # No caption or alt text, add the filename as the alt text so
5187 # that screen readers at least get some description of the image
5188 $params['frame']['alt'] = $title->getText();
5190 # Do not set $params['frame']['title'] because tooltips don't make sense
5192 } else { # Inline image
5193 if ( !isset( $params['frame']['alt'] ) ) {
5194 # No alt text, use the "caption" for the alt text
5195 if ( $caption !== '') {
5196 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5198 # No caption, fall back to using the filename for the
5200 $params['frame']['alt'] = $title->getText();
5203 # Use the "caption" for the tooltip text
5204 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5207 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5209 # Linker does the rest
5210 $time = isset( $options['time'] ) ?
$options['time'] : false;
5211 $ret = Linker
::makeImageLink( $this, $title, $file, $params['frame'], $params['handler'],
5212 $time, $descQuery, $this->mOptions
->getThumbSize() );
5214 # Give the handler a chance to modify the parser object
5216 $handler->parserTransformHook( $this, $file );
5224 * @param $holders LinkHolderArray
5225 * @return mixed|String
5227 protected function stripAltText( $caption, $holders ) {
5228 # Strip bad stuff out of the title (tooltip). We can't just use
5229 # replaceLinkHoldersText() here, because if this function is called
5230 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5232 $tooltip = $holders->replaceText( $caption );
5234 $tooltip = $this->replaceLinkHoldersText( $caption );
5237 # make sure there are no placeholders in thumbnail attributes
5238 # that are later expanded to html- so expand them now and
5240 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5241 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5247 * Set a flag in the output object indicating that the content is dynamic and
5248 * shouldn't be cached.
5250 function disableCache() {
5251 wfDebug( "Parser output marked as uncacheable.\n" );
5252 if ( !$this->mOutput
) {
5253 throw new MWException( __METHOD__
.
5254 " can only be called when actually parsing something" );
5256 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5257 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5261 * Callback from the Sanitizer for expanding items found in HTML attribute
5262 * values, so they can be safely tested and escaped.
5264 * @param $text String
5265 * @param $frame PPFrame
5268 function attributeStripCallback( &$text, $frame = false ) {
5269 $text = $this->replaceVariables( $text, $frame );
5270 $text = $this->mStripState
->unstripBoth( $text );
5279 function getTags() {
5280 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
), array_keys( $this->mFunctionTagHooks
) );
5284 * Replace transparent tags in $text with the values given by the callbacks.
5286 * Transparent tag hooks are like regular XML-style tag hooks, except they
5287 * operate late in the transformation sequence, on HTML instead of wikitext.
5289 * @param $text string
5293 function replaceTransparentTags( $text ) {
5295 $elements = array_keys( $this->mTransparentTagHooks
);
5296 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5297 $replacements = array();
5299 foreach ( $matches as $marker => $data ) {
5300 list( $element, $content, $params, $tag ) = $data;
5301 $tagName = strtolower( $element );
5302 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5303 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
5307 $replacements[$marker] = $output;
5309 return strtr( $text, $replacements );
5313 * Break wikitext input into sections, and either pull or replace
5314 * some particular section's text.
5316 * External callers should use the getSection and replaceSection methods.
5318 * @param $text String: Page wikitext
5319 * @param $section String: a section identifier string of the form:
5320 * "<flag1> - <flag2> - ... - <section number>"
5322 * Currently the only recognised flag is "T", which means the target section number
5323 * was derived during a template inclusion parse, in other words this is a template
5324 * section edit link. If no flags are given, it was an ordinary section edit link.
5325 * This flag is required to avoid a section numbering mismatch when a section is
5326 * enclosed by "<includeonly>" (bug 6563).
5328 * The section number 0 pulls the text before the first heading; other numbers will
5329 * pull the given section along with its lower-level subsections. If the section is
5330 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5332 * Section 0 is always considered to exist, even if it only contains the empty
5333 * string. If $text is the empty string and section 0 is replaced, $newText is
5336 * @param $mode String: one of "get" or "replace"
5337 * @param $newText String: replacement text for section data.
5338 * @return String: for "get", the extracted section text.
5339 * for "replace", the whole page with the section replaced.
5341 private function extractSections( $text, $section, $mode, $newText='' ) {
5342 global $wgTitle; # not generally used but removes an ugly failure mode
5343 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5345 $frame = $this->getPreprocessor()->newFrame();
5347 # Process section extraction flags
5349 $sectionParts = explode( '-', $section );
5350 $sectionIndex = array_pop( $sectionParts );
5351 foreach ( $sectionParts as $part ) {
5352 if ( $part === 'T' ) {
5353 $flags |
= self
::PTD_FOR_INCLUSION
;
5357 # Check for empty input
5358 if ( strval( $text ) === '' ) {
5359 # Only sections 0 and T-0 exist in an empty document
5360 if ( $sectionIndex == 0 ) {
5361 if ( $mode === 'get' ) {
5367 if ( $mode === 'get' ) {
5375 # Preprocess the text
5376 $root = $this->preprocessToDom( $text, $flags );
5378 # <h> nodes indicate section breaks
5379 # They can only occur at the top level, so we can find them by iterating the root's children
5380 $node = $root->getFirstChild();
5382 # Find the target section
5383 if ( $sectionIndex == 0 ) {
5384 # Section zero doesn't nest, level=big
5385 $targetLevel = 1000;
5388 if ( $node->getName() === 'h' ) {
5389 $bits = $node->splitHeading();
5390 if ( $bits['i'] == $sectionIndex ) {
5391 $targetLevel = $bits['level'];
5395 if ( $mode === 'replace' ) {
5396 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5398 $node = $node->getNextSibling();
5404 if ( $mode === 'get' ) {
5411 # Find the end of the section, including nested sections
5413 if ( $node->getName() === 'h' ) {
5414 $bits = $node->splitHeading();
5415 $curLevel = $bits['level'];
5416 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5420 if ( $mode === 'get' ) {
5421 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5423 $node = $node->getNextSibling();
5426 # Write out the remainder (in replace mode only)
5427 if ( $mode === 'replace' ) {
5428 # Output the replacement text
5429 # Add two newlines on -- trailing whitespace in $newText is conventionally
5430 # stripped by the editor, so we need both newlines to restore the paragraph gap
5431 # Only add trailing whitespace if there is newText
5432 if ( $newText != "" ) {
5433 $outText .= $newText . "\n\n";
5437 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5438 $node = $node->getNextSibling();
5442 if ( is_string( $outText ) ) {
5443 # Re-insert stripped tags
5444 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5451 * This function returns the text of a section, specified by a number ($section).
5452 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5453 * the first section before any such heading (section 0).
5455 * If a section contains subsections, these are also returned.
5457 * @param $text String: text to look in
5458 * @param $section String: section identifier
5459 * @param $deftext String: default to return if section is not found
5460 * @return string text of the requested section
5462 public function getSection( $text, $section, $deftext='' ) {
5463 return $this->extractSections( $text, $section, "get", $deftext );
5467 * This function returns $oldtext after the content of the section
5468 * specified by $section has been replaced with $text. If the target
5469 * section does not exist, $oldtext is returned unchanged.
5471 * @param $oldtext String: former text of the article
5472 * @param $section int section identifier
5473 * @param $text String: replacing text
5474 * @return String: modified text
5476 public function replaceSection( $oldtext, $section, $text ) {
5477 return $this->extractSections( $oldtext, $section, "replace", $text );
5481 * Get the ID of the revision we are parsing
5483 * @return Mixed: integer or null
5485 function getRevisionId() {
5486 return $this->mRevisionId
;
5490 * Get the revision object for $this->mRevisionId
5492 * @return Revision|null either a Revision object or null
5494 protected function getRevisionObject() {
5495 if ( !is_null( $this->mRevisionObject
) ) {
5496 return $this->mRevisionObject
;
5498 if ( is_null( $this->mRevisionId
) ) {
5502 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5503 return $this->mRevisionObject
;
5507 * Get the timestamp associated with the current revision, adjusted for
5508 * the default server-local timestamp
5510 function getRevisionTimestamp() {
5511 if ( is_null( $this->mRevisionTimestamp
) ) {
5512 wfProfileIn( __METHOD__
);
5516 $revObject = $this->getRevisionObject();
5517 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5519 # The cryptic '' timezone parameter tells to use the site-default
5520 # timezone offset instead of the user settings.
5522 # Since this value will be saved into the parser cache, served
5523 # to other users, and potentially even used inside links and such,
5524 # it needs to be consistent for all visitors.
5525 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5527 wfProfileOut( __METHOD__
);
5529 return $this->mRevisionTimestamp
;
5533 * Get the name of the user that edited the last revision
5535 * @return String: user name
5537 function getRevisionUser() {
5538 if( is_null( $this->mRevisionUser
) ) {
5539 $revObject = $this->getRevisionObject();
5541 # if this template is subst: the revision id will be blank,
5542 # so just use the current user's name
5544 $this->mRevisionUser
= $revObject->getUserText();
5545 } elseif( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5546 $this->mRevisionUser
= $this->getUser()->getName();
5549 return $this->mRevisionUser
;
5553 * Mutator for $mDefaultSort
5555 * @param $sort string New value
5557 public function setDefaultSort( $sort ) {
5558 $this->mDefaultSort
= $sort;
5559 $this->mOutput
->setProperty( 'defaultsort', $sort );
5563 * Accessor for $mDefaultSort
5564 * Will use the empty string if none is set.
5566 * This value is treated as a prefix, so the
5567 * empty string is equivalent to sorting by
5572 public function getDefaultSort() {
5573 if ( $this->mDefaultSort
!== false ) {
5574 return $this->mDefaultSort
;
5581 * Accessor for $mDefaultSort
5582 * Unlike getDefaultSort(), will return false if none is set
5584 * @return string or false
5586 public function getCustomDefaultSort() {
5587 return $this->mDefaultSort
;
5591 * Try to guess the section anchor name based on a wikitext fragment
5592 * presumably extracted from a heading, for example "Header" from
5595 * @param $text string
5599 public function guessSectionNameFromWikiText( $text ) {
5600 # Strip out wikitext links(they break the anchor)
5601 $text = $this->stripSectionName( $text );
5602 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5603 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5607 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5608 * instead. For use in redirects, since IE6 interprets Redirect: headers
5609 * as something other than UTF-8 (apparently?), resulting in breakage.
5611 * @param $text String: The section name
5612 * @return string An anchor
5614 public function guessLegacySectionNameFromWikiText( $text ) {
5615 # Strip out wikitext links(they break the anchor)
5616 $text = $this->stripSectionName( $text );
5617 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5618 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5622 * Strips a text string of wikitext for use in a section anchor
5624 * Accepts a text string and then removes all wikitext from the
5625 * string and leaves only the resultant text (i.e. the result of
5626 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5627 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5628 * to create valid section anchors by mimicing the output of the
5629 * parser when headings are parsed.
5631 * @param $text String: text string to be stripped of wikitext
5632 * for use in a Section anchor
5633 * @return string Filtered text string
5635 public function stripSectionName( $text ) {
5636 # Strip internal link markup
5637 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5638 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5640 # Strip external link markup
5641 # @todo FIXME: Not tolerant to blank link text
5642 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5643 # on how many empty links there are on the page - need to figure that out.
5644 $text = preg_replace( '/\[(?i:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5646 # Parse wikitext quotes (italics & bold)
5647 $text = $this->doQuotes( $text );
5650 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5655 * strip/replaceVariables/unstrip for preprocessor regression testing
5657 * @param $text string
5658 * @param $title Title
5659 * @param $options ParserOptions
5660 * @param $outputType int
5664 function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5665 $this->startParse( $title, $options, $outputType, true );
5667 $text = $this->replaceVariables( $text );
5668 $text = $this->mStripState
->unstripBoth( $text );
5669 $text = Sanitizer
::removeHTMLtags( $text );
5674 * @param $text string
5675 * @param $title Title
5676 * @param $options ParserOptions
5679 function testPst( $text, Title
$title, ParserOptions
$options ) {
5680 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5685 * @param $title Title
5686 * @param $options ParserOptions
5689 function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5690 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5694 * Call a callback function on all regions of the given text that are not
5695 * inside strip markers, and replace those regions with the return value
5696 * of the callback. For example, with input:
5700 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5701 * two strings will be replaced with the value returned by the callback in
5709 function markerSkipCallback( $s, $callback ) {
5712 while ( $i < strlen( $s ) ) {
5713 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5714 if ( $markerStart === false ) {
5715 $out .= call_user_func( $callback, substr( $s, $i ) );
5718 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5719 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5720 if ( $markerEnd === false ) {
5721 $out .= substr( $s, $markerStart );
5724 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5725 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5734 * Remove any strip markers found in the given text.
5736 * @param $text Input string
5739 function killMarkers( $text ) {
5740 return $this->mStripState
->killMarkers( $text );
5744 * Save the parser state required to convert the given half-parsed text to
5745 * HTML. "Half-parsed" in this context means the output of
5746 * recursiveTagParse() or internalParse(). This output has strip markers
5747 * from replaceVariables (extensionSubstitution() etc.), and link
5748 * placeholders from replaceLinkHolders().
5750 * Returns an array which can be serialized and stored persistently. This
5751 * array can later be loaded into another parser instance with
5752 * unserializeHalfParsedText(). The text can then be safely incorporated into
5753 * the return value of a parser hook.
5755 * @param $text string
5759 function serializeHalfParsedText( $text ) {
5760 wfProfileIn( __METHOD__
);
5763 'version' => self
::HALF_PARSED_VERSION
,
5764 'stripState' => $this->mStripState
->getSubState( $text ),
5765 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
5767 wfProfileOut( __METHOD__
);
5772 * Load the parser state given in the $data array, which is assumed to
5773 * have been generated by serializeHalfParsedText(). The text contents is
5774 * extracted from the array, and its markers are transformed into markers
5775 * appropriate for the current Parser instance. This transformed text is
5776 * returned, and can be safely included in the return value of a parser
5779 * If the $data array has been stored persistently, the caller should first
5780 * check whether it is still valid, by calling isValidHalfParsedText().
5782 * @param $data array Serialized data
5785 function unserializeHalfParsedText( $data ) {
5786 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
5787 throw new MWException( __METHOD__
.': invalid version' );
5790 # First, extract the strip state.
5791 $texts = array( $data['text'] );
5792 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
5794 # Now renumber links
5795 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
5797 # Should be good to go.
5802 * Returns true if the given array, presumed to be generated by
5803 * serializeHalfParsedText(), is compatible with the current version of the
5806 * @param $data Array
5810 function isValidHalfParsedText( $data ) {
5811 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
5815 * Parsed a width param of imagelink like 300px or 200x300px
5817 * @param $value String
5822 public function parseWidthParam( $value ) {
5823 $parsedWidthParam = array();
5824 if( $value === '' ) {
5825 return $parsedWidthParam;
5828 # (bug 13500) In both cases (width/height and width only),
5829 # permit trailing "px" for backward compatibility.
5830 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
5831 $width = intval( $m[1] );
5832 $height = intval( $m[2] );
5833 $parsedWidthParam['width'] = $width;
5834 $parsedWidthParam['height'] = $height;
5835 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
5836 $width = intval( $value );
5837 $parsedWidthParam['width'] = $width;
5839 return $parsedWidthParam;