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).
35 * There are five main entry points into the Parser class:
37 * produces HTML output
39 * produces altered wiki markup.
41 * removes HTML comments and expands templates
42 * cleanSig() / cleanSigInSig()
43 * Cleans a signature before saving it to preferences
45 * Return the content of a section from an article for section editing
47 * Replaces a section by number inside an article
49 * Removes <noinclude> sections, and <includeonly> tags.
54 * NOT $wgUser or $wgTitle or $wgRequest or $wgLang. Keep them away!
57 * $wgUseDynamicDates*, $wgInterwikiMagic*,
58 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
59 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
62 * * only within ParserOptions
69 * Update this version number when the ParserOutput format
70 * changes in an incompatible way, so the parser cache
71 * can automatically discard old data.
73 const VERSION
= '1.6.4';
76 * Update this version number when the output of serialiseHalfParsedText()
77 * changes in an incompatible way
79 const HALF_PARSED_VERSION
= 2;
81 # Flags for Parser::setFunctionHook
82 # Also available as global constants from Defines.php
83 const SFH_NO_HASH
= 1;
84 const SFH_OBJECT_ARGS
= 2;
86 # Constants needed for external link processing
87 # Everything except bracket, space, or control characters
88 # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20
89 # as well as U+3000 is IDEOGRAPHIC SPACE for bug 19052
90 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F\p{Zs}]';
91 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F\p{Zs}]+)
92 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sxu';
94 # State constants for the definition list colon extraction
95 const COLON_STATE_TEXT
= 0;
96 const COLON_STATE_TAG
= 1;
97 const COLON_STATE_TAGSTART
= 2;
98 const COLON_STATE_CLOSETAG
= 3;
99 const COLON_STATE_TAGSLASH
= 4;
100 const COLON_STATE_COMMENT
= 5;
101 const COLON_STATE_COMMENTDASH
= 6;
102 const COLON_STATE_COMMENTDASHDASH
= 7;
104 # Flags for preprocessToDom
105 const PTD_FOR_INCLUSION
= 1;
107 # Allowed values for $this->mOutputType
108 # Parameter to startExternalParse().
109 const OT_HTML
= 1; # like parse()
110 const OT_WIKI
= 2; # like preSaveTransform()
111 const OT_PREPROCESS
= 3; # like preprocess()
113 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
115 # Marker Suffix needs to be accessible staticly.
116 const MARKER_SUFFIX
= "-QINU\x7f";
119 var $mTagHooks = array();
120 var $mTransparentTagHooks = array();
121 var $mFunctionHooks = array();
122 var $mFunctionSynonyms = array( 0 => array(), 1 => array() );
123 var $mFunctionTagHooks = array();
124 var $mStripList = array();
125 var $mDefaultStripList = array();
126 var $mVarCache = array();
127 var $mImageParams = array();
128 var $mImageParamsMagicArray = array();
129 var $mMarkerIndex = 0;
130 var $mFirstCall = true;
132 # Initialised by initialiseVariables()
135 * @var MagicWordArray
140 * @var MagicWordArray
143 var $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
145 # Cleared with clearState():
150 var $mAutonumber, $mDTopen;
157 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
159 * @var LinkHolderArray
164 var $mIncludeSizes, $mPPNodeCount, $mHighestExpansionDepth, $mDefaultSort;
165 var $mTplExpandCache; # empty-frame expansion cache
166 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
167 var $mExpensiveFunctionCount; # number of expensive parser function calls
168 var $mShowToc, $mForceTocPosition;
173 var $mUser; # User object; only used when doing pre-save transform
176 # These are variables reset at least once per parse regardless of $clearState
186 var $mTitle; # Title context, used for self-link rendering and similar things
187 var $mOutputType; # Output type, one of the OT_xxx constants
188 var $ot; # Shortcut alias, see setOutputType()
189 var $mRevisionObject; # The revision object of the specified revision ID
190 var $mRevisionId; # ID to display in {{REVISIONID}} tags
191 var $mRevisionTimestamp; # The timestamp of the specified revision ID
192 var $mRevisionUser; # User to display in {{REVISIONUSER}} tag
193 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp
205 public function __construct( $conf = array() ) {
206 $this->mConf
= $conf;
207 $this->mUrlProtocols
= wfUrlProtocols();
208 $this->mExtLinkBracketedRegex
= '/\[((' . $this->mUrlProtocols
. ')'.
209 self
::EXT_LINK_URL_CLASS
.'+)\p{Zs}*([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/Su';
210 if ( isset( $conf['preprocessorClass'] ) ) {
211 $this->mPreprocessorClass
= $conf['preprocessorClass'];
212 } elseif ( defined( 'MW_COMPILED' ) ) {
213 # Preprocessor_Hash is much faster than Preprocessor_DOM in compiled mode
214 $this->mPreprocessorClass
= 'Preprocessor_Hash';
215 } elseif ( extension_loaded( 'domxml' ) ) {
216 # PECL extension that conflicts with the core DOM extension (bug 13770)
217 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
218 $this->mPreprocessorClass
= 'Preprocessor_Hash';
219 } elseif ( extension_loaded( 'dom' ) ) {
220 $this->mPreprocessorClass
= 'Preprocessor_DOM';
222 $this->mPreprocessorClass
= 'Preprocessor_Hash';
224 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
228 * Reduce memory usage to reduce the impact of circular references
230 function __destruct() {
231 if ( isset( $this->mLinkHolders
) ) {
232 unset( $this->mLinkHolders
);
234 foreach ( $this as $name => $value ) {
235 unset( $this->$name );
240 * Do various kinds of initialisation on the first call of the parser
242 function firstCallInit() {
243 if ( !$this->mFirstCall
) {
246 $this->mFirstCall
= false;
248 wfProfileIn( __METHOD__
);
250 CoreParserFunctions
::register( $this );
251 CoreTagHooks
::register( $this );
252 $this->initialiseVariables();
254 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
255 wfProfileOut( __METHOD__
);
263 function clearState() {
264 wfProfileIn( __METHOD__
);
265 if ( $this->mFirstCall
) {
266 $this->firstCallInit();
268 $this->mOutput
= new ParserOutput
;
269 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
270 $this->mAutonumber
= 0;
271 $this->mLastSection
= '';
272 $this->mDTopen
= false;
273 $this->mIncludeCount
= array();
274 $this->mArgStack
= false;
275 $this->mInPre
= false;
276 $this->mLinkHolders
= new LinkHolderArray( $this );
278 $this->mRevisionObject
= $this->mRevisionTimestamp
=
279 $this->mRevisionId
= $this->mRevisionUser
= null;
280 $this->mVarCache
= array();
284 * Prefix for temporary replacement strings for the multipass parser.
285 * \x07 should never appear in input as it's disallowed in XML.
286 * Using it at the front also gives us a little extra robustness
287 * since it shouldn't match when butted up against identifier-like
290 * Must not consist of all title characters, or else it will change
291 * the behaviour of <nowiki> in a link.
293 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
294 $this->mStripState
= new StripState( $this->mUniqPrefix
);
297 # Clear these on every parse, bug 4549
298 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
300 $this->mShowToc
= true;
301 $this->mForceTocPosition
= false;
302 $this->mIncludeSizes
= array(
306 $this->mPPNodeCount
= 0;
307 $this->mHighestExpansionDepth
= 0;
308 $this->mDefaultSort
= false;
309 $this->mHeadings
= array();
310 $this->mDoubleUnderscores
= array();
311 $this->mExpensiveFunctionCount
= 0;
314 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
315 $this->mPreprocessor
= null;
318 wfRunHooks( 'ParserClearState', array( &$this ) );
319 wfProfileOut( __METHOD__
);
323 * Convert wikitext to HTML
324 * Do not call this function recursively.
326 * @param $text String: text we want to parse
327 * @param $title Title object
328 * @param $options ParserOptions
329 * @param $linestart boolean
330 * @param $clearState boolean
331 * @param $revid Int: number to pass in {{REVISIONID}}
332 * @return ParserOutput a ParserOutput
334 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
336 * First pass--just handle <nowiki> sections, pass the rest off
337 * to internalParse() which does all the real work.
340 global $wgUseTidy, $wgAlwaysUseTidy, $wgDisableLangConversion, $wgDisableTitleConversion;
341 $fname = __METHOD__
.'-' . wfGetCaller();
342 wfProfileIn( __METHOD__
);
343 wfProfileIn( $fname );
345 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
347 # Remove the strip marker tag prefix from the input, if present.
349 $text = str_replace( $this->mUniqPrefix
, '', $text );
352 $oldRevisionId = $this->mRevisionId
;
353 $oldRevisionObject = $this->mRevisionObject
;
354 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
355 $oldRevisionUser = $this->mRevisionUser
;
356 if ( $revid !== null ) {
357 $this->mRevisionId
= $revid;
358 $this->mRevisionObject
= null;
359 $this->mRevisionTimestamp
= null;
360 $this->mRevisionUser
= null;
363 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
365 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
366 $text = $this->internalParse( $text );
367 wfRunHooks( 'ParserAfterParse', array( &$this, &$text, &$this->mStripState
) );
369 $text = $this->mStripState
->unstripGeneral( $text );
371 # Clean up special characters, only run once, next-to-last before doBlockLevels
373 # french spaces, last one Guillemet-left
374 # only if there is something before the space
375 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
376 # french spaces, Guillemet-right
377 '/(\\302\\253) /' => '\\1 ',
378 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
380 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
382 $text = $this->doBlockLevels( $text, $linestart );
384 $this->replaceLinkHolders( $text );
387 * The input doesn't get language converted if
389 * b) Content isn't converted
390 * c) It's a conversion table
391 * d) it is an interface message (which is in the user language)
393 if ( !( $wgDisableLangConversion
394 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
395 ||
$this->mTitle
->isConversionTable() ) )
397 # Run convert unconditionally in 1.18-compatible mode
398 global $wgBug34832TransitionalRollback;
399 if ( $wgBug34832TransitionalRollback ||
!$this->mOptions
->getInterfaceMessage() ) {
400 # The position of the convert() call should not be changed. it
401 # assumes that the links are all replaced and the only thing left
402 # is the <nowiki> mark.
403 $text = $this->getConverterLanguage()->convert( $text );
408 * A converted title will be provided in the output object if title and
409 * content conversion are enabled, the article text does not contain
410 * a conversion-suppressing double-underscore tag, and no
411 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
412 * automatic link conversion.
414 if ( !( $wgDisableLangConversion
415 ||
$wgDisableTitleConversion
416 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
417 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
418 ||
$this->mOutput
->getDisplayTitle() !== false ) )
420 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
421 if ( $convruletitle ) {
422 $this->mOutput
->setTitleText( $convruletitle );
424 $titleText = $this->getConverterLanguage()->convertTitle( $title );
425 $this->mOutput
->setTitleText( $titleText );
429 $text = $this->mStripState
->unstripNoWiki( $text );
431 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
433 $text = $this->replaceTransparentTags( $text );
434 $text = $this->mStripState
->unstripGeneral( $text );
436 $text = Sanitizer
::normalizeCharReferences( $text );
438 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
439 $text = MWTidy
::tidy( $text );
441 # attempt to sanitize at least some nesting problems
442 # (bug #2702 and quite a few others)
444 # ''Something [http://www.cool.com cool''] -->
445 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
446 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
447 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
448 # fix up an anchor inside another anchor, only
449 # at least for a single single nested link (bug 3695)
450 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
451 '\\1\\2</a>\\3</a>\\1\\4</a>',
452 # fix div inside inline elements- doBlockLevels won't wrap a line which
453 # contains a div, so fix it up here; replace
454 # div with escaped text
455 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
456 '\\1\\3<div\\5>\\6</div>\\8\\9',
457 # remove empty italic or bold tag pairs, some
458 # introduced by rules above
459 '/<([bi])><\/\\1>/' => '',
462 $text = preg_replace(
463 array_keys( $tidyregs ),
464 array_values( $tidyregs ),
468 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
469 $this->limitationWarn( 'expensive-parserfunction',
470 $this->mExpensiveFunctionCount
,
471 $this->mOptions
->getExpensiveParserFunctionLimit()
475 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
477 # Information on include size limits, for the benefit of users who try to skirt them
478 if ( $this->mOptions
->getEnableLimitReport() ) {
479 $max = $this->mOptions
->getMaxIncludeSize();
480 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/{$this->mOptions->getExpensiveParserFunctionLimit()}\n";
482 "NewPP limit report\n" .
483 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
484 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
485 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
486 "Highest expansion depth: {$this->mHighestExpansionDepth}/{$this->mOptions->getMaxPPExpandDepth()}\n".
488 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
489 $text .= "\n<!-- \n$limitReport-->\n";
491 $this->mOutput
->setText( $text );
493 $this->mRevisionId
= $oldRevisionId;
494 $this->mRevisionObject
= $oldRevisionObject;
495 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
496 $this->mRevisionUser
= $oldRevisionUser;
497 wfProfileOut( $fname );
498 wfProfileOut( __METHOD__
);
500 return $this->mOutput
;
504 * Recursive parser entry point that can be called from an extension tag
507 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
509 * @param $text String: text extension wants to have parsed
510 * @param $frame PPFrame: The frame to use for expanding any template variables
514 function recursiveTagParse( $text, $frame=false ) {
515 wfProfileIn( __METHOD__
);
516 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
517 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
518 $text = $this->internalParse( $text, false, $frame );
519 wfProfileOut( __METHOD__
);
524 * Expand templates and variables in the text, producing valid, static wikitext.
525 * Also removes comments.
526 * @return mixed|string
528 function preprocess( $text, Title
$title, ParserOptions
$options, $revid = null ) {
529 wfProfileIn( __METHOD__
);
530 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
531 if ( $revid !== null ) {
532 $this->mRevisionId
= $revid;
534 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
535 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
536 $text = $this->replaceVariables( $text );
537 $text = $this->mStripState
->unstripBoth( $text );
538 wfProfileOut( __METHOD__
);
543 * Recursive parser entry point that can be called from an extension tag
546 * @param $text String: text to be expanded
547 * @param $frame PPFrame: The frame to use for expanding any template variables
551 public function recursivePreprocess( $text, $frame = false ) {
552 wfProfileIn( __METHOD__
);
553 $text = $this->replaceVariables( $text, $frame );
554 $text = $this->mStripState
->unstripBoth( $text );
555 wfProfileOut( __METHOD__
);
560 * Process the wikitext for the ?preload= feature. (bug 5210)
562 * <noinclude>, <includeonly> etc. are parsed as for template transclusion,
563 * comments, templates, arguments, tags hooks and parser functions are untouched.
565 * @param $text String
566 * @param $title Title
567 * @param $options ParserOptions
570 public function getPreloadText( $text, Title
$title, ParserOptions
$options ) {
571 # Parser (re)initialisation
572 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
574 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
575 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
576 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
577 $text = $this->mStripState
->unstripBoth( $text );
582 * Get a random string
586 static public function getRandomString() {
587 return wfRandomString( 16 );
591 * Set the current user.
592 * Should only be used when doing pre-save transform.
594 * @param $user Mixed: User object or null (to reset)
596 function setUser( $user ) {
597 $this->mUser
= $user;
601 * Accessor for mUniqPrefix.
605 public function uniqPrefix() {
606 if ( !isset( $this->mUniqPrefix
) ) {
607 # @todo FIXME: This is probably *horribly wrong*
608 # LanguageConverter seems to want $wgParser's uniqPrefix, however
609 # if this is called for a parser cache hit, the parser may not
610 # have ever been initialized in the first place.
611 # Not really sure what the heck is supposed to be going on here.
613 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
615 return $this->mUniqPrefix
;
619 * Set the context title
623 function setTitle( $t ) {
624 if ( !$t ||
$t instanceof FakeTitle
) {
625 $t = Title
::newFromText( 'NO TITLE' );
628 if ( strval( $t->getFragment() ) !== '' ) {
629 # Strip the fragment to avoid various odd effects
630 $this->mTitle
= clone $t;
631 $this->mTitle
->setFragment( '' );
638 * Accessor for the Title object
640 * @return Title object
642 function getTitle() {
643 return $this->mTitle
;
647 * Accessor/mutator for the Title object
649 * @param $x Title object or null to just get the current one
650 * @return Title object
652 function Title( $x = null ) {
653 return wfSetVar( $this->mTitle
, $x );
657 * Set the output type
659 * @param $ot Integer: new value
661 function setOutputType( $ot ) {
662 $this->mOutputType
= $ot;
665 'html' => $ot == self
::OT_HTML
,
666 'wiki' => $ot == self
::OT_WIKI
,
667 'pre' => $ot == self
::OT_PREPROCESS
,
668 'plain' => $ot == self
::OT_PLAIN
,
673 * Accessor/mutator for the output type
675 * @param $x int|null New value or null to just get the current one
678 function OutputType( $x = null ) {
679 return wfSetVar( $this->mOutputType
, $x );
683 * Get the ParserOutput object
685 * @return ParserOutput object
687 function getOutput() {
688 return $this->mOutput
;
692 * Get the ParserOptions object
694 * @return ParserOptions object
696 function getOptions() {
697 return $this->mOptions
;
701 * Accessor/mutator for the ParserOptions object
703 * @param $x ParserOptions New value or null to just get the current one
704 * @return ParserOptions Current ParserOptions object
706 function Options( $x = null ) {
707 return wfSetVar( $this->mOptions
, $x );
713 function nextLinkID() {
714 return $this->mLinkID++
;
720 function setLinkID( $id ) {
721 $this->mLinkID
= $id;
725 * Get a language object for use in parser functions such as {{FORMATNUM:}}
728 function getFunctionLang() {
729 return $this->getTargetLanguage();
733 * Get the target language for the content being parsed. This is usually the
734 * language that the content is in.
736 function getTargetLanguage() {
737 $target = $this->mOptions
->getTargetLanguage();
738 if ( $target !== null ) {
740 } elseif( $this->mOptions
->getInterfaceMessage() ) {
741 return $this->mOptions
->getUserLangObj();
742 } elseif( is_null( $this->mTitle
) ) {
743 throw new MWException( __METHOD__
.': $this->mTitle is null' );
745 return $this->mTitle
->getPageLanguage();
749 * Get the language object for language conversion
751 function getConverterLanguage() {
752 global $wgBug34832TransitionalRollback, $wgContLang;
753 if ( $wgBug34832TransitionalRollback ) {
756 return $this->getTargetLanguage();
761 * Get a User object either from $this->mUser, if set, or from the
762 * ParserOptions object otherwise
764 * @return User object
767 if ( !is_null( $this->mUser
) ) {
770 return $this->mOptions
->getUser();
774 * Get a preprocessor object
776 * @return Preprocessor instance
778 function getPreprocessor() {
779 if ( !isset( $this->mPreprocessor
) ) {
780 $class = $this->mPreprocessorClass
;
781 $this->mPreprocessor
= new $class( $this );
783 return $this->mPreprocessor
;
787 * Replaces all occurrences of HTML-style comments and the given tags
788 * in the text with a random marker and returns the next text. The output
789 * parameter $matches will be an associative array filled with data in
791 * 'UNIQ-xxxxx' => array(
794 * array( 'param' => 'x' ),
795 * '<element param="x">tag content</element>' ) )
797 * @param $elements array list of element names. Comments are always extracted.
798 * @param $text string Source text string.
799 * @param $matches array Out parameter, Array: extracted tags
800 * @param $uniq_prefix string
801 * @return String: stripped text
803 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
808 $taglist = implode( '|', $elements );
809 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
811 while ( $text != '' ) {
812 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
814 if ( count( $p ) < 5 ) {
817 if ( count( $p ) > 5 ) {
831 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
832 $stripped .= $marker;
834 if ( $close === '/>' ) {
835 # Empty element tag, <tag />
840 if ( $element === '!--' ) {
843 $end = "/(<\\/$element\\s*>)/i";
845 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
847 if ( count( $q ) < 3 ) {
848 # No end tag -- let it run out to the end of the text.
857 $matches[$marker] = array( $element,
859 Sanitizer
::decodeTagAttributes( $attributes ),
860 "<$element$attributes$close$content$tail" );
866 * Get a list of strippable XML-like elements
870 function getStripList() {
871 return $this->mStripList
;
875 * Add an item to the strip state
876 * Returns the unique tag which must be inserted into the stripped text
877 * The tag will be replaced with the original text in unstrip()
879 * @param $text string
883 function insertStripItem( $text ) {
884 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
885 $this->mMarkerIndex++
;
886 $this->mStripState
->addGeneral( $rnd, $text );
891 * parse the wiki syntax used to render tables
896 function doTableStuff( $text ) {
897 wfProfileIn( __METHOD__
);
899 $lines = StringUtils
::explode( "\n", $text );
901 $td_history = array(); # Is currently a td tag open?
902 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
903 $tr_history = array(); # Is currently a tr tag open?
904 $tr_attributes = array(); # history of tr attributes
905 $has_opened_tr = array(); # Did this table open a <tr> element?
906 $indent_level = 0; # indent level of the table
908 foreach ( $lines as $outLine ) {
909 $line = trim( $outLine );
911 if ( $line === '' ) { # empty line, go to next line
912 $out .= $outLine."\n";
916 $first_character = $line[0];
919 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
920 # First check if we are starting a new table
921 $indent_level = strlen( $matches[1] );
923 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
924 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
926 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
927 array_push( $td_history , false );
928 array_push( $last_tag_history , '' );
929 array_push( $tr_history , false );
930 array_push( $tr_attributes , '' );
931 array_push( $has_opened_tr , false );
932 } elseif ( count( $td_history ) == 0 ) {
933 # Don't do any of the following
934 $out .= $outLine."\n";
936 } elseif ( substr( $line , 0 , 2 ) === '|}' ) {
937 # We are ending a table
938 $line = '</table>' . substr( $line , 2 );
939 $last_tag = array_pop( $last_tag_history );
941 if ( !array_pop( $has_opened_tr ) ) {
942 $line = "<tr><td></td></tr>{$line}";
945 if ( array_pop( $tr_history ) ) {
946 $line = "</tr>{$line}";
949 if ( array_pop( $td_history ) ) {
950 $line = "</{$last_tag}>{$line}";
952 array_pop( $tr_attributes );
953 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
954 } elseif ( substr( $line , 0 , 2 ) === '|-' ) {
955 # Now we have a table row
956 $line = preg_replace( '#^\|-+#', '', $line );
958 # Whats after the tag is now only attributes
959 $attributes = $this->mStripState
->unstripBoth( $line );
960 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
961 array_pop( $tr_attributes );
962 array_push( $tr_attributes, $attributes );
965 $last_tag = array_pop( $last_tag_history );
966 array_pop( $has_opened_tr );
967 array_push( $has_opened_tr , true );
969 if ( array_pop( $tr_history ) ) {
973 if ( array_pop( $td_history ) ) {
974 $line = "</{$last_tag}>{$line}";
978 array_push( $tr_history , false );
979 array_push( $td_history , false );
980 array_push( $last_tag_history , '' );
981 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line , 0 , 2 ) === '|+' ) {
982 # This might be cell elements, td, th or captions
983 if ( substr( $line , 0 , 2 ) === '|+' ) {
984 $first_character = '+';
985 $line = substr( $line , 1 );
988 $line = substr( $line , 1 );
990 if ( $first_character === '!' ) {
991 $line = str_replace( '!!' , '||' , $line );
994 # Split up multiple cells on the same line.
995 # FIXME : This can result in improper nesting of tags processed
996 # by earlier parser steps, but should avoid splitting up eg
997 # attribute values containing literal "||".
998 $cells = StringUtils
::explodeMarkup( '||' , $line );
1002 # Loop through each table cell
1003 foreach ( $cells as $cell ) {
1005 if ( $first_character !== '+' ) {
1006 $tr_after = array_pop( $tr_attributes );
1007 if ( !array_pop( $tr_history ) ) {
1008 $previous = "<tr{$tr_after}>\n";
1010 array_push( $tr_history , true );
1011 array_push( $tr_attributes , '' );
1012 array_pop( $has_opened_tr );
1013 array_push( $has_opened_tr , true );
1016 $last_tag = array_pop( $last_tag_history );
1018 if ( array_pop( $td_history ) ) {
1019 $previous = "</{$last_tag}>\n{$previous}";
1022 if ( $first_character === '|' ) {
1024 } elseif ( $first_character === '!' ) {
1026 } elseif ( $first_character === '+' ) {
1027 $last_tag = 'caption';
1032 array_push( $last_tag_history , $last_tag );
1034 # A cell could contain both parameters and data
1035 $cell_data = explode( '|' , $cell , 2 );
1037 # Bug 553: Note that a '|' inside an invalid link should not
1038 # be mistaken as delimiting cell parameters
1039 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1040 $cell = "{$previous}<{$last_tag}>{$cell}";
1041 } elseif ( count( $cell_data ) == 1 ) {
1042 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1044 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1045 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
1046 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1050 array_push( $td_history , true );
1053 $out .= $outLine . "\n";
1056 # Closing open td, tr && table
1057 while ( count( $td_history ) > 0 ) {
1058 if ( array_pop( $td_history ) ) {
1061 if ( array_pop( $tr_history ) ) {
1064 if ( !array_pop( $has_opened_tr ) ) {
1065 $out .= "<tr><td></td></tr>\n" ;
1068 $out .= "</table>\n";
1071 # Remove trailing line-ending (b/c)
1072 if ( substr( $out, -1 ) === "\n" ) {
1073 $out = substr( $out, 0, -1 );
1076 # special case: don't return empty table
1077 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1081 wfProfileOut( __METHOD__
);
1087 * Helper function for parse() that transforms wiki markup into
1088 * HTML. Only called for $mOutputType == self::OT_HTML.
1092 * @param $text string
1093 * @param $isMain bool
1094 * @param $frame bool
1098 function internalParse( $text, $isMain = true, $frame = false ) {
1099 wfProfileIn( __METHOD__
);
1103 # Hook to suspend the parser in this state
1104 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1105 wfProfileOut( __METHOD__
);
1109 # if $frame is provided, then use $frame for replacing any variables
1111 # use frame depth to infer how include/noinclude tags should be handled
1112 # depth=0 means this is the top-level document; otherwise it's an included document
1113 if ( !$frame->depth
) {
1116 $flag = Parser
::PTD_FOR_INCLUSION
;
1118 $dom = $this->preprocessToDom( $text, $flag );
1119 $text = $frame->expand( $dom );
1121 # if $frame is not provided, then use old-style replaceVariables
1122 $text = $this->replaceVariables( $text );
1125 wfRunHooks( 'InternalParseBeforeSanitize', array( &$this, &$text, &$this->mStripState
) );
1126 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1127 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1129 # Tables need to come after variable replacement for things to work
1130 # properly; putting them before other transformations should keep
1131 # exciting things like link expansions from showing up in surprising
1133 $text = $this->doTableStuff( $text );
1135 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1137 $text = $this->doDoubleUnderscore( $text );
1139 $text = $this->doHeadings( $text );
1140 if ( $this->mOptions
->getUseDynamicDates() ) {
1141 $df = DateFormatter
::getInstance();
1142 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1144 $text = $this->replaceInternalLinks( $text );
1145 $text = $this->doAllQuotes( $text );
1146 $text = $this->replaceExternalLinks( $text );
1148 # replaceInternalLinks may sometimes leave behind
1149 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1150 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
1152 $text = $this->doMagicLinks( $text );
1153 $text = $this->formatHeadings( $text, $origText, $isMain );
1155 wfProfileOut( __METHOD__
);
1160 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1161 * magic external links.
1166 * @param $text string
1170 function doMagicLinks( $text ) {
1171 wfProfileIn( __METHOD__
);
1172 $prots = wfUrlProtocolsWithoutProtRel();
1173 $urlChar = self
::EXT_LINK_URL_CLASS
;
1174 $text = preg_replace_callback(
1176 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1177 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1178 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1179 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1180 ISBN\s+(\b # m[5]: ISBN, capture number
1181 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1182 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1183 [0-9Xx] # check digit
1185 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1186 wfProfileOut( __METHOD__
);
1191 * @throws MWException
1193 * @return HTML|string
1195 function magicLinkCallback( $m ) {
1196 if ( isset( $m[1] ) && $m[1] !== '' ) {
1199 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1202 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1203 # Free external link
1204 return $this->makeFreeExternalLink( $m[0] );
1205 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1207 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1210 $CssClass = 'mw-magiclink-rfc';
1212 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1214 $urlmsg = 'pubmedurl';
1215 $CssClass = 'mw-magiclink-pmid';
1218 throw new MWException( __METHOD__
.': unrecognised match type "' .
1219 substr( $m[0], 0, 20 ) . '"' );
1221 $url = wfMsgForContent( $urlmsg, $id );
1222 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1223 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1226 $num = strtr( $isbn, array(
1231 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1233 htmlspecialchars( $titleObj->getLocalUrl() ) .
1234 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1241 * Make a free external link, given a user-supplied URL
1243 * @param $url string
1245 * @return string HTML
1248 function makeFreeExternalLink( $url ) {
1249 wfProfileIn( __METHOD__
);
1253 # The characters '<' and '>' (which were escaped by
1254 # removeHTMLtags()) should not be included in
1255 # URLs, per RFC 2396.
1257 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1258 $trail = substr( $url, $m2[0][1] ) . $trail;
1259 $url = substr( $url, 0, $m2[0][1] );
1262 # Move trailing punctuation to $trail
1264 # If there is no left bracket, then consider right brackets fair game too
1265 if ( strpos( $url, '(' ) === false ) {
1269 $numSepChars = strspn( strrev( $url ), $sep );
1270 if ( $numSepChars ) {
1271 $trail = substr( $url, -$numSepChars ) . $trail;
1272 $url = substr( $url, 0, -$numSepChars );
1275 $url = Sanitizer
::cleanUrl( $url );
1277 # Is this an external image?
1278 $text = $this->maybeMakeExternalImage( $url );
1279 if ( $text === false ) {
1280 # Not an image, make a link
1281 $text = Linker
::makeExternalLink( $url,
1282 $this->getConverterLanguage()->markNoConversion($url), true, 'free',
1283 $this->getExternalLinkAttribs( $url ) );
1284 # Register it in the output object...
1285 # Replace unnecessary URL escape codes with their equivalent characters
1286 $pasteurized = self
::replaceUnusualEscapes( $url );
1287 $this->mOutput
->addExternalLink( $pasteurized );
1289 wfProfileOut( __METHOD__
);
1290 return $text . $trail;
1295 * Parse headers and return html
1299 * @param $text string
1303 function doHeadings( $text ) {
1304 wfProfileIn( __METHOD__
);
1305 for ( $i = 6; $i >= 1; --$i ) {
1306 $h = str_repeat( '=', $i );
1307 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1308 "<h$i>\\1</h$i>", $text );
1310 wfProfileOut( __METHOD__
);
1315 * Replace single quotes with HTML markup
1318 * @param $text string
1320 * @return string the altered text
1322 function doAllQuotes( $text ) {
1323 wfProfileIn( __METHOD__
);
1325 $lines = StringUtils
::explode( "\n", $text );
1326 foreach ( $lines as $line ) {
1327 $outtext .= $this->doQuotes( $line ) . "\n";
1329 $outtext = substr( $outtext, 0,-1 );
1330 wfProfileOut( __METHOD__
);
1335 * Helper function for doAllQuotes()
1337 * @param $text string
1341 public function doQuotes( $text ) {
1342 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1343 if ( count( $arr ) == 1 ) {
1346 # First, do some preliminary work. This may shift some apostrophes from
1347 # being mark-up to being text. It also counts the number of occurrences
1348 # of bold and italics mark-ups.
1351 for ( $i = 0; $i < count( $arr ); $i++
) {
1352 if ( ( $i %
2 ) == 1 ) {
1353 # If there are ever four apostrophes, assume the first is supposed to
1354 # be text, and the remaining three constitute mark-up for bold text.
1355 if ( strlen( $arr[$i] ) == 4 ) {
1358 } elseif ( strlen( $arr[$i] ) > 5 ) {
1359 # If there are more than 5 apostrophes in a row, assume they're all
1360 # text except for the last 5.
1361 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1364 # Count the number of occurrences of bold and italics mark-ups.
1365 # We are not counting sequences of five apostrophes.
1366 if ( strlen( $arr[$i] ) == 2 ) {
1368 } elseif ( strlen( $arr[$i] ) == 3 ) {
1370 } elseif ( strlen( $arr[$i] ) == 5 ) {
1377 # If there is an odd number of both bold and italics, it is likely
1378 # that one of the bold ones was meant to be an apostrophe followed
1379 # by italics. Which one we cannot know for certain, but it is more
1380 # likely to be one that has a single-letter word before it.
1381 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1383 $firstsingleletterword = -1;
1384 $firstmultiletterword = -1;
1386 foreach ( $arr as $r ) {
1387 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1388 $x1 = substr( $arr[$i-1], -1 );
1389 $x2 = substr( $arr[$i-1], -2, 1 );
1390 if ( $x1 === ' ' ) {
1391 if ( $firstspace == -1 ) {
1394 } elseif ( $x2 === ' ') {
1395 if ( $firstsingleletterword == -1 ) {
1396 $firstsingleletterword = $i;
1399 if ( $firstmultiletterword == -1 ) {
1400 $firstmultiletterword = $i;
1407 # If there is a single-letter word, use it!
1408 if ( $firstsingleletterword > -1 ) {
1409 $arr[$firstsingleletterword] = "''";
1410 $arr[$firstsingleletterword-1] .= "'";
1411 } elseif ( $firstmultiletterword > -1 ) {
1412 # If not, but there's a multi-letter word, use that one.
1413 $arr[$firstmultiletterword] = "''";
1414 $arr[$firstmultiletterword-1] .= "'";
1415 } elseif ( $firstspace > -1 ) {
1416 # ... otherwise use the first one that has neither.
1417 # (notice that it is possible for all three to be -1 if, for example,
1418 # there is only one pentuple-apostrophe in the line)
1419 $arr[$firstspace] = "''";
1420 $arr[$firstspace-1] .= "'";
1424 # Now let's actually convert our apostrophic mush to HTML!
1429 foreach ( $arr as $r ) {
1430 if ( ( $i %
2 ) == 0 ) {
1431 if ( $state === 'both' ) {
1437 if ( strlen( $r ) == 2 ) {
1438 if ( $state === 'i' ) {
1439 $output .= '</i>'; $state = '';
1440 } elseif ( $state === 'bi' ) {
1441 $output .= '</i>'; $state = 'b';
1442 } elseif ( $state === 'ib' ) {
1443 $output .= '</b></i><b>'; $state = 'b';
1444 } elseif ( $state === 'both' ) {
1445 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1446 } else { # $state can be 'b' or ''
1447 $output .= '<i>'; $state .= 'i';
1449 } elseif ( strlen( $r ) == 3 ) {
1450 if ( $state === 'b' ) {
1451 $output .= '</b>'; $state = '';
1452 } elseif ( $state === 'bi' ) {
1453 $output .= '</i></b><i>'; $state = 'i';
1454 } elseif ( $state === 'ib' ) {
1455 $output .= '</b>'; $state = 'i';
1456 } elseif ( $state === 'both' ) {
1457 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1458 } else { # $state can be 'i' or ''
1459 $output .= '<b>'; $state .= 'b';
1461 } elseif ( strlen( $r ) == 5 ) {
1462 if ( $state === 'b' ) {
1463 $output .= '</b><i>'; $state = 'i';
1464 } elseif ( $state === 'i' ) {
1465 $output .= '</i><b>'; $state = 'b';
1466 } elseif ( $state === 'bi' ) {
1467 $output .= '</i></b>'; $state = '';
1468 } elseif ( $state === 'ib' ) {
1469 $output .= '</b></i>'; $state = '';
1470 } elseif ( $state === 'both' ) {
1471 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1472 } else { # ($state == '')
1473 $buffer = ''; $state = 'both';
1479 # Now close all remaining tags. Notice that the order is important.
1480 if ( $state === 'b' ||
$state === 'ib' ) {
1483 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1486 if ( $state === 'bi' ) {
1489 # There might be lonely ''''', so make sure we have a buffer
1490 if ( $state === 'both' && $buffer ) {
1491 $output .= '<b><i>'.$buffer.'</i></b>';
1498 * Replace external links (REL)
1500 * Note: this is all very hackish and the order of execution matters a lot.
1501 * Make sure to run maintenance/parserTests.php if you change this code.
1505 * @param $text string
1509 function replaceExternalLinks( $text ) {
1510 wfProfileIn( __METHOD__
);
1512 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1513 $s = array_shift( $bits );
1516 while ( $i<count( $bits ) ) {
1518 $protocol = $bits[$i++
];
1519 $text = $bits[$i++
];
1520 $trail = $bits[$i++
];
1522 # The characters '<' and '>' (which were escaped by
1523 # removeHTMLtags()) should not be included in
1524 # URLs, per RFC 2396.
1526 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1527 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1528 $url = substr( $url, 0, $m2[0][1] );
1531 # If the link text is an image URL, replace it with an <img> tag
1532 # This happened by accident in the original parser, but some people used it extensively
1533 $img = $this->maybeMakeExternalImage( $text );
1534 if ( $img !== false ) {
1540 # Set linktype for CSS - if URL==text, link is essentially free
1541 $linktype = ( $text === $url ) ?
'free' : 'text';
1543 # No link text, e.g. [http://domain.tld/some.link]
1544 if ( $text == '' ) {
1546 $langObj = $this->getTargetLanguage();
1547 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1548 $linktype = 'autonumber';
1550 # Have link text, e.g. [http://domain.tld/some.link text]s
1552 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1555 $text = $this->getConverterLanguage()->markNoConversion( $text );
1557 $url = Sanitizer
::cleanUrl( $url );
1559 # Use the encoded URL
1560 # This means that users can paste URLs directly into the text
1561 # Funny characters like ö aren't valid in URLs anyway
1562 # This was changed in August 2004
1563 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1564 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1566 # Register link in the output object.
1567 # Replace unnecessary URL escape codes with the referenced character
1568 # This prevents spammers from hiding links from the filters
1569 $pasteurized = self
::replaceUnusualEscapes( $url );
1570 $this->mOutput
->addExternalLink( $pasteurized );
1573 wfProfileOut( __METHOD__
);
1578 * Get an associative array of additional HTML attributes appropriate for a
1579 * particular external link. This currently may include rel => nofollow
1580 * (depending on configuration, namespace, and the URL's domain) and/or a
1581 * target attribute (depending on configuration).
1583 * @param $url String|bool optional URL, to extract the domain from for rel =>
1584 * nofollow if appropriate
1585 * @return Array associative array of HTML attributes
1587 function getExternalLinkAttribs( $url = false ) {
1589 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1590 $ns = $this->mTitle
->getNamespace();
1591 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) &&
1592 !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions ) )
1594 $attribs['rel'] = 'nofollow';
1596 if ( $this->mOptions
->getExternalLinkTarget() ) {
1597 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1603 * Replace unusual URL escape codes with their equivalent characters
1605 * @param $url String
1608 * @todo This can merge genuinely required bits in the path or query string,
1609 * breaking legit URLs. A proper fix would treat the various parts of
1610 * the URL differently; as a workaround, just use the output for
1611 * statistical records, not for actual linking/output.
1613 static function replaceUnusualEscapes( $url ) {
1614 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1615 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1619 * Callback function used in replaceUnusualEscapes().
1620 * Replaces unusual URL escape codes with their equivalent character
1622 * @param $matches array
1626 private static function replaceUnusualEscapesCallback( $matches ) {
1627 $char = urldecode( $matches[0] );
1628 $ord = ord( $char );
1629 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1630 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1631 # No, shouldn't be escaped
1634 # Yes, leave it escaped
1640 * make an image if it's allowed, either through the global
1641 * option, through the exception, or through the on-wiki whitelist
1644 * $param $url string
1648 function maybeMakeExternalImage( $url ) {
1649 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1650 $imagesexception = !empty( $imagesfrom );
1652 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1653 if ( $imagesexception && is_array( $imagesfrom ) ) {
1654 $imagematch = false;
1655 foreach ( $imagesfrom as $match ) {
1656 if ( strpos( $url, $match ) === 0 ) {
1661 } elseif ( $imagesexception ) {
1662 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1664 $imagematch = false;
1666 if ( $this->mOptions
->getAllowExternalImages()
1667 ||
( $imagesexception && $imagematch ) ) {
1668 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1670 $text = Linker
::makeExternalImage( $url );
1673 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1674 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1675 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1676 foreach ( $whitelist as $entry ) {
1677 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1678 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1681 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1682 # Image matches a whitelist entry
1683 $text = Linker
::makeExternalImage( $url );
1692 * Process [[ ]] wikilinks
1696 * @return String: processed text
1700 function replaceInternalLinks( $s ) {
1701 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1706 * Process [[ ]] wikilinks (RIL)
1707 * @return LinkHolderArray
1711 function replaceInternalLinks2( &$s ) {
1712 wfProfileIn( __METHOD__
);
1714 wfProfileIn( __METHOD__
.'-setup' );
1715 static $tc = FALSE, $e1, $e1_img;
1716 # the % is needed to support urlencoded titles as well
1718 $tc = Title
::legalChars() . '#%';
1719 # Match a link having the form [[namespace:link|alternate]]trail
1720 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1721 # Match cases where there is no "]]", which might still be images
1722 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1725 $holders = new LinkHolderArray( $this );
1727 # split the entire text string on occurrences of [[
1728 $a = StringUtils
::explode( '[[', ' ' . $s );
1729 # get the first element (all text up to first [[), and remove the space we added
1732 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1733 $s = substr( $s, 1 );
1735 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1737 if ( $useLinkPrefixExtension ) {
1738 # Match the end of a line for a word that's not followed by whitespace,
1739 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1740 $e2 = wfMsgForContent( 'linkprefix' );
1743 if ( is_null( $this->mTitle
) ) {
1744 wfProfileOut( __METHOD__
.'-setup' );
1745 wfProfileOut( __METHOD__
);
1746 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1748 $nottalk = !$this->mTitle
->isTalkPage();
1750 if ( $useLinkPrefixExtension ) {
1752 if ( preg_match( $e2, $s, $m ) ) {
1753 $first_prefix = $m[2];
1755 $first_prefix = false;
1761 if ( $this->getConverterLanguage()->hasVariants() ) {
1762 $selflink = $this->getConverterLanguage()->autoConvertToAllVariants(
1763 $this->mTitle
->getPrefixedText() );
1765 $selflink = array( $this->mTitle
->getPrefixedText() );
1767 $useSubpages = $this->areSubpagesAllowed();
1768 wfProfileOut( __METHOD__
.'-setup' );
1770 # Loop for each link
1771 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1772 # Check for excessive memory usage
1773 if ( $holders->isBig() ) {
1775 # Do the existence check, replace the link holders and clear the array
1776 $holders->replace( $s );
1780 if ( $useLinkPrefixExtension ) {
1781 wfProfileIn( __METHOD__
.'-prefixhandling' );
1782 if ( preg_match( $e2, $s, $m ) ) {
1789 if ( $first_prefix ) {
1790 $prefix = $first_prefix;
1791 $first_prefix = false;
1793 wfProfileOut( __METHOD__
.'-prefixhandling' );
1796 $might_be_img = false;
1798 wfProfileIn( __METHOD__
."-e1" );
1799 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1801 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1802 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1803 # the real problem is with the $e1 regex
1806 # Still some problems for cases where the ] is meant to be outside punctuation,
1807 # and no image is in sight. See bug 2095.
1809 if ( $text !== '' &&
1810 substr( $m[3], 0, 1 ) === ']' &&
1811 strpos( $text, '[' ) !== false
1814 $text .= ']'; # so that replaceExternalLinks($text) works later
1815 $m[3] = substr( $m[3], 1 );
1817 # fix up urlencoded title texts
1818 if ( strpos( $m[1], '%' ) !== false ) {
1819 # Should anchors '#' also be rejected?
1820 $m[1] = str_replace( array('<', '>'), array('<', '>'), rawurldecode( $m[1] ) );
1823 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1824 $might_be_img = true;
1826 if ( strpos( $m[1], '%' ) !== false ) {
1827 $m[1] = rawurldecode( $m[1] );
1830 } else { # Invalid form; output directly
1831 $s .= $prefix . '[[' . $line ;
1832 wfProfileOut( __METHOD__
."-e1" );
1835 wfProfileOut( __METHOD__
."-e1" );
1836 wfProfileIn( __METHOD__
."-misc" );
1838 # Don't allow internal links to pages containing
1839 # PROTO: where PROTO is a valid URL protocol; these
1840 # should be external links.
1841 if ( preg_match( '/^(?:' . $this->mUrlProtocols
. ')/', $m[1] ) ) {
1842 $s .= $prefix . '[[' . $line ;
1843 wfProfileOut( __METHOD__
."-misc" );
1847 # Make subpage if necessary
1848 if ( $useSubpages ) {
1849 $link = $this->maybeDoSubpageLink( $m[1], $text );
1854 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1856 # Strip off leading ':'
1857 $link = substr( $link, 1 );
1860 wfProfileOut( __METHOD__
."-misc" );
1861 wfProfileIn( __METHOD__
."-title" );
1862 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1863 if ( $nt === null ) {
1864 $s .= $prefix . '[[' . $line;
1865 wfProfileOut( __METHOD__
."-title" );
1869 $ns = $nt->getNamespace();
1870 $iw = $nt->getInterWiki();
1871 wfProfileOut( __METHOD__
."-title" );
1873 if ( $might_be_img ) { # if this is actually an invalid link
1874 wfProfileIn( __METHOD__
."-might_be_img" );
1875 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1878 # look at the next 'line' to see if we can close it there
1880 $next_line = $a->current();
1881 if ( $next_line === false ||
$next_line === null ) {
1884 $m = explode( ']]', $next_line, 3 );
1885 if ( count( $m ) == 3 ) {
1886 # the first ]] closes the inner link, the second the image
1888 $text .= "[[{$m[0]}]]{$m[1]}";
1891 } elseif ( count( $m ) == 2 ) {
1892 # if there's exactly one ]] that's fine, we'll keep looking
1893 $text .= "[[{$m[0]}]]{$m[1]}";
1895 # if $next_line is invalid too, we need look no further
1896 $text .= '[[' . $next_line;
1901 # we couldn't find the end of this imageLink, so output it raw
1902 # but don't ignore what might be perfectly normal links in the text we've examined
1903 $holders->merge( $this->replaceInternalLinks2( $text ) );
1904 $s .= "{$prefix}[[$link|$text";
1905 # note: no $trail, because without an end, there *is* no trail
1906 wfProfileOut( __METHOD__
."-might_be_img" );
1909 } else { # it's not an image, so output it raw
1910 $s .= "{$prefix}[[$link|$text";
1911 # note: no $trail, because without an end, there *is* no trail
1912 wfProfileOut( __METHOD__
."-might_be_img" );
1915 wfProfileOut( __METHOD__
."-might_be_img" );
1918 $wasblank = ( $text == '' );
1922 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1923 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1924 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1925 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1926 $text = $this->doQuotes( $text );
1929 # Link not escaped by : , create the various objects
1932 wfProfileIn( __METHOD__
."-interwiki" );
1933 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && Language
::fetchLanguageName( $iw, null, 'mw' ) ) {
1934 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1935 $s = rtrim( $s . $prefix );
1936 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1937 wfProfileOut( __METHOD__
."-interwiki" );
1940 wfProfileOut( __METHOD__
."-interwiki" );
1942 if ( $ns == NS_FILE
) {
1943 wfProfileIn( __METHOD__
."-image" );
1944 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1946 # if no parameters were passed, $text
1947 # becomes something like "File:Foo.png",
1948 # which we don't want to pass on to the
1952 # recursively parse links inside the image caption
1953 # actually, this will parse them in any other parameters, too,
1954 # but it might be hard to fix that, and it doesn't matter ATM
1955 $text = $this->replaceExternalLinks( $text );
1956 $holders->merge( $this->replaceInternalLinks2( $text ) );
1958 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1959 $s .= $prefix . $this->armorLinks(
1960 $this->makeImage( $nt, $text, $holders ) ) . $trail;
1962 $s .= $prefix . $trail;
1964 wfProfileOut( __METHOD__
."-image" );
1968 if ( $ns == NS_CATEGORY
) {
1969 wfProfileIn( __METHOD__
."-category" );
1970 $s = rtrim( $s . "\n" ); # bug 87
1973 $sortkey = $this->getDefaultSort();
1977 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1978 $sortkey = str_replace( "\n", '', $sortkey );
1979 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
1980 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1983 * Strip the whitespace Category links produce, see bug 87
1984 * @todo We might want to use trim($tmp, "\n") here.
1986 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
1988 wfProfileOut( __METHOD__
."-category" );
1993 # Self-link checking
1994 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1995 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1996 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2001 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2002 # @todo FIXME: Should do batch file existence checks, see comment below
2003 if ( $ns == NS_MEDIA
) {
2004 wfProfileIn( __METHOD__
."-media" );
2005 # Give extensions a chance to select the file revision for us
2008 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2009 array( $this, $nt, &$options, &$descQuery ) );
2010 # Fetch and register the file (file title may be different via hooks)
2011 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2012 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2013 $s .= $prefix . $this->armorLinks(
2014 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2015 wfProfileOut( __METHOD__
."-media" );
2019 wfProfileIn( __METHOD__
."-always_known" );
2020 # Some titles, such as valid special pages or files in foreign repos, should
2021 # be shown as bluelinks even though they're not included in the page table
2023 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2024 # batch file existence checks for NS_FILE and NS_MEDIA
2025 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2026 $this->mOutput
->addLink( $nt );
2027 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2029 # Links will be added to the output link list after checking
2030 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2032 wfProfileOut( __METHOD__
."-always_known" );
2034 wfProfileOut( __METHOD__
);
2039 * Render a forced-blue link inline; protect against double expansion of
2040 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2041 * Since this little disaster has to split off the trail text to avoid
2042 * breaking URLs in the following text without breaking trails on the
2043 * wiki links, it's been made into a horrible function.
2046 * @param $text String
2047 * @param $query Array or String
2048 * @param $trail String
2049 * @param $prefix String
2050 * @return String: HTML-wikitext mix oh yuck
2052 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2053 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2055 if ( is_string( $query ) ) {
2056 $query = wfCgiToArray( $query );
2058 if ( $text == '' ) {
2059 $text = htmlspecialchars( $nt->getPrefixedText() );
2062 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2064 return $this->armorLinks( $link ) . $trail;
2068 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2069 * going to go through further parsing steps before inline URL expansion.
2071 * Not needed quite as much as it used to be since free links are a bit
2072 * more sensible these days. But bracketed links are still an issue.
2074 * @param $text String: more-or-less HTML
2075 * @return String: less-or-more HTML with NOPARSE bits
2077 function armorLinks( $text ) {
2078 return preg_replace( '/\b(' . $this->mUrlProtocols
. ')/',
2079 "{$this->mUniqPrefix}NOPARSE$1", $text );
2083 * Return true if subpage links should be expanded on this page.
2086 function areSubpagesAllowed() {
2087 # Some namespaces don't allow subpages
2088 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2092 * Handle link to subpage if necessary
2094 * @param $target String: the source of the link
2095 * @param &$text String: the link text, modified as necessary
2096 * @return string the full name of the link
2099 function maybeDoSubpageLink( $target, &$text ) {
2100 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2104 * Used by doBlockLevels()
2109 function closeParagraph() {
2111 if ( $this->mLastSection
!= '' ) {
2112 $result = '</' . $this->mLastSection
. ">\n";
2114 $this->mInPre
= false;
2115 $this->mLastSection
= '';
2120 * getCommon() returns the length of the longest common substring
2121 * of both arguments, starting at the beginning of both.
2124 * @param $st1 string
2125 * @param $st2 string
2129 function getCommon( $st1, $st2 ) {
2130 $fl = strlen( $st1 );
2131 $shorter = strlen( $st2 );
2132 if ( $fl < $shorter ) {
2136 for ( $i = 0; $i < $shorter; ++
$i ) {
2137 if ( $st1[$i] != $st2[$i] ) {
2145 * These next three functions open, continue, and close the list
2146 * element appropriate to the prefix character passed into them.
2149 * @param $char string
2153 function openList( $char ) {
2154 $result = $this->closeParagraph();
2156 if ( '*' === $char ) {
2157 $result .= '<ul><li>';
2158 } elseif ( '#' === $char ) {
2159 $result .= '<ol><li>';
2160 } elseif ( ':' === $char ) {
2161 $result .= '<dl><dd>';
2162 } elseif ( ';' === $char ) {
2163 $result .= '<dl><dt>';
2164 $this->mDTopen
= true;
2166 $result = '<!-- ERR 1 -->';
2174 * @param $char String
2179 function nextItem( $char ) {
2180 if ( '*' === $char ||
'#' === $char ) {
2182 } elseif ( ':' === $char ||
';' === $char ) {
2184 if ( $this->mDTopen
) {
2187 if ( ';' === $char ) {
2188 $this->mDTopen
= true;
2189 return $close . '<dt>';
2191 $this->mDTopen
= false;
2192 return $close . '<dd>';
2195 return '<!-- ERR 2 -->';
2200 * @param $char String
2205 function closeList( $char ) {
2206 if ( '*' === $char ) {
2207 $text = '</li></ul>';
2208 } elseif ( '#' === $char ) {
2209 $text = '</li></ol>';
2210 } elseif ( ':' === $char ) {
2211 if ( $this->mDTopen
) {
2212 $this->mDTopen
= false;
2213 $text = '</dt></dl>';
2215 $text = '</dd></dl>';
2218 return '<!-- ERR 3 -->';
2225 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2227 * @param $text String
2228 * @param $linestart Boolean: whether or not this is at the start of a line.
2230 * @return string the lists rendered as HTML
2232 function doBlockLevels( $text, $linestart ) {
2233 wfProfileIn( __METHOD__
);
2235 # Parsing through the text line by line. The main thing
2236 # happening here is handling of block-level elements p, pre,
2237 # and making lists from lines starting with * # : etc.
2239 $textLines = StringUtils
::explode( "\n", $text );
2241 $lastPrefix = $output = '';
2242 $this->mDTopen
= $inBlockElem = false;
2244 $paragraphStack = false;
2246 foreach ( $textLines as $oLine ) {
2248 if ( !$linestart ) {
2258 $lastPrefixLength = strlen( $lastPrefix );
2259 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2260 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2261 # If not in a <pre> element, scan for and figure out what prefixes are there.
2262 if ( !$this->mInPre
) {
2263 # Multiple prefixes may abut each other for nested lists.
2264 $prefixLength = strspn( $oLine, '*#:;' );
2265 $prefix = substr( $oLine, 0, $prefixLength );
2268 # ; and : are both from definition-lists, so they're equivalent
2269 # for the purposes of determining whether or not we need to open/close
2271 $prefix2 = str_replace( ';', ':', $prefix );
2272 $t = substr( $oLine, $prefixLength );
2273 $this->mInPre
= (bool)$preOpenMatch;
2275 # Don't interpret any other prefixes in preformatted text
2277 $prefix = $prefix2 = '';
2282 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2283 # Same as the last item, so no need to deal with nesting or opening stuff
2284 $output .= $this->nextItem( substr( $prefix, -1 ) );
2285 $paragraphStack = false;
2287 if ( substr( $prefix, -1 ) === ';') {
2288 # The one nasty exception: definition lists work like this:
2289 # ; title : definition text
2290 # So we check for : in the remainder text to split up the
2291 # title and definition, without b0rking links.
2293 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2295 $output .= $term . $this->nextItem( ':' );
2298 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2299 # We need to open or close prefixes, or both.
2301 # Either open or close a level...
2302 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2303 $paragraphStack = false;
2305 # Close all the prefixes which aren't shared.
2306 while ( $commonPrefixLength < $lastPrefixLength ) {
2307 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2308 --$lastPrefixLength;
2311 # Continue the current prefix if appropriate.
2312 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2313 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2316 # Open prefixes where appropriate.
2317 while ( $prefixLength > $commonPrefixLength ) {
2318 $char = substr( $prefix, $commonPrefixLength, 1 );
2319 $output .= $this->openList( $char );
2321 if ( ';' === $char ) {
2322 # @todo FIXME: This is dupe of code above
2323 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2325 $output .= $term . $this->nextItem( ':' );
2328 ++
$commonPrefixLength;
2330 $lastPrefix = $prefix2;
2333 # If we have no prefixes, go to paragraph mode.
2334 if ( 0 == $prefixLength ) {
2335 wfProfileIn( __METHOD__
."-paragraph" );
2336 # No prefix (not in list)--go to paragraph mode
2337 # XXX: use a stack for nestable elements like span, table and div
2338 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2339 $closematch = preg_match(
2340 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2341 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2342 if ( $openmatch or $closematch ) {
2343 $paragraphStack = false;
2344 # TODO bug 5718: paragraph closed
2345 $output .= $this->closeParagraph();
2346 if ( $preOpenMatch and !$preCloseMatch ) {
2347 $this->mInPre
= true;
2349 $inBlockElem = !$closematch;
2350 } elseif ( !$inBlockElem && !$this->mInPre
) {
2351 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2353 if ( $this->mLastSection
!== 'pre' ) {
2354 $paragraphStack = false;
2355 $output .= $this->closeParagraph().'<pre>';
2356 $this->mLastSection
= 'pre';
2358 $t = substr( $t, 1 );
2361 if ( trim( $t ) === '' ) {
2362 if ( $paragraphStack ) {
2363 $output .= $paragraphStack.'<br />';
2364 $paragraphStack = false;
2365 $this->mLastSection
= 'p';
2367 if ( $this->mLastSection
!== 'p' ) {
2368 $output .= $this->closeParagraph();
2369 $this->mLastSection
= '';
2370 $paragraphStack = '<p>';
2372 $paragraphStack = '</p><p>';
2376 if ( $paragraphStack ) {
2377 $output .= $paragraphStack;
2378 $paragraphStack = false;
2379 $this->mLastSection
= 'p';
2380 } elseif ( $this->mLastSection
!== 'p' ) {
2381 $output .= $this->closeParagraph().'<p>';
2382 $this->mLastSection
= 'p';
2387 wfProfileOut( __METHOD__
."-paragraph" );
2389 # somewhere above we forget to get out of pre block (bug 785)
2390 if ( $preCloseMatch && $this->mInPre
) {
2391 $this->mInPre
= false;
2393 if ( $paragraphStack === false ) {
2397 while ( $prefixLength ) {
2398 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2401 if ( $this->mLastSection
!= '' ) {
2402 $output .= '</' . $this->mLastSection
. '>';
2403 $this->mLastSection
= '';
2406 wfProfileOut( __METHOD__
);
2411 * Split up a string on ':', ignoring any occurrences inside tags
2412 * to prevent illegal overlapping.
2414 * @param $str String the string to split
2415 * @param &$before String set to everything before the ':'
2416 * @param &$after String set to everything after the ':'
2417 * @return String the position of the ':', or false if none found
2419 function findColonNoLinks( $str, &$before, &$after ) {
2420 wfProfileIn( __METHOD__
);
2422 $pos = strpos( $str, ':' );
2423 if ( $pos === false ) {
2425 wfProfileOut( __METHOD__
);
2429 $lt = strpos( $str, '<' );
2430 if ( $lt === false ||
$lt > $pos ) {
2431 # Easy; no tag nesting to worry about
2432 $before = substr( $str, 0, $pos );
2433 $after = substr( $str, $pos+
1 );
2434 wfProfileOut( __METHOD__
);
2438 # Ugly state machine to walk through avoiding tags.
2439 $state = self
::COLON_STATE_TEXT
;
2441 $len = strlen( $str );
2442 for( $i = 0; $i < $len; $i++
) {
2446 # (Using the number is a performance hack for common cases)
2447 case 0: # self::COLON_STATE_TEXT:
2450 # Could be either a <start> tag or an </end> tag
2451 $state = self
::COLON_STATE_TAGSTART
;
2454 if ( $stack == 0 ) {
2456 $before = substr( $str, 0, $i );
2457 $after = substr( $str, $i +
1 );
2458 wfProfileOut( __METHOD__
);
2461 # Embedded in a tag; don't break it.
2464 # Skip ahead looking for something interesting
2465 $colon = strpos( $str, ':', $i );
2466 if ( $colon === false ) {
2467 # Nothing else interesting
2468 wfProfileOut( __METHOD__
);
2471 $lt = strpos( $str, '<', $i );
2472 if ( $stack === 0 ) {
2473 if ( $lt === false ||
$colon < $lt ) {
2475 $before = substr( $str, 0, $colon );
2476 $after = substr( $str, $colon +
1 );
2477 wfProfileOut( __METHOD__
);
2481 if ( $lt === false ) {
2482 # Nothing else interesting to find; abort!
2483 # We're nested, but there's no close tags left. Abort!
2486 # Skip ahead to next tag start
2488 $state = self
::COLON_STATE_TAGSTART
;
2491 case 1: # self::COLON_STATE_TAG:
2496 $state = self
::COLON_STATE_TEXT
;
2499 # Slash may be followed by >?
2500 $state = self
::COLON_STATE_TAGSLASH
;
2506 case 2: # self::COLON_STATE_TAGSTART:
2509 $state = self
::COLON_STATE_CLOSETAG
;
2512 $state = self
::COLON_STATE_COMMENT
;
2515 # Illegal early close? This shouldn't happen D:
2516 $state = self
::COLON_STATE_TEXT
;
2519 $state = self
::COLON_STATE_TAG
;
2522 case 3: # self::COLON_STATE_CLOSETAG:
2527 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2528 wfProfileOut( __METHOD__
);
2531 $state = self
::COLON_STATE_TEXT
;
2534 case self
::COLON_STATE_TAGSLASH
:
2536 # Yes, a self-closed tag <blah/>
2537 $state = self
::COLON_STATE_TEXT
;
2539 # Probably we're jumping the gun, and this is an attribute
2540 $state = self
::COLON_STATE_TAG
;
2543 case 5: # self::COLON_STATE_COMMENT:
2545 $state = self
::COLON_STATE_COMMENTDASH
;
2548 case self
::COLON_STATE_COMMENTDASH
:
2550 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2552 $state = self
::COLON_STATE_COMMENT
;
2555 case self
::COLON_STATE_COMMENTDASHDASH
:
2557 $state = self
::COLON_STATE_TEXT
;
2559 $state = self
::COLON_STATE_COMMENT
;
2563 throw new MWException( "State machine error in " . __METHOD__
);
2567 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2568 wfProfileOut( __METHOD__
);
2571 wfProfileOut( __METHOD__
);
2576 * Return value of a magic variable (like PAGENAME)
2580 * @param $index integer
2581 * @param $frame PPFrame
2585 function getVariableValue( $index, $frame = false ) {
2586 global $wgContLang, $wgSitename, $wgServer;
2587 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2589 if ( is_null( $this->mTitle
) ) {
2590 // If no title set, bad things are going to happen
2591 // later. Title should always be set since this
2592 // should only be called in the middle of a parse
2593 // operation (but the unit-tests do funky stuff)
2594 throw new MWException( __METHOD__
. ' Should only be '
2595 . ' called while parsing (no title set)' );
2599 * Some of these require message or data lookups and can be
2600 * expensive to check many times.
2602 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2603 if ( isset( $this->mVarCache
[$index] ) ) {
2604 return $this->mVarCache
[$index];
2608 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2609 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2612 global $wgLocaltimezone;
2613 if ( isset( $wgLocaltimezone ) ) {
2614 $oldtz = date_default_timezone_get();
2615 date_default_timezone_set( $wgLocaltimezone );
2618 $localTimestamp = date( 'YmdHis', $ts );
2619 $localMonth = date( 'm', $ts );
2620 $localMonth1 = date( 'n', $ts );
2621 $localMonthName = date( 'n', $ts );
2622 $localDay = date( 'j', $ts );
2623 $localDay2 = date( 'd', $ts );
2624 $localDayOfWeek = date( 'w', $ts );
2625 $localWeek = date( 'W', $ts );
2626 $localYear = date( 'Y', $ts );
2627 $localHour = date( 'H', $ts );
2628 if ( isset( $wgLocaltimezone ) ) {
2629 date_default_timezone_set( $oldtz );
2632 $pageLang = $this->getFunctionLang();
2635 case 'currentmonth':
2636 $value = $pageLang->formatNum( gmdate( 'm', $ts ) );
2638 case 'currentmonth1':
2639 $value = $pageLang->formatNum( gmdate( 'n', $ts ) );
2641 case 'currentmonthname':
2642 $value = $pageLang->getMonthName( gmdate( 'n', $ts ) );
2644 case 'currentmonthnamegen':
2645 $value = $pageLang->getMonthNameGen( gmdate( 'n', $ts ) );
2647 case 'currentmonthabbrev':
2648 $value = $pageLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2651 $value = $pageLang->formatNum( gmdate( 'j', $ts ) );
2654 $value = $pageLang->formatNum( gmdate( 'd', $ts ) );
2657 $value = $pageLang->formatNum( $localMonth );
2660 $value = $pageLang->formatNum( $localMonth1 );
2662 case 'localmonthname':
2663 $value = $pageLang->getMonthName( $localMonthName );
2665 case 'localmonthnamegen':
2666 $value = $pageLang->getMonthNameGen( $localMonthName );
2668 case 'localmonthabbrev':
2669 $value = $pageLang->getMonthAbbreviation( $localMonthName );
2672 $value = $pageLang->formatNum( $localDay );
2675 $value = $pageLang->formatNum( $localDay2 );
2678 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2681 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2683 case 'fullpagename':
2684 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2686 case 'fullpagenamee':
2687 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2690 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2692 case 'subpagenamee':
2693 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2695 case 'basepagename':
2696 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2698 case 'basepagenamee':
2699 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2701 case 'talkpagename':
2702 if ( $this->mTitle
->canTalk() ) {
2703 $talkPage = $this->mTitle
->getTalkPage();
2704 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2709 case 'talkpagenamee':
2710 if ( $this->mTitle
->canTalk() ) {
2711 $talkPage = $this->mTitle
->getTalkPage();
2712 $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() );
2717 case 'subjectpagename':
2718 $subjPage = $this->mTitle
->getSubjectPage();
2719 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2721 case 'subjectpagenamee':
2722 $subjPage = $this->mTitle
->getSubjectPage();
2723 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() );
2725 case 'pageid': // requested in bug 23427
2726 $pageid = $this->getTitle()->getArticleId();
2727 if( $pageid == 0 ) {
2728 # 0 means the page doesn't exist in the database,
2729 # which means the user is previewing a new page.
2730 # The vary-revision flag must be set, because the magic word
2731 # will have a different value once the page is saved.
2732 $this->mOutput
->setFlag( 'vary-revision' );
2733 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2735 $value = $pageid ?
$pageid : null;
2738 # Let the edit saving system know we should parse the page
2739 # *after* a revision ID has been assigned.
2740 $this->mOutput
->setFlag( 'vary-revision' );
2741 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2742 $value = $this->mRevisionId
;
2745 # Let the edit saving system know we should parse the page
2746 # *after* a revision ID has been assigned. This is for null edits.
2747 $this->mOutput
->setFlag( 'vary-revision' );
2748 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2749 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2751 case 'revisionday2':
2752 # Let the edit saving system know we should parse the page
2753 # *after* a revision ID has been assigned. This is for null edits.
2754 $this->mOutput
->setFlag( 'vary-revision' );
2755 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2756 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2758 case 'revisionmonth':
2759 # Let the edit saving system know we should parse the page
2760 # *after* a revision ID has been assigned. This is for null edits.
2761 $this->mOutput
->setFlag( 'vary-revision' );
2762 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2763 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2765 case 'revisionmonth1':
2766 # Let the edit saving system know we should parse the page
2767 # *after* a revision ID has been assigned. This is for null edits.
2768 $this->mOutput
->setFlag( 'vary-revision' );
2769 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2770 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2772 case 'revisionyear':
2773 # Let the edit saving system know we should parse the page
2774 # *after* a revision ID has been assigned. This is for null edits.
2775 $this->mOutput
->setFlag( 'vary-revision' );
2776 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2777 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2779 case 'revisiontimestamp':
2780 # Let the edit saving system know we should parse the page
2781 # *after* a revision ID has been assigned. This is for null edits.
2782 $this->mOutput
->setFlag( 'vary-revision' );
2783 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2784 $value = $this->getRevisionTimestamp();
2786 case 'revisionuser':
2787 # Let the edit saving system know we should parse the page
2788 # *after* a revision ID has been assigned. This is for null edits.
2789 $this->mOutput
->setFlag( 'vary-revision' );
2790 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2791 $value = $this->getRevisionUser();
2794 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2797 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2799 case 'namespacenumber':
2800 $value = $this->mTitle
->getNamespace();
2803 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2806 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2808 case 'subjectspace':
2809 $value = $this->mTitle
->getSubjectNsText();
2811 case 'subjectspacee':
2812 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2814 case 'currentdayname':
2815 $value = $pageLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2818 $value = $pageLang->formatNum( gmdate( 'Y', $ts ), true );
2821 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2824 $value = $pageLang->formatNum( gmdate( 'H', $ts ), true );
2827 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2828 # int to remove the padding
2829 $value = $pageLang->formatNum( (int)gmdate( 'W', $ts ) );
2832 $value = $pageLang->formatNum( gmdate( 'w', $ts ) );
2834 case 'localdayname':
2835 $value = $pageLang->getWeekdayName( $localDayOfWeek +
1 );
2838 $value = $pageLang->formatNum( $localYear, true );
2841 $value = $pageLang->time( $localTimestamp, false, false );
2844 $value = $pageLang->formatNum( $localHour, true );
2847 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2848 # int to remove the padding
2849 $value = $pageLang->formatNum( (int)$localWeek );
2852 $value = $pageLang->formatNum( $localDayOfWeek );
2854 case 'numberofarticles':
2855 $value = $pageLang->formatNum( SiteStats
::articles() );
2857 case 'numberoffiles':
2858 $value = $pageLang->formatNum( SiteStats
::images() );
2860 case 'numberofusers':
2861 $value = $pageLang->formatNum( SiteStats
::users() );
2863 case 'numberofactiveusers':
2864 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2866 case 'numberofpages':
2867 $value = $pageLang->formatNum( SiteStats
::pages() );
2869 case 'numberofadmins':
2870 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2872 case 'numberofedits':
2873 $value = $pageLang->formatNum( SiteStats
::edits() );
2875 case 'numberofviews':
2876 global $wgDisableCounters;
2877 $value = !$wgDisableCounters ?
$pageLang->formatNum( SiteStats
::views() ) : '';
2879 case 'currenttimestamp':
2880 $value = wfTimestamp( TS_MW
, $ts );
2882 case 'localtimestamp':
2883 $value = $localTimestamp;
2885 case 'currentversion':
2886 $value = SpecialVersion
::getVersion();
2889 return $wgArticlePath;
2895 $serverParts = wfParseUrl( $wgServer );
2896 return $serverParts && isset( $serverParts['host'] ) ?
$serverParts['host'] : $wgServer;
2898 return $wgScriptPath;
2900 return $wgStylePath;
2901 case 'directionmark':
2902 return $pageLang->getDirMark();
2903 case 'contentlanguage':
2904 global $wgLanguageCode;
2905 return $wgLanguageCode;
2908 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2916 $this->mVarCache
[$index] = $value;
2923 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2927 function initialiseVariables() {
2928 wfProfileIn( __METHOD__
);
2929 $variableIDs = MagicWord
::getVariableIDs();
2930 $substIDs = MagicWord
::getSubstIDs();
2932 $this->mVariables
= new MagicWordArray( $variableIDs );
2933 $this->mSubstWords
= new MagicWordArray( $substIDs );
2934 wfProfileOut( __METHOD__
);
2938 * Preprocess some wikitext and return the document tree.
2939 * This is the ghost of replace_variables().
2941 * @param $text String: The text to parse
2942 * @param $flags Integer: bitwise combination of:
2943 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2944 * included. Default is to assume a direct page view.
2946 * The generated DOM tree must depend only on the input text and the flags.
2947 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2949 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2950 * change in the DOM tree for a given text, must be passed through the section identifier
2951 * in the section edit link and thus back to extractSections().
2953 * The output of this function is currently only cached in process memory, but a persistent
2954 * cache may be implemented at a later date which takes further advantage of these strict
2955 * dependency requirements.
2961 function preprocessToDom( $text, $flags = 0 ) {
2962 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2967 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2973 public static function splitWhitespace( $s ) {
2974 $ltrimmed = ltrim( $s );
2975 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2976 $trimmed = rtrim( $ltrimmed );
2977 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2979 $w2 = substr( $ltrimmed, -$diff );
2983 return array( $w1, $trimmed, $w2 );
2987 * Replace magic variables, templates, and template arguments
2988 * with the appropriate text. Templates are substituted recursively,
2989 * taking care to avoid infinite loops.
2991 * Note that the substitution depends on value of $mOutputType:
2992 * self::OT_WIKI: only {{subst:}} templates
2993 * self::OT_PREPROCESS: templates but not extension tags
2994 * self::OT_HTML: all templates and extension tags
2996 * @param $text String the text to transform
2997 * @param $frame PPFrame Object describing the arguments passed to the template.
2998 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2999 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
3000 * @param $argsOnly Boolean only do argument (triple-brace) expansion, not double-brace expansion
3005 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3006 # Is there any text? Also, Prevent too big inclusions!
3007 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3010 wfProfileIn( __METHOD__
);
3012 if ( $frame === false ) {
3013 $frame = $this->getPreprocessor()->newFrame();
3014 } elseif ( !( $frame instanceof PPFrame
) ) {
3015 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
3016 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3019 $dom = $this->preprocessToDom( $text );
3020 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3021 $text = $frame->expand( $dom, $flags );
3023 wfProfileOut( __METHOD__
);
3028 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3030 * @param $args array
3034 static function createAssocArgs( $args ) {
3035 $assocArgs = array();
3037 foreach ( $args as $arg ) {
3038 $eqpos = strpos( $arg, '=' );
3039 if ( $eqpos === false ) {
3040 $assocArgs[$index++
] = $arg;
3042 $name = trim( substr( $arg, 0, $eqpos ) );
3043 $value = trim( substr( $arg, $eqpos+
1 ) );
3044 if ( $value === false ) {
3047 if ( $name !== false ) {
3048 $assocArgs[$name] = $value;
3057 * Warn the user when a parser limitation is reached
3058 * Will warn at most once the user per limitation type
3060 * @param $limitationType String: should be one of:
3061 * 'expensive-parserfunction' (corresponding messages:
3062 * 'expensive-parserfunction-warning',
3063 * 'expensive-parserfunction-category')
3064 * 'post-expand-template-argument' (corresponding messages:
3065 * 'post-expand-template-argument-warning',
3066 * 'post-expand-template-argument-category')
3067 * 'post-expand-template-inclusion' (corresponding messages:
3068 * 'post-expand-template-inclusion-warning',
3069 * 'post-expand-template-inclusion-category')
3070 * @param $current int|null Current value
3071 * @param $max int|null Maximum allowed, when an explicit limit has been
3072 * exceeded, provide the values (optional)
3074 function limitationWarn( $limitationType, $current = null, $max = null) {
3075 # does no harm if $current and $max are present but are unnecessary for the message
3076 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
3077 $this->mOutput
->addWarning( $warning );
3078 $this->addTrackingCategory( "$limitationType-category" );
3082 * Return the text of a template, after recursively
3083 * replacing any variables or templates within the template.
3085 * @param $piece Array: the parts of the template
3086 * $piece['title']: the title, i.e. the part before the |
3087 * $piece['parts']: the parameter array
3088 * $piece['lineStart']: whether the brace was at the start of a line
3089 * @param $frame PPFrame The current frame, contains template arguments
3090 * @return String: the text of the template
3093 function braceSubstitution( $piece, $frame ) {
3095 wfProfileIn( __METHOD__
);
3096 wfProfileIn( __METHOD__
.'-setup' );
3099 $found = false; # $text has been filled
3100 $nowiki = false; # wiki markup in $text should be escaped
3101 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3102 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3103 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3104 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3106 # Title object, where $text came from
3109 # $part1 is the bit before the first |, and must contain only title characters.
3110 # Various prefixes will be stripped from it later.
3111 $titleWithSpaces = $frame->expand( $piece['title'] );
3112 $part1 = trim( $titleWithSpaces );
3115 # Original title text preserved for various purposes
3116 $originalTitle = $part1;
3118 # $args is a list of argument nodes, starting from index 0, not including $part1
3119 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3120 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3121 wfProfileOut( __METHOD__
.'-setup' );
3123 $titleProfileIn = null; // profile templates
3126 wfProfileIn( __METHOD__
.'-modifiers' );
3129 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3131 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3132 # Decide whether to expand template or keep wikitext as-is.
3133 if ( $this->ot
['wiki'] ) {
3134 if ( $substMatch === false ) {
3135 $literal = true; # literal when in PST with no prefix
3137 $literal = false; # expand when in PST with subst: or safesubst:
3140 if ( $substMatch == 'subst' ) {
3141 $literal = true; # literal when not in PST with plain subst:
3143 $literal = false; # expand when not in PST with safesubst: or no prefix
3147 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3154 if ( !$found && $args->getLength() == 0 ) {
3155 $id = $this->mVariables
->matchStartToEnd( $part1 );
3156 if ( $id !== false ) {
3157 $text = $this->getVariableValue( $id, $frame );
3158 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3159 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3165 # MSG, MSGNW and RAW
3168 $mwMsgnw = MagicWord
::get( 'msgnw' );
3169 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3172 # Remove obsolete MSG:
3173 $mwMsg = MagicWord
::get( 'msg' );
3174 $mwMsg->matchStartAndRemove( $part1 );
3178 $mwRaw = MagicWord
::get( 'raw' );
3179 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3180 $forceRawInterwiki = true;
3183 wfProfileOut( __METHOD__
.'-modifiers' );
3187 wfProfileIn( __METHOD__
. '-pfunc' );
3189 $colonPos = strpos( $part1, ':' );
3190 if ( $colonPos !== false ) {
3191 # Case sensitive functions
3192 $function = substr( $part1, 0, $colonPos );
3193 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3194 $function = $this->mFunctionSynonyms
[1][$function];
3196 # Case insensitive functions
3197 $function = $wgContLang->lc( $function );
3198 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3199 $function = $this->mFunctionSynonyms
[0][$function];
3205 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3206 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3207 $initialArgs = array( &$this );
3208 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3209 if ( $flags & SFH_OBJECT_ARGS
) {
3210 # Add a frame parameter, and pass the arguments as an array
3211 $allArgs = $initialArgs;
3212 $allArgs[] = $frame;
3213 for ( $i = 0; $i < $args->getLength(); $i++
) {
3214 $funcArgs[] = $args->item( $i );
3216 $allArgs[] = $funcArgs;
3218 # Convert arguments to plain text
3219 for ( $i = 0; $i < $args->getLength(); $i++
) {
3220 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3222 $allArgs = array_merge( $initialArgs, $funcArgs );
3225 # Workaround for PHP bug 35229 and similar
3226 if ( !is_callable( $callback ) ) {
3227 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3228 wfProfileOut( __METHOD__
. '-pfunc' );
3229 wfProfileOut( __METHOD__
);
3230 throw new MWException( "Tag hook for $function is not callable\n" );
3232 $result = call_user_func_array( $callback, $allArgs );
3235 $preprocessFlags = 0;
3237 if ( is_array( $result ) ) {
3238 if ( isset( $result[0] ) ) {
3240 unset( $result[0] );
3243 # Extract flags into the local scope
3244 # This allows callers to set flags such as nowiki, found, etc.
3250 $text = $this->preprocessToDom( $text, $preprocessFlags );
3253 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3256 wfProfileOut( __METHOD__
. '-pfunc' );
3259 # Finish mangling title and then check for loops.
3260 # Set $title to a Title object and $titleText to the PDBK
3263 # Split the title into page and subpage
3265 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3266 if ( $subpage !== '' ) {
3267 $ns = $this->mTitle
->getNamespace();
3269 $title = Title
::newFromText( $part1, $ns );
3271 $titleText = $title->getPrefixedText();
3272 # Check for language variants if the template is not found
3273 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3274 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3276 # Do recursion depth check
3277 $limit = $this->mOptions
->getMaxTemplateDepth();
3278 if ( $frame->depth
>= $limit ) {
3280 $text = '<span class="error">'
3281 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
3287 # Load from database
3288 if ( !$found && $title ) {
3289 if ( !Profiler
::instance()->isPersistent() ) {
3290 # Too many unique items can kill profiling DBs/collectors
3291 $titleProfileIn = __METHOD__
. "-title-" . $title->getDBKey();
3292 wfProfileIn( $titleProfileIn ); // template in
3294 wfProfileIn( __METHOD__
. '-loadtpl' );
3295 if ( !$title->isExternal() ) {
3296 if ( $title->isSpecialPage()
3297 && $this->mOptions
->getAllowSpecialInclusion()
3298 && $this->ot
['html'] )
3300 // Pass the template arguments as URL parameters.
3301 // "uselang" will have no effect since the Language object
3302 // is forced to the one defined in ParserOptions.
3303 $pageArgs = array();
3304 for ( $i = 0; $i < $args->getLength(); $i++
) {
3305 $bits = $args->item( $i )->splitArg();
3306 if ( strval( $bits['index'] ) === '' ) {
3307 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3308 $value = trim( $frame->expand( $bits['value'] ) );
3309 $pageArgs[$name] = $value;
3313 // Create a new context to execute the special page
3314 $context = new RequestContext
;
3315 $context->setTitle( $title );
3316 $context->setRequest( new FauxRequest( $pageArgs ) );
3317 $context->setUser( $this->getUser() );
3318 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3319 $ret = SpecialPageFactory
::capturePath( $title, $context );
3321 $text = $context->getOutput()->getHTML();
3322 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3325 $this->disableCache();
3327 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3328 $found = false; # access denied
3329 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3331 list( $text, $title ) = $this->getTemplateDom( $title );
3332 if ( $text !== false ) {
3338 # If the title is valid but undisplayable, make a link to it
3339 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3340 $text = "[[:$titleText]]";
3343 } elseif ( $title->isTrans() ) {
3344 # Interwiki transclusion
3345 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3346 $text = $this->interwikiTransclude( $title, 'render' );
3349 $text = $this->interwikiTransclude( $title, 'raw' );
3350 # Preprocess it like a template
3351 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3357 # Do infinite loop check
3358 # This has to be done after redirect resolution to avoid infinite loops via redirects
3359 if ( !$frame->loopCheck( $title ) ) {
3361 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3362 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3364 wfProfileOut( __METHOD__
. '-loadtpl' );
3367 # If we haven't found text to substitute by now, we're done
3368 # Recover the source wikitext and return it
3370 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3371 if ( $titleProfileIn ) {
3372 wfProfileOut( $titleProfileIn ); // template out
3374 wfProfileOut( __METHOD__
);
3375 return array( 'object' => $text );
3378 # Expand DOM-style return values in a child frame
3379 if ( $isChildObj ) {
3380 # Clean up argument array
3381 $newFrame = $frame->newChild( $args, $title );
3384 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3385 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3386 # Expansion is eligible for the empty-frame cache
3387 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3388 $text = $this->mTplExpandCache
[$titleText];
3390 $text = $newFrame->expand( $text );
3391 $this->mTplExpandCache
[$titleText] = $text;
3394 # Uncached expansion
3395 $text = $newFrame->expand( $text );
3398 if ( $isLocalObj && $nowiki ) {
3399 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3400 $isLocalObj = false;
3403 if ( $titleProfileIn ) {
3404 wfProfileOut( $titleProfileIn ); // template out
3407 # Replace raw HTML by a placeholder
3409 $text = $this->insertStripItem( $text );
3410 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3411 # Escape nowiki-style return values
3412 $text = wfEscapeWikiText( $text );
3413 } elseif ( is_string( $text )
3414 && !$piece['lineStart']
3415 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3417 # Bug 529: if the template begins with a table or block-level
3418 # element, it should be treated as beginning a new line.
3419 # This behaviour is somewhat controversial.
3420 $text = "\n" . $text;
3423 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3424 # Error, oversize inclusion
3425 if ( $titleText !== false ) {
3426 # Make a working, properly escaped link if possible (bug 23588)
3427 $text = "[[:$titleText]]";
3429 # This will probably not be a working link, but at least it may
3430 # provide some hint of where the problem is
3431 preg_replace( '/^:/', '', $originalTitle );
3432 $text = "[[:$originalTitle]]";
3434 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3435 $this->limitationWarn( 'post-expand-template-inclusion' );
3438 if ( $isLocalObj ) {
3439 $ret = array( 'object' => $text );
3441 $ret = array( 'text' => $text );
3444 wfProfileOut( __METHOD__
);
3449 * Get the semi-parsed DOM representation of a template with a given title,
3450 * and its redirect destination title. Cached.
3452 * @param $title Title
3456 function getTemplateDom( $title ) {
3457 $cacheTitle = $title;
3458 $titleText = $title->getPrefixedDBkey();
3460 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3461 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3462 $title = Title
::makeTitle( $ns, $dbk );
3463 $titleText = $title->getPrefixedDBkey();
3465 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3466 return array( $this->mTplDomCache
[$titleText], $title );
3469 # Cache miss, go to the database
3470 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3472 if ( $text === false ) {
3473 $this->mTplDomCache
[$titleText] = false;
3474 return array( false, $title );
3477 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3478 $this->mTplDomCache
[ $titleText ] = $dom;
3480 if ( !$title->equals( $cacheTitle ) ) {
3481 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3482 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3485 return array( $dom, $title );
3489 * Fetch the unparsed text of a template and register a reference to it.
3490 * @param Title $title
3491 * @return Array ( string or false, Title )
3493 function fetchTemplateAndTitle( $title ) {
3494 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3495 $stuff = call_user_func( $templateCb, $title, $this );
3496 $text = $stuff['text'];
3497 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3498 if ( isset( $stuff['deps'] ) ) {
3499 foreach ( $stuff['deps'] as $dep ) {
3500 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3503 return array( $text, $finalTitle );
3507 * Fetch the unparsed text of a template and register a reference to it.
3508 * @param Title $title
3509 * @return mixed string or false
3511 function fetchTemplate( $title ) {
3512 $rv = $this->fetchTemplateAndTitle( $title );
3517 * Static function to get a template
3518 * Can be overridden via ParserOptions::setTemplateCallback().
3520 * @parma $title Title
3521 * @param $parser Parser
3525 static function statelessFetchTemplate( $title, $parser = false ) {
3526 $text = $skip = false;
3527 $finalTitle = $title;
3530 # Loop to fetch the article, with up to 1 redirect
3531 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3532 # Give extensions a chance to select the revision instead
3533 $id = false; # Assume current
3534 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3535 array( $parser, $title, &$skip, &$id ) );
3541 'page_id' => $title->getArticleID(),
3548 ? Revision
::newFromId( $id )
3549 : Revision
::newFromTitle( $title );
3550 $rev_id = $rev ?
$rev->getId() : 0;
3551 # If there is no current revision, there is no page
3552 if ( $id === false && !$rev ) {
3553 $linkCache = LinkCache
::singleton();
3554 $linkCache->addBadLinkObj( $title );
3559 'page_id' => $title->getArticleID(),
3560 'rev_id' => $rev_id );
3561 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3562 # We fetched a rev from a different title; register it too...
3564 'title' => $rev->getTitle(),
3565 'page_id' => $rev->getPage(),
3566 'rev_id' => $rev_id );
3570 $text = $rev->getText();
3571 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3573 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3574 if ( !$message->exists() ) {
3578 $text = $message->plain();
3582 if ( $text === false ) {
3586 $finalTitle = $title;
3587 $title = Title
::newFromRedirect( $text );
3591 'finalTitle' => $finalTitle,
3596 * Fetch a file and its title and register a reference to it.
3597 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3598 * @param Title $title
3599 * @param Array $options Array of options to RepoGroup::findFile
3602 function fetchFile( $title, $options = array() ) {
3603 $res = $this->fetchFileAndTitle( $title, $options );
3608 * Fetch a file and its title and register a reference to it.
3609 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3610 * @param Title $title
3611 * @param Array $options Array of options to RepoGroup::findFile
3612 * @return Array ( File or false, Title of file )
3614 function fetchFileAndTitle( $title, $options = array() ) {
3615 if ( isset( $options['broken'] ) ) {
3616 $file = false; // broken thumbnail forced by hook
3617 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3618 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3619 } else { // get by (name,timestamp)
3620 $file = wfFindFile( $title, $options );
3622 $time = $file ?
$file->getTimestamp() : false;
3623 $sha1 = $file ?
$file->getSha1() : false;
3624 # Register the file as a dependency...
3625 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3626 if ( $file && !$title->equals( $file->getTitle() ) ) {
3627 # Update fetched file title
3628 $title = $file->getTitle();
3629 if ( is_null( $file->getRedirectedTitle() ) ) {
3630 # This file was not a redirect, but the title does not match.
3631 # Register under the new name because otherwise the link will
3633 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3636 return array( $file, $title );
3640 * Transclude an interwiki link.
3642 * @param $title Title
3647 function interwikiTransclude( $title, $action ) {
3648 global $wgEnableScaryTranscluding;
3650 if ( !$wgEnableScaryTranscluding ) {
3651 return wfMsgForContent('scarytranscludedisabled');
3654 $url = $title->getFullUrl( "action=$action" );
3656 if ( strlen( $url ) > 255 ) {
3657 return wfMsgForContent( 'scarytranscludetoolong' );
3659 return $this->fetchScaryTemplateMaybeFromCache( $url );
3663 * @param $url string
3664 * @return Mixed|String
3666 function fetchScaryTemplateMaybeFromCache( $url ) {
3667 global $wgTranscludeCacheExpiry;
3668 $dbr = wfGetDB( DB_SLAVE
);
3669 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3670 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3671 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3673 return $obj->tc_contents
;
3676 $text = Http
::get( $url );
3678 return wfMsgForContent( 'scarytranscludefailed', $url );
3681 $dbw = wfGetDB( DB_MASTER
);
3682 $dbw->replace( 'transcache', array('tc_url'), array(
3684 'tc_time' => $dbw->timestamp( time() ),
3685 'tc_contents' => $text)
3691 * Triple brace replacement -- used for template arguments
3694 * @param $peice array
3695 * @param $frame PPFrame
3699 function argSubstitution( $piece, $frame ) {
3700 wfProfileIn( __METHOD__
);
3703 $parts = $piece['parts'];
3704 $nameWithSpaces = $frame->expand( $piece['title'] );
3705 $argName = trim( $nameWithSpaces );
3707 $text = $frame->getArgument( $argName );
3708 if ( $text === false && $parts->getLength() > 0
3712 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3715 # No match in frame, use the supplied default
3716 $object = $parts->item( 0 )->getChildren();
3718 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3719 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3720 $this->limitationWarn( 'post-expand-template-argument' );
3723 if ( $text === false && $object === false ) {
3725 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3727 if ( $error !== false ) {
3730 if ( $object !== false ) {
3731 $ret = array( 'object' => $object );
3733 $ret = array( 'text' => $text );
3736 wfProfileOut( __METHOD__
);
3741 * Return the text to be used for a given extension tag.
3742 * This is the ghost of strip().
3744 * @param $params array Associative array of parameters:
3745 * name PPNode for the tag name
3746 * attr PPNode for unparsed text where tag attributes are thought to be
3747 * attributes Optional associative array of parsed attributes
3748 * inner Contents of extension element
3749 * noClose Original text did not have a close tag
3750 * @param $frame PPFrame
3754 function extensionSubstitution( $params, $frame ) {
3755 $name = $frame->expand( $params['name'] );
3756 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3757 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3758 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3760 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3761 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3762 if ( $isFunctionTag ) {
3763 $markerType = 'none';
3765 $markerType = 'general';
3767 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3768 $name = strtolower( $name );
3769 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3770 if ( isset( $params['attributes'] ) ) {
3771 $attributes = $attributes +
$params['attributes'];
3774 if ( isset( $this->mTagHooks
[$name] ) ) {
3775 # Workaround for PHP bug 35229 and similar
3776 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3777 throw new MWException( "Tag hook for $name is not callable\n" );
3779 $output = call_user_func_array( $this->mTagHooks
[$name],
3780 array( $content, $attributes, $this, $frame ) );
3781 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3782 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3783 if ( !is_callable( $callback ) ) {
3784 throw new MWException( "Tag hook for $name is not callable\n" );
3787 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3789 $output = '<span class="error">Invalid tag extension name: ' .
3790 htmlspecialchars( $name ) . '</span>';
3793 if ( is_array( $output ) ) {
3794 # Extract flags to local scope (to override $markerType)
3796 $output = $flags[0];
3801 if ( is_null( $attrText ) ) {
3804 if ( isset( $params['attributes'] ) ) {
3805 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3806 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3807 htmlspecialchars( $attrValue ) . '"';
3810 if ( $content === null ) {
3811 $output = "<$name$attrText/>";
3813 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3814 $output = "<$name$attrText>$content$close";
3818 if ( $markerType === 'none' ) {
3820 } elseif ( $markerType === 'nowiki' ) {
3821 $this->mStripState
->addNoWiki( $marker, $output );
3822 } elseif ( $markerType === 'general' ) {
3823 $this->mStripState
->addGeneral( $marker, $output );
3825 throw new MWException( __METHOD__
.': invalid marker type' );
3831 * Increment an include size counter
3833 * @param $type String: the type of expansion
3834 * @param $size Integer: the size of the text
3835 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3837 function incrementIncludeSize( $type, $size ) {
3838 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3841 $this->mIncludeSizes
[$type] +
= $size;
3847 * Increment the expensive function count
3849 * @return Boolean: false if the limit has been exceeded
3851 function incrementExpensiveFunctionCount() {
3852 $this->mExpensiveFunctionCount++
;
3853 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
3857 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3858 * Fills $this->mDoubleUnderscores, returns the modified text
3860 * @param $text string
3864 function doDoubleUnderscore( $text ) {
3865 wfProfileIn( __METHOD__
);
3867 # The position of __TOC__ needs to be recorded
3868 $mw = MagicWord
::get( 'toc' );
3869 if ( $mw->match( $text ) ) {
3870 $this->mShowToc
= true;
3871 $this->mForceTocPosition
= true;
3873 # Set a placeholder. At the end we'll fill it in with the TOC.
3874 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3876 # Only keep the first one.
3877 $text = $mw->replace( '', $text );
3880 # Now match and remove the rest of them
3881 $mwa = MagicWord
::getDoubleUnderscoreArray();
3882 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3884 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3885 $this->mOutput
->mNoGallery
= true;
3887 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3888 $this->mShowToc
= false;
3890 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3891 $this->addTrackingCategory( 'hidden-category-category' );
3893 # (bug 8068) Allow control over whether robots index a page.
3895 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
3896 # is not desirable, the last one on the page should win.
3897 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3898 $this->mOutput
->setIndexPolicy( 'noindex' );
3899 $this->addTrackingCategory( 'noindex-category' );
3901 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3902 $this->mOutput
->setIndexPolicy( 'index' );
3903 $this->addTrackingCategory( 'index-category' );
3906 # Cache all double underscores in the database
3907 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
3908 $this->mOutput
->setProperty( $key, '' );
3911 wfProfileOut( __METHOD__
);
3916 * Add a tracking category, getting the title from a system message,
3917 * or print a debug message if the title is invalid.
3919 * @param $msg String: message key
3920 * @return Boolean: whether the addition was successful
3922 public function addTrackingCategory( $msg ) {
3923 if ( $this->mTitle
->getNamespace() === NS_SPECIAL
) {
3924 wfDebug( __METHOD__
.": Not adding tracking category $msg to special page!\n" );
3927 // Important to parse with correct title (bug 31469)
3928 $cat = wfMessage( $msg )
3929 ->title( $this->getTitle() )
3930 ->inContentLanguage()
3933 # Allow tracking categories to be disabled by setting them to "-"
3934 if ( $cat === '-' ) {
3938 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3939 if ( $containerCategory ) {
3940 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3943 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3949 * This function accomplishes several tasks:
3950 * 1) Auto-number headings if that option is enabled
3951 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3952 * 3) Add a Table of contents on the top for users who have enabled the option
3953 * 4) Auto-anchor headings
3955 * It loops through all headlines, collects the necessary data, then splits up the
3956 * string and re-inserts the newly formatted headlines.
3958 * @param $text String
3959 * @param $origText String: original, untouched wikitext
3960 * @param $isMain Boolean
3961 * @return mixed|string
3964 function formatHeadings( $text, $origText, $isMain=true ) {
3965 global $wgMaxTocLevel, $wgHtml5, $wgExperimentalHtmlIds;
3967 # Inhibit editsection links if requested in the page
3968 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3969 $maybeShowEditLink = $showEditLink = false;
3971 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
3972 $showEditLink = $this->mOptions
->getEditSection();
3974 if ( $showEditLink ) {
3975 $this->mOutput
->setEditSectionTokens( true );
3978 # Get all headlines for numbering them and adding funky stuff like [edit]
3979 # links - this is for later, but we need the number of headlines right now
3981 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3983 # if there are fewer than 4 headlines in the article, do not show TOC
3984 # unless it's been explicitly enabled.
3985 $enoughToc = $this->mShowToc
&&
3986 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
3988 # Allow user to stipulate that a page should have a "new section"
3989 # link added via __NEWSECTIONLINK__
3990 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3991 $this->mOutput
->setNewSection( true );
3994 # Allow user to remove the "new section"
3995 # link via __NONEWSECTIONLINK__
3996 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3997 $this->mOutput
->hideNewSection( true );
4000 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4001 # override above conditions and always show TOC above first header
4002 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4003 $this->mShowToc
= true;
4011 # Ugh .. the TOC should have neat indentation levels which can be
4012 # passed to the skin functions. These are determined here
4016 $sublevelCount = array();
4017 $levelCount = array();
4022 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4023 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4024 $oldType = $this->mOutputType
;
4025 $this->setOutputType( self
::OT_WIKI
);
4026 $frame = $this->getPreprocessor()->newFrame();
4027 $root = $this->preprocessToDom( $origText );
4028 $node = $root->getFirstChild();
4033 foreach ( $matches[3] as $headline ) {
4034 $isTemplate = false;
4036 $sectionIndex = false;
4038 $markerMatches = array();
4039 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
4040 $serial = $markerMatches[1];
4041 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4042 $isTemplate = ( $titleText != $baseTitleText );
4043 $headline = preg_replace( "/^$markerRegex/", "", $headline );
4047 $prevlevel = $level;
4049 $level = $matches[1][$headlineCount];
4051 if ( $level > $prevlevel ) {
4052 # Increase TOC level
4054 $sublevelCount[$toclevel] = 0;
4055 if ( $toclevel<$wgMaxTocLevel ) {
4056 $prevtoclevel = $toclevel;
4057 $toc .= Linker
::tocIndent();
4060 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4061 # Decrease TOC level, find level to jump to
4063 for ( $i = $toclevel; $i > 0; $i-- ) {
4064 if ( $levelCount[$i] == $level ) {
4065 # Found last matching level
4068 } elseif ( $levelCount[$i] < $level ) {
4069 # Found first matching level below current level
4077 if ( $toclevel<$wgMaxTocLevel ) {
4078 if ( $prevtoclevel < $wgMaxTocLevel ) {
4079 # Unindent only if the previous toc level was shown :p
4080 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4081 $prevtoclevel = $toclevel;
4083 $toc .= Linker
::tocLineEnd();
4087 # No change in level, end TOC line
4088 if ( $toclevel<$wgMaxTocLevel ) {
4089 $toc .= Linker
::tocLineEnd();
4093 $levelCount[$toclevel] = $level;
4095 # count number of headlines for each level
4096 @$sublevelCount[$toclevel]++
;
4098 for( $i = 1; $i <= $toclevel; $i++
) {
4099 if ( !empty( $sublevelCount[$i] ) ) {
4103 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4108 # The safe header is a version of the header text safe to use for links
4110 # Remove link placeholders by the link text.
4111 # <!--LINK number-->
4113 # link text with suffix
4114 # Do this before unstrip since link text can contain strip markers
4115 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4117 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4118 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4120 # Strip out HTML (first regex removes any tag not allowed)
4121 # Allowed tags are <sup> and <sub> (bug 8393), <i> (bug 26375) and <b> (r105284)
4122 # We strip any parameter from accepted tags (second regex)
4123 $tocline = preg_replace(
4124 array( '#<(?!/?(sup|sub|i|b)(?: [^>]*)?>).*?'.'>#', '#<(/?(sup|sub|i|b))(?: .*?)?'.'>#' ),
4125 array( '', '<$1>' ),
4128 $tocline = trim( $tocline );
4130 # For the anchor, strip out HTML-y stuff period
4131 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
4132 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4134 # Save headline for section edit hint before it's escaped
4135 $headlineHint = $safeHeadline;
4137 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
4138 # For reverse compatibility, provide an id that's
4139 # HTML4-compatible, like we used to.
4141 # It may be worth noting, academically, that it's possible for
4142 # the legacy anchor to conflict with a non-legacy headline
4143 # anchor on the page. In this case likely the "correct" thing
4144 # would be to either drop the legacy anchors or make sure
4145 # they're numbered first. However, this would require people
4146 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4147 # manually, so let's not bother worrying about it.
4148 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4149 array( 'noninitial', 'legacy' ) );
4150 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4152 if ( $legacyHeadline == $safeHeadline ) {
4153 # No reason to have both (in fact, we can't)
4154 $legacyHeadline = false;
4157 $legacyHeadline = false;
4158 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4162 # HTML names must be case-insensitively unique (bug 10721).
4163 # This does not apply to Unicode characters per
4164 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4165 # @todo FIXME: We may be changing them depending on the current locale.
4166 $arrayKey = strtolower( $safeHeadline );
4167 if ( $legacyHeadline === false ) {
4168 $legacyArrayKey = false;
4170 $legacyArrayKey = strtolower( $legacyHeadline );
4173 # count how many in assoc. array so we can track dupes in anchors
4174 if ( isset( $refers[$arrayKey] ) ) {
4175 $refers[$arrayKey]++
;
4177 $refers[$arrayKey] = 1;
4179 if ( isset( $refers[$legacyArrayKey] ) ) {
4180 $refers[$legacyArrayKey]++
;
4182 $refers[$legacyArrayKey] = 1;
4185 # Don't number the heading if it is the only one (looks silly)
4186 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4187 # the two are different if the line contains a link
4188 $headline = Html
::element( 'span', array( 'class' => 'mw-headline-number' ), $numbering ) . ' ' . $headline;
4191 # Create the anchor for linking from the TOC to the section
4192 $anchor = $safeHeadline;
4193 $legacyAnchor = $legacyHeadline;
4194 if ( $refers[$arrayKey] > 1 ) {
4195 $anchor .= '_' . $refers[$arrayKey];
4197 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4198 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4200 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4201 $toc .= Linker
::tocLine( $anchor, $tocline,
4202 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4205 # Add the section to the section tree
4206 # Find the DOM node for this header
4207 while ( $node && !$isTemplate ) {
4208 if ( $node->getName() === 'h' ) {
4209 $bits = $node->splitHeading();
4210 if ( $bits['i'] == $sectionIndex ) {
4214 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4215 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4216 $node = $node->getNextSibling();
4219 'toclevel' => $toclevel,
4222 'number' => $numbering,
4223 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4224 'fromtitle' => $titleText,
4225 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
4226 'anchor' => $anchor,
4229 # give headline the correct <h#> tag
4230 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4231 // Output edit section links as markers with styles that can be customized by skins
4232 if ( $isTemplate ) {
4233 # Put a T flag in the section identifier, to indicate to extractSections()
4234 # that sections inside <includeonly> should be counted.
4235 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4237 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
4239 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4240 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4241 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4242 // so we don't have to worry about a user trying to input one of these markers directly.
4243 // We use a page and section attribute to stop the language converter from converting these important bits
4244 // of data, but put the headline hint inside a content block because the language converter is supposed to
4245 // be able to convert that piece of data.
4246 $editlink = '<mw:editsection page="' . htmlspecialchars($editlinkArgs[0]);
4247 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"';
4248 if ( isset($editlinkArgs[2]) ) {
4249 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4256 $head[$headlineCount] = Linker
::makeHeadline( $level,
4257 $matches['attrib'][$headlineCount], $anchor, $headline,
4258 $editlink, $legacyAnchor );
4263 $this->setOutputType( $oldType );
4265 # Never ever show TOC if no headers
4266 if ( $numVisible < 1 ) {
4271 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4272 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4274 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4275 $this->mOutput
->setTOCHTML( $toc );
4279 $this->mOutput
->setSections( $tocraw );
4282 # split up and insert constructed headlines
4283 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4286 // build an array of document sections
4287 $sections = array();
4288 foreach ( $blocks as $block ) {
4289 // $head is zero-based, sections aren't.
4290 if ( empty( $head[$i - 1] ) ) {
4291 $sections[$i] = $block;
4293 $sections[$i] = $head[$i - 1] . $block;
4297 * Send a hook, one per section.
4298 * The idea here is to be able to make section-level DIVs, but to do so in a
4299 * lower-impact, more correct way than r50769
4302 * $section : the section number
4303 * &$sectionContent : ref to the content of the section
4304 * $showEditLinks : boolean describing whether this section has an edit link
4306 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4311 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4312 // append the TOC at the beginning
4313 // Top anchor now in skin
4314 $sections[0] = $sections[0] . $toc . "\n";
4317 $full .= join( '', $sections );
4319 if ( $this->mForceTocPosition
) {
4320 return str_replace( '<!--MWTOC-->', $toc, $full );
4327 * Transform wiki markup when saving a page by doing \r\n -> \n
4328 * conversion, substitting signatures, {{subst:}} templates, etc.
4330 * @param $text String: the text to transform
4331 * @param $title Title: the Title object for the current article
4332 * @param $user User: the User object describing the current user
4333 * @param $options ParserOptions: parsing options
4334 * @param $clearState Boolean: whether to clear the parser state first
4335 * @return String: the altered wiki markup
4337 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4338 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4339 $this->setUser( $user );
4344 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4345 if( $options->getPreSaveTransform() ) {
4346 $text = $this->pstPass2( $text, $user );
4348 $text = $this->mStripState
->unstripBoth( $text );
4350 $this->setUser( null ); #Reset
4356 * Pre-save transform helper function
4359 * @param $text string
4364 function pstPass2( $text, $user ) {
4365 global $wgContLang, $wgLocaltimezone;
4367 # Note: This is the timestamp saved as hardcoded wikitext to
4368 # the database, we use $wgContLang here in order to give
4369 # everyone the same signature and use the default one rather
4370 # than the one selected in each user's preferences.
4371 # (see also bug 12815)
4372 $ts = $this->mOptions
->getTimestamp();
4373 if ( isset( $wgLocaltimezone ) ) {
4374 $tz = $wgLocaltimezone;
4376 $tz = date_default_timezone_get();
4379 $unixts = wfTimestamp( TS_UNIX
, $ts );
4380 $oldtz = date_default_timezone_get();
4381 date_default_timezone_set( $tz );
4382 $ts = date( 'YmdHis', $unixts );
4383 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4385 # Allow translation of timezones through wiki. date() can return
4386 # whatever crap the system uses, localised or not, so we cannot
4387 # ship premade translations.
4388 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4389 $msg = wfMessage( $key )->inContentLanguage();
4390 if ( $msg->exists() ) {
4391 $tzMsg = $msg->text();
4394 date_default_timezone_set( $oldtz );
4396 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4398 # Variable replacement
4399 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4400 $text = $this->replaceVariables( $text );
4402 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4403 # which may corrupt this parser instance via its wfMsgExt( parsemag ) call-
4406 $sigText = $this->getUserSig( $user );
4407 $text = strtr( $text, array(
4409 '~~~~' => "$sigText $d",
4413 # Context links: [[|name]] and [[name (context)|]]
4414 $tc = '[' . Title
::legalChars() . ']';
4415 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4417 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4418 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]]
4419 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/"; # [[ns:page (context), context|]]
4420 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4422 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4423 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4424 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4425 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4427 $t = $this->mTitle
->getText();
4429 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4430 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4431 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4432 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4434 # if there's no context, don't bother duplicating the title
4435 $text = preg_replace( $p2, '[[\\1]]', $text );
4438 # Trim trailing whitespace
4439 $text = rtrim( $text );
4445 * Fetch the user's signature text, if any, and normalize to
4446 * validated, ready-to-insert wikitext.
4447 * If you have pre-fetched the nickname or the fancySig option, you can
4448 * specify them here to save a database query.
4449 * Do not reuse this parser instance after calling getUserSig(),
4450 * as it may have changed if it's the $wgParser.
4453 * @param $nickname String|bool nickname to use or false to use user's default nickname
4454 * @param $fancySig Boolean|null whether the nicknname is the complete signature
4455 * or null to use default value
4458 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4459 global $wgMaxSigChars;
4461 $username = $user->getName();
4463 # If not given, retrieve from the user object.
4464 if ( $nickname === false )
4465 $nickname = $user->getOption( 'nickname' );
4467 if ( is_null( $fancySig ) ) {
4468 $fancySig = $user->getBoolOption( 'fancysig' );
4471 $nickname = $nickname == null ?
$username : $nickname;
4473 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4474 $nickname = $username;
4475 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4476 } elseif ( $fancySig !== false ) {
4477 # Sig. might contain markup; validate this
4478 if ( $this->validateSig( $nickname ) !== false ) {
4479 # Validated; clean up (if needed) and return it
4480 return $this->cleanSig( $nickname, true );
4482 # Failed to validate; fall back to the default
4483 $nickname = $username;
4484 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4488 # Make sure nickname doesnt get a sig in a sig
4489 $nickname = self
::cleanSigInSig( $nickname );
4491 # If we're still here, make it a link to the user page
4492 $userText = wfEscapeWikiText( $username );
4493 $nickText = wfEscapeWikiText( $nickname );
4494 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4496 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4500 * Check that the user's signature contains no bad XML
4502 * @param $text String
4503 * @return mixed An expanded string, or false if invalid.
4505 function validateSig( $text ) {
4506 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4510 * Clean up signature text
4512 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4513 * 2) Substitute all transclusions
4515 * @param $text String
4516 * @param $parsing bool Whether we're cleaning (preferences save) or parsing
4517 * @return String: signature text
4519 public function cleanSig( $text, $parsing = false ) {
4522 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4525 # Option to disable this feature
4526 if ( !$this->mOptions
->getCleanSignatures() ) {
4530 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4531 # => Move this logic to braceSubstitution()
4532 $substWord = MagicWord
::get( 'subst' );
4533 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4534 $substText = '{{' . $substWord->getSynonym( 0 );
4536 $text = preg_replace( $substRegex, $substText, $text );
4537 $text = self
::cleanSigInSig( $text );
4538 $dom = $this->preprocessToDom( $text );
4539 $frame = $this->getPreprocessor()->newFrame();
4540 $text = $frame->expand( $dom );
4543 $text = $this->mStripState
->unstripBoth( $text );
4550 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4552 * @param $text String
4553 * @return String: signature text with /~{3,5}/ removed
4555 public static function cleanSigInSig( $text ) {
4556 $text = preg_replace( '/~{3,5}/', '', $text );
4561 * Set up some variables which are usually set up in parse()
4562 * so that an external function can call some class members with confidence
4564 * @param $title Title|null
4565 * @param $options ParserOptions
4566 * @param $outputType
4567 * @param $clearState bool
4569 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4570 $this->startParse( $title, $options, $outputType, $clearState );
4574 * @param $title Title|null
4575 * @param $options ParserOptions
4576 * @param $outputType
4577 * @param $clearState bool
4579 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4580 $this->setTitle( $title );
4581 $this->mOptions
= $options;
4582 $this->setOutputType( $outputType );
4583 if ( $clearState ) {
4584 $this->clearState();
4589 * Wrapper for preprocess()
4591 * @param $text String: the text to preprocess
4592 * @param $options ParserOptions: options
4593 * @param $title Title object or null to use $wgTitle
4596 public function transformMsg( $text, $options, $title = null ) {
4597 static $executing = false;
4599 # Guard against infinite recursion
4605 wfProfileIn( __METHOD__
);
4611 # It's not uncommon having a null $wgTitle in scripts. See r80898
4612 # Create a ghost title in such case
4613 $title = Title
::newFromText( 'Dwimmerlaik' );
4615 $text = $this->preprocess( $text, $title, $options );
4618 wfProfileOut( __METHOD__
);
4623 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4624 * The callback should have the following form:
4625 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4627 * Transform and return $text. Use $parser for any required context, e.g. use
4628 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4630 * Hooks may return extended information by returning an array, of which the
4631 * first numbered element (index 0) must be the return string, and all other
4632 * entries are extracted into local variables within an internal function
4633 * in the Parser class.
4635 * This interface (introduced r61913) appears to be undocumented, but
4636 * 'markerName' is used by some core tag hooks to override which strip
4637 * array their results are placed in. **Use great caution if attempting
4638 * this interface, as it is not documented and injudicious use could smash
4639 * private variables.**
4641 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4642 * @param $callback Mixed: the callback function (and object) to use for the tag
4643 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4645 public function setHook( $tag, $callback ) {
4646 $tag = strtolower( $tag );
4647 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4648 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4650 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4651 $this->mTagHooks
[$tag] = $callback;
4652 if ( !in_array( $tag, $this->mStripList
) ) {
4653 $this->mStripList
[] = $tag;
4660 * As setHook(), but letting the contents be parsed.
4662 * Transparent tag hooks are like regular XML-style tag hooks, except they
4663 * operate late in the transformation sequence, on HTML instead of wikitext.
4665 * This is probably obsoleted by things dealing with parser frames?
4666 * The only extension currently using it is geoserver.
4669 * @todo better document or deprecate this
4671 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4672 * @param $callback Mixed: the callback function (and object) to use for the tag
4673 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4675 function setTransparentTagHook( $tag, $callback ) {
4676 $tag = strtolower( $tag );
4677 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4678 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4680 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4681 $this->mTransparentTagHooks
[$tag] = $callback;
4687 * Remove all tag hooks
4689 function clearTagHooks() {
4690 $this->mTagHooks
= array();
4691 $this->mFunctionTagHooks
= array();
4692 $this->mStripList
= $this->mDefaultStripList
;
4696 * Create a function, e.g. {{sum:1|2|3}}
4697 * The callback function should have the form:
4698 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4700 * Or with SFH_OBJECT_ARGS:
4701 * function myParserFunction( $parser, $frame, $args ) { ... }
4703 * The callback may either return the text result of the function, or an array with the text
4704 * in element 0, and a number of flags in the other elements. The names of the flags are
4705 * specified in the keys. Valid flags are:
4706 * found The text returned is valid, stop processing the template. This
4708 * nowiki Wiki markup in the return value should be escaped
4709 * isHTML The returned text is HTML, armour it against wikitext transformation
4711 * @param $id String: The magic word ID
4712 * @param $callback Mixed: the callback function (and object) to use
4713 * @param $flags Integer: a combination of the following flags:
4714 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4716 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4717 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4718 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4719 * the arguments, and to control the way they are expanded.
4721 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4722 * arguments, for instance:
4723 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4725 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4726 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4727 * working if/when this is changed.
4729 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4732 * Please read the documentation in includes/parser/Preprocessor.php for more information
4733 * about the methods available in PPFrame and PPNode.
4735 * @return string|callback The old callback function for this name, if any
4737 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4740 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4741 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4743 # Add to function cache
4744 $mw = MagicWord
::get( $id );
4746 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4748 $synonyms = $mw->getSynonyms();
4749 $sensitive = intval( $mw->isCaseSensitive() );
4751 foreach ( $synonyms as $syn ) {
4753 if ( !$sensitive ) {
4754 $syn = $wgContLang->lc( $syn );
4757 if ( !( $flags & SFH_NO_HASH
) ) {
4760 # Remove trailing colon
4761 if ( substr( $syn, -1, 1 ) === ':' ) {
4762 $syn = substr( $syn, 0, -1 );
4764 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4770 * Get all registered function hook identifiers
4774 function getFunctionHooks() {
4775 return array_keys( $this->mFunctionHooks
);
4779 * Create a tag function, e.g. <test>some stuff</test>.
4780 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4781 * Unlike parser functions, their content is not preprocessed.
4784 function setFunctionTagHook( $tag, $callback, $flags ) {
4785 $tag = strtolower( $tag );
4786 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4787 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4788 $this->mFunctionTagHooks
[$tag] : null;
4789 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4791 if ( !in_array( $tag, $this->mStripList
) ) {
4792 $this->mStripList
[] = $tag;
4799 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
4800 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4801 * Placeholders created in Skin::makeLinkObj()
4803 * @param $text string
4804 * @param $options int
4806 * @return array of link CSS classes, indexed by PDBK.
4808 function replaceLinkHolders( &$text, $options = 0 ) {
4809 return $this->mLinkHolders
->replace( $text );
4813 * Replace <!--LINK--> link placeholders with plain text of links
4814 * (not HTML-formatted).
4816 * @param $text String
4819 function replaceLinkHoldersText( $text ) {
4820 return $this->mLinkHolders
->replaceText( $text );
4824 * Renders an image gallery from a text with one line per image.
4825 * text labels may be given by using |-style alternative text. E.g.
4826 * Image:one.jpg|The number "1"
4827 * Image:tree.jpg|A tree
4828 * given as text will return the HTML of a gallery with two images,
4829 * labeled 'The number "1"' and
4832 * @param string $text
4833 * @param array $params
4834 * @return string HTML
4836 function renderImageGallery( $text, $params ) {
4837 $ig = new ImageGallery();
4838 $ig->setContextTitle( $this->mTitle
);
4839 $ig->setShowBytes( false );
4840 $ig->setShowFilename( false );
4841 $ig->setParser( $this );
4842 $ig->setHideBadImages();
4843 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4845 if ( isset( $params['showfilename'] ) ) {
4846 $ig->setShowFilename( true );
4848 $ig->setShowFilename( false );
4850 if ( isset( $params['caption'] ) ) {
4851 $caption = $params['caption'];
4852 $caption = htmlspecialchars( $caption );
4853 $caption = $this->replaceInternalLinks( $caption );
4854 $ig->setCaptionHtml( $caption );
4856 if ( isset( $params['perrow'] ) ) {
4857 $ig->setPerRow( $params['perrow'] );
4859 if ( isset( $params['widths'] ) ) {
4860 $ig->setWidths( $params['widths'] );
4862 if ( isset( $params['heights'] ) ) {
4863 $ig->setHeights( $params['heights'] );
4866 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4868 $lines = StringUtils
::explode( "\n", $text );
4869 foreach ( $lines as $line ) {
4870 # match lines like these:
4871 # Image:someimage.jpg|This is some image
4873 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4875 if ( count( $matches ) == 0 ) {
4879 if ( strpos( $matches[0], '%' ) !== false ) {
4880 $matches[1] = rawurldecode( $matches[1] );
4882 $title = Title
::newFromText( $matches[1], NS_FILE
);
4883 if ( is_null( $title ) ) {
4884 # Bogus title. Ignore these so we don't bomb out later.
4891 if ( isset( $matches[3] ) ) {
4892 // look for an |alt= definition while trying not to break existing
4893 // captions with multiple pipes (|) in it, until a more sensible grammar
4894 // is defined for images in galleries
4896 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
4897 $parameterMatches = StringUtils
::explode('|', $matches[3]);
4898 $magicWordAlt = MagicWord
::get( 'img_alt' );
4899 $magicWordLink = MagicWord
::get( 'img_link' );
4901 foreach ( $parameterMatches as $parameterMatch ) {
4902 if ( $match = $magicWordAlt->matchVariableStartToEnd( $parameterMatch ) ) {
4903 $alt = $this->stripAltText( $match, false );
4905 elseif( $match = $magicWordLink->matchVariableStartToEnd( $parameterMatch ) ){
4906 $link = strip_tags($this->replaceLinkHoldersText($match));
4907 $chars = self
::EXT_LINK_URL_CLASS
;
4908 $prots = $this->mUrlProtocols
;
4909 //check to see if link matches an absolute url, if not then it must be a wiki link.
4910 if(!preg_match( "/^($prots)$chars+$/u", $link)){
4911 $localLinkTitle = Title
::newFromText($link);
4912 $link = $localLinkTitle->getLocalURL();
4916 // concatenate all other pipes
4917 $label .= '|' . $parameterMatch;
4920 // remove the first pipe
4921 $label = substr( $label, 1 );
4924 $ig->add( $title, $label, $alt ,$link);
4926 return $ig->toHTML();
4933 function getImageParams( $handler ) {
4935 $handlerClass = get_class( $handler );
4939 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4940 # Initialise static lists
4941 static $internalParamNames = array(
4942 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4943 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4944 'bottom', 'text-bottom' ),
4945 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4946 'upright', 'border', 'link', 'alt' ),
4948 static $internalParamMap;
4949 if ( !$internalParamMap ) {
4950 $internalParamMap = array();
4951 foreach ( $internalParamNames as $type => $names ) {
4952 foreach ( $names as $name ) {
4953 $magicName = str_replace( '-', '_', "img_$name" );
4954 $internalParamMap[$magicName] = array( $type, $name );
4959 # Add handler params
4960 $paramMap = $internalParamMap;
4962 $handlerParamMap = $handler->getParamMap();
4963 foreach ( $handlerParamMap as $magic => $paramName ) {
4964 $paramMap[$magic] = array( 'handler', $paramName );
4967 $this->mImageParams
[$handlerClass] = $paramMap;
4968 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4970 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4974 * Parse image options text and use it to make an image
4976 * @param $title Title
4977 * @param $options String
4978 * @param $holders LinkHolderArray|bool
4979 * @return string HTML
4981 function makeImage( $title, $options, $holders = false ) {
4982 # Check if the options text is of the form "options|alt text"
4984 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4985 # * left no resizing, just left align. label is used for alt= only
4986 # * right same, but right aligned
4987 # * none same, but not aligned
4988 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4989 # * center center the image
4990 # * frame Keep original image size, no magnify-button.
4991 # * framed Same as "frame"
4992 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4993 # * upright reduce width for upright images, rounded to full __0 px
4994 # * border draw a 1px border around the image
4995 # * alt Text for HTML alt attribute (defaults to empty)
4996 # * link Set the target of the image link. Can be external, interwiki, or local
4997 # vertical-align values (no % or length right now):
5007 $parts = StringUtils
::explode( "|", $options );
5009 # Give extensions a chance to select the file revision for us
5012 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5013 array( $this, $title, &$options, &$descQuery ) );
5014 # Fetch and register the file (file title may be different via hooks)
5015 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5018 $handler = $file ?
$file->getHandler() : false;
5020 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5023 $this->addTrackingCategory( 'broken-file-category' );
5026 # Process the input parameters
5028 $params = array( 'frame' => array(), 'handler' => array(),
5029 'horizAlign' => array(), 'vertAlign' => array() );
5030 foreach ( $parts as $part ) {
5031 $part = trim( $part );
5032 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5034 if ( isset( $paramMap[$magicName] ) ) {
5035 list( $type, $paramName ) = $paramMap[$magicName];
5037 # Special case; width and height come in one variable together
5038 if ( $type === 'handler' && $paramName === 'width' ) {
5039 $parsedWidthParam = $this->parseWidthParam( $value );
5040 if( isset( $parsedWidthParam['width'] ) ) {
5041 $width = $parsedWidthParam['width'];
5042 if ( $handler->validateParam( 'width', $width ) ) {
5043 $params[$type]['width'] = $width;
5047 if( isset( $parsedWidthParam['height'] ) ) {
5048 $height = $parsedWidthParam['height'];
5049 if ( $handler->validateParam( 'height', $height ) ) {
5050 $params[$type]['height'] = $height;
5054 # else no validation -- bug 13436
5056 if ( $type === 'handler' ) {
5057 # Validate handler parameter
5058 $validated = $handler->validateParam( $paramName, $value );
5060 # Validate internal parameters
5061 switch( $paramName ) {
5064 # @todo FIXME: Possibly check validity here for
5065 # manualthumb? downstream behavior seems odd with
5066 # missing manual thumbs.
5068 $value = $this->stripAltText( $value, $holders );
5071 $chars = self
::EXT_LINK_URL_CLASS
;
5072 $prots = $this->mUrlProtocols
;
5073 if ( $value === '' ) {
5074 $paramName = 'no-link';
5077 } elseif ( preg_match( "/^$prots/", $value ) ) {
5078 if ( preg_match( "/^($prots)$chars+$/u", $value, $m ) ) {
5079 $paramName = 'link-url';
5080 $this->mOutput
->addExternalLink( $value );
5081 if ( $this->mOptions
->getExternalLinkTarget() ) {
5082 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5087 $linkTitle = Title
::newFromText( $value );
5089 $paramName = 'link-title';
5090 $value = $linkTitle;
5091 $this->mOutput
->addLink( $linkTitle );
5097 # Most other things appear to be empty or numeric...
5098 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5103 $params[$type][$paramName] = $value;
5107 if ( !$validated ) {
5112 # Process alignment parameters
5113 if ( $params['horizAlign'] ) {
5114 $params['frame']['align'] = key( $params['horizAlign'] );
5116 if ( $params['vertAlign'] ) {
5117 $params['frame']['valign'] = key( $params['vertAlign'] );
5120 $params['frame']['caption'] = $caption;
5122 # Will the image be presented in a frame, with the caption below?
5123 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5124 isset( $params['frame']['framed'] ) ||
5125 isset( $params['frame']['thumbnail'] ) ||
5126 isset( $params['frame']['manualthumb'] );
5128 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5129 # came to also set the caption, ordinary text after the image -- which
5130 # makes no sense, because that just repeats the text multiple times in
5131 # screen readers. It *also* came to set the title attribute.
5133 # Now that we have an alt attribute, we should not set the alt text to
5134 # equal the caption: that's worse than useless, it just repeats the
5135 # text. This is the framed/thumbnail case. If there's no caption, we
5136 # use the unnamed parameter for alt text as well, just for the time be-
5137 # ing, if the unnamed param is set and the alt param is not.
5139 # For the future, we need to figure out if we want to tweak this more,
5140 # e.g., introducing a title= parameter for the title; ignoring the un-
5141 # named parameter entirely for images without a caption; adding an ex-
5142 # plicit caption= parameter and preserving the old magic unnamed para-
5144 if ( $imageIsFramed ) { # Framed image
5145 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5146 # No caption or alt text, add the filename as the alt text so
5147 # that screen readers at least get some description of the image
5148 $params['frame']['alt'] = $title->getText();
5150 # Do not set $params['frame']['title'] because tooltips don't make sense
5152 } else { # Inline image
5153 if ( !isset( $params['frame']['alt'] ) ) {
5154 # No alt text, use the "caption" for the alt text
5155 if ( $caption !== '') {
5156 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5158 # No caption, fall back to using the filename for the
5160 $params['frame']['alt'] = $title->getText();
5163 # Use the "caption" for the tooltip text
5164 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5167 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5169 # Linker does the rest
5170 $time = isset( $options['time'] ) ?
$options['time'] : false;
5171 $ret = Linker
::makeImageLink2( $title, $file, $params['frame'], $params['handler'],
5172 $time, $descQuery, $this->mOptions
->getThumbSize() );
5174 # Give the handler a chance to modify the parser object
5176 $handler->parserTransformHook( $this, $file );
5184 * @param $holders LinkHolderArray
5185 * @return mixed|String
5187 protected function stripAltText( $caption, $holders ) {
5188 # Strip bad stuff out of the title (tooltip). We can't just use
5189 # replaceLinkHoldersText() here, because if this function is called
5190 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5192 $tooltip = $holders->replaceText( $caption );
5194 $tooltip = $this->replaceLinkHoldersText( $caption );
5197 # make sure there are no placeholders in thumbnail attributes
5198 # that are later expanded to html- so expand them now and
5200 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5201 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5207 * Set a flag in the output object indicating that the content is dynamic and
5208 * shouldn't be cached.
5210 function disableCache() {
5211 wfDebug( "Parser output marked as uncacheable.\n" );
5212 if ( !$this->mOutput
) {
5213 throw new MWException( __METHOD__
.
5214 " can only be called when actually parsing something" );
5216 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5217 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5221 * Callback from the Sanitizer for expanding items found in HTML attribute
5222 * values, so they can be safely tested and escaped.
5224 * @param $text String
5225 * @param $frame PPFrame
5228 function attributeStripCallback( &$text, $frame = false ) {
5229 $text = $this->replaceVariables( $text, $frame );
5230 $text = $this->mStripState
->unstripBoth( $text );
5239 function getTags() {
5240 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
), array_keys( $this->mFunctionTagHooks
) );
5244 * Replace transparent tags in $text with the values given by the callbacks.
5246 * Transparent tag hooks are like regular XML-style tag hooks, except they
5247 * operate late in the transformation sequence, on HTML instead of wikitext.
5249 * @param $text string
5253 function replaceTransparentTags( $text ) {
5255 $elements = array_keys( $this->mTransparentTagHooks
);
5256 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5257 $replacements = array();
5259 foreach ( $matches as $marker => $data ) {
5260 list( $element, $content, $params, $tag ) = $data;
5261 $tagName = strtolower( $element );
5262 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5263 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
5267 $replacements[$marker] = $output;
5269 return strtr( $text, $replacements );
5273 * Break wikitext input into sections, and either pull or replace
5274 * some particular section's text.
5276 * External callers should use the getSection and replaceSection methods.
5278 * @param $text String: Page wikitext
5279 * @param $section String: a section identifier string of the form:
5280 * <flag1> - <flag2> - ... - <section number>
5282 * Currently the only recognised flag is "T", which means the target section number
5283 * was derived during a template inclusion parse, in other words this is a template
5284 * section edit link. If no flags are given, it was an ordinary section edit link.
5285 * This flag is required to avoid a section numbering mismatch when a section is
5286 * enclosed by <includeonly> (bug 6563).
5288 * The section number 0 pulls the text before the first heading; other numbers will
5289 * pull the given section along with its lower-level subsections. If the section is
5290 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5292 * Section 0 is always considered to exist, even if it only contains the empty
5293 * string. If $text is the empty string and section 0 is replaced, $newText is
5296 * @param $mode String: one of "get" or "replace"
5297 * @param $newText String: replacement text for section data.
5298 * @return String: for "get", the extracted section text.
5299 * for "replace", the whole page with the section replaced.
5301 private function extractSections( $text, $section, $mode, $newText='' ) {
5302 global $wgTitle; # not generally used but removes an ugly failure mode
5303 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5305 $frame = $this->getPreprocessor()->newFrame();
5307 # Process section extraction flags
5309 $sectionParts = explode( '-', $section );
5310 $sectionIndex = array_pop( $sectionParts );
5311 foreach ( $sectionParts as $part ) {
5312 if ( $part === 'T' ) {
5313 $flags |
= self
::PTD_FOR_INCLUSION
;
5317 # Check for empty input
5318 if ( strval( $text ) === '' ) {
5319 # Only sections 0 and T-0 exist in an empty document
5320 if ( $sectionIndex == 0 ) {
5321 if ( $mode === 'get' ) {
5327 if ( $mode === 'get' ) {
5335 # Preprocess the text
5336 $root = $this->preprocessToDom( $text, $flags );
5338 # <h> nodes indicate section breaks
5339 # They can only occur at the top level, so we can find them by iterating the root's children
5340 $node = $root->getFirstChild();
5342 # Find the target section
5343 if ( $sectionIndex == 0 ) {
5344 # Section zero doesn't nest, level=big
5345 $targetLevel = 1000;
5348 if ( $node->getName() === 'h' ) {
5349 $bits = $node->splitHeading();
5350 if ( $bits['i'] == $sectionIndex ) {
5351 $targetLevel = $bits['level'];
5355 if ( $mode === 'replace' ) {
5356 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5358 $node = $node->getNextSibling();
5364 if ( $mode === 'get' ) {
5371 # Find the end of the section, including nested sections
5373 if ( $node->getName() === 'h' ) {
5374 $bits = $node->splitHeading();
5375 $curLevel = $bits['level'];
5376 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5380 if ( $mode === 'get' ) {
5381 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5383 $node = $node->getNextSibling();
5386 # Write out the remainder (in replace mode only)
5387 if ( $mode === 'replace' ) {
5388 # Output the replacement text
5389 # Add two newlines on -- trailing whitespace in $newText is conventionally
5390 # stripped by the editor, so we need both newlines to restore the paragraph gap
5391 # Only add trailing whitespace if there is newText
5392 if ( $newText != "" ) {
5393 $outText .= $newText . "\n\n";
5397 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5398 $node = $node->getNextSibling();
5402 if ( is_string( $outText ) ) {
5403 # Re-insert stripped tags
5404 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5411 * This function returns the text of a section, specified by a number ($section).
5412 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5413 * the first section before any such heading (section 0).
5415 * If a section contains subsections, these are also returned.
5417 * @param $text String: text to look in
5418 * @param $section String: section identifier
5419 * @param $deftext String: default to return if section is not found
5420 * @return string text of the requested section
5422 public function getSection( $text, $section, $deftext='' ) {
5423 return $this->extractSections( $text, $section, "get", $deftext );
5427 * This function returns $oldtext after the content of the section
5428 * specified by $section has been replaced with $text. If the target
5429 * section does not exist, $oldtext is returned unchanged.
5431 * @param $oldtext String: former text of the article
5432 * @param $section int section identifier
5433 * @param $text String: replacing text
5434 * @return String: modified text
5436 public function replaceSection( $oldtext, $section, $text ) {
5437 return $this->extractSections( $oldtext, $section, "replace", $text );
5441 * Get the ID of the revision we are parsing
5443 * @return Mixed: integer or null
5445 function getRevisionId() {
5446 return $this->mRevisionId
;
5450 * Get the revision object for $this->mRevisionId
5452 * @return Revision|null either a Revision object or null
5454 protected function getRevisionObject() {
5455 if ( !is_null( $this->mRevisionObject
) ) {
5456 return $this->mRevisionObject
;
5458 if ( is_null( $this->mRevisionId
) ) {
5462 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5463 return $this->mRevisionObject
;
5467 * Get the timestamp associated with the current revision, adjusted for
5468 * the default server-local timestamp
5470 function getRevisionTimestamp() {
5471 if ( is_null( $this->mRevisionTimestamp
) ) {
5472 wfProfileIn( __METHOD__
);
5476 $revObject = $this->getRevisionObject();
5477 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5479 # The cryptic '' timezone parameter tells to use the site-default
5480 # timezone offset instead of the user settings.
5482 # Since this value will be saved into the parser cache, served
5483 # to other users, and potentially even used inside links and such,
5484 # it needs to be consistent for all visitors.
5485 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5487 wfProfileOut( __METHOD__
);
5489 return $this->mRevisionTimestamp
;
5493 * Get the name of the user that edited the last revision
5495 * @return String: user name
5497 function getRevisionUser() {
5498 if( is_null( $this->mRevisionUser
) ) {
5499 $revObject = $this->getRevisionObject();
5501 # if this template is subst: the revision id will be blank,
5502 # so just use the current user's name
5504 $this->mRevisionUser
= $revObject->getUserText();
5505 } elseif( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5506 $this->mRevisionUser
= $this->getUser()->getName();
5509 return $this->mRevisionUser
;
5513 * Mutator for $mDefaultSort
5515 * @param $sort string New value
5517 public function setDefaultSort( $sort ) {
5518 $this->mDefaultSort
= $sort;
5519 $this->mOutput
->setProperty( 'defaultsort', $sort );
5523 * Accessor for $mDefaultSort
5524 * Will use the empty string if none is set.
5526 * This value is treated as a prefix, so the
5527 * empty string is equivalent to sorting by
5532 public function getDefaultSort() {
5533 if ( $this->mDefaultSort
!== false ) {
5534 return $this->mDefaultSort
;
5541 * Accessor for $mDefaultSort
5542 * Unlike getDefaultSort(), will return false if none is set
5544 * @return string or false
5546 public function getCustomDefaultSort() {
5547 return $this->mDefaultSort
;
5551 * Try to guess the section anchor name based on a wikitext fragment
5552 * presumably extracted from a heading, for example "Header" from
5555 * @param $text string
5559 public function guessSectionNameFromWikiText( $text ) {
5560 # Strip out wikitext links(they break the anchor)
5561 $text = $this->stripSectionName( $text );
5562 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5563 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5567 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5568 * instead. For use in redirects, since IE6 interprets Redirect: headers
5569 * as something other than UTF-8 (apparently?), resulting in breakage.
5571 * @param $text String: The section name
5572 * @return string An anchor
5574 public function guessLegacySectionNameFromWikiText( $text ) {
5575 # Strip out wikitext links(they break the anchor)
5576 $text = $this->stripSectionName( $text );
5577 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5578 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5582 * Strips a text string of wikitext for use in a section anchor
5584 * Accepts a text string and then removes all wikitext from the
5585 * string and leaves only the resultant text (i.e. the result of
5586 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5587 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5588 * to create valid section anchors by mimicing the output of the
5589 * parser when headings are parsed.
5591 * @param $text String: text string to be stripped of wikitext
5592 * for use in a Section anchor
5593 * @return string Filtered text string
5595 public function stripSectionName( $text ) {
5596 # Strip internal link markup
5597 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5598 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5600 # Strip external link markup
5601 # @todo FIXME: Not tolerant to blank link text
5602 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5603 # on how many empty links there are on the page - need to figure that out.
5604 $text = preg_replace( '/\[(?:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5606 # Parse wikitext quotes (italics & bold)
5607 $text = $this->doQuotes( $text );
5610 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5615 * strip/replaceVariables/unstrip for preprocessor regression testing
5617 * @param $text string
5618 * @param $title Title
5619 * @param $options ParserOptions
5620 * @param $outputType int
5624 function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5625 $this->startParse( $title, $options, $outputType, true );
5627 $text = $this->replaceVariables( $text );
5628 $text = $this->mStripState
->unstripBoth( $text );
5629 $text = Sanitizer
::removeHTMLtags( $text );
5634 * @param $text string
5635 * @param $title Title
5636 * @param $options ParserOptions
5639 function testPst( $text, Title
$title, ParserOptions
$options ) {
5640 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5645 * @param $title Title
5646 * @param $options ParserOptions
5649 function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5650 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5654 * Call a callback function on all regions of the given text that are not
5655 * inside strip markers, and replace those regions with the return value
5656 * of the callback. For example, with input:
5660 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5661 * two strings will be replaced with the value returned by the callback in
5669 function markerSkipCallback( $s, $callback ) {
5672 while ( $i < strlen( $s ) ) {
5673 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5674 if ( $markerStart === false ) {
5675 $out .= call_user_func( $callback, substr( $s, $i ) );
5678 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5679 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5680 if ( $markerEnd === false ) {
5681 $out .= substr( $s, $markerStart );
5684 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5685 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5694 * Remove any strip markers found in the given text.
5696 * @param $text Input string
5699 function killMarkers( $text ) {
5700 return $this->mStripState
->killMarkers( $text );
5704 * Save the parser state required to convert the given half-parsed text to
5705 * HTML. "Half-parsed" in this context means the output of
5706 * recursiveTagParse() or internalParse(). This output has strip markers
5707 * from replaceVariables (extensionSubstitution() etc.), and link
5708 * placeholders from replaceLinkHolders().
5710 * Returns an array which can be serialized and stored persistently. This
5711 * array can later be loaded into another parser instance with
5712 * unserializeHalfParsedText(). The text can then be safely incorporated into
5713 * the return value of a parser hook.
5715 * @param $text string
5719 function serializeHalfParsedText( $text ) {
5720 wfProfileIn( __METHOD__
);
5723 'version' => self
::HALF_PARSED_VERSION
,
5724 'stripState' => $this->mStripState
->getSubState( $text ),
5725 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
5727 wfProfileOut( __METHOD__
);
5732 * Load the parser state given in the $data array, which is assumed to
5733 * have been generated by serializeHalfParsedText(). The text contents is
5734 * extracted from the array, and its markers are transformed into markers
5735 * appropriate for the current Parser instance. This transformed text is
5736 * returned, and can be safely included in the return value of a parser
5739 * If the $data array has been stored persistently, the caller should first
5740 * check whether it is still valid, by calling isValidHalfParsedText().
5742 * @param $data array Serialized data
5745 function unserializeHalfParsedText( $data ) {
5746 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
5747 throw new MWException( __METHOD__
.': invalid version' );
5750 # First, extract the strip state.
5751 $texts = array( $data['text'] );
5752 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
5754 # Now renumber links
5755 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
5757 # Should be good to go.
5762 * Returns true if the given array, presumed to be generated by
5763 * serializeHalfParsedText(), is compatible with the current version of the
5766 * @param $data Array
5770 function isValidHalfParsedText( $data ) {
5771 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;
5775 * Parsed a width param of imagelink like 300px or 200x300px
5777 * @param $value String
5782 public function parseWidthParam( $value ) {
5783 $parsedWidthParam = array();
5784 if( $value === '' ) {
5785 return $parsedWidthParam;
5788 # (bug 13500) In both cases (width/height and width only),
5789 # permit trailing "px" for backward compatibility.
5790 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
5791 $width = intval( $m[1] );
5792 $height = intval( $m[2] );
5793 $parsedWidthParam['width'] = $width;
5794 $parsedWidthParam['height'] = $height;
5795 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
5796 $width = intval( $value );
5797 $parsedWidthParam['width'] = $width;
5799 return $parsedWidthParam;