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 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1126 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1128 # Tables need to come after variable replacement for things to work
1129 # properly; putting them before other transformations should keep
1130 # exciting things like link expansions from showing up in surprising
1132 $text = $this->doTableStuff( $text );
1134 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1136 $text = $this->doDoubleUnderscore( $text );
1138 $text = $this->doHeadings( $text );
1139 if ( $this->mOptions
->getUseDynamicDates() ) {
1140 $df = DateFormatter
::getInstance();
1141 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1143 $text = $this->replaceInternalLinks( $text );
1144 $text = $this->doAllQuotes( $text );
1145 $text = $this->replaceExternalLinks( $text );
1147 # replaceInternalLinks may sometimes leave behind
1148 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1149 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
1151 $text = $this->doMagicLinks( $text );
1152 $text = $this->formatHeadings( $text, $origText, $isMain );
1154 wfProfileOut( __METHOD__
);
1159 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1160 * magic external links.
1165 * @param $text string
1169 function doMagicLinks( $text ) {
1170 wfProfileIn( __METHOD__
);
1171 $prots = wfUrlProtocolsWithoutProtRel();
1172 $urlChar = self
::EXT_LINK_URL_CLASS
;
1173 $text = preg_replace_callback(
1175 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1176 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1177 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1178 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1179 ISBN\s+(\b # m[5]: ISBN, capture number
1180 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1181 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1182 [0-9Xx] # check digit
1184 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1185 wfProfileOut( __METHOD__
);
1190 * @throws MWException
1192 * @return HTML|string
1194 function magicLinkCallback( $m ) {
1195 if ( isset( $m[1] ) && $m[1] !== '' ) {
1198 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1201 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1202 # Free external link
1203 return $this->makeFreeExternalLink( $m[0] );
1204 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1206 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1209 $CssClass = 'mw-magiclink-rfc';
1211 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1213 $urlmsg = 'pubmedurl';
1214 $CssClass = 'mw-magiclink-pmid';
1217 throw new MWException( __METHOD__
.': unrecognised match type "' .
1218 substr( $m[0], 0, 20 ) . '"' );
1220 $url = wfMsgForContent( $urlmsg, $id );
1221 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1222 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1225 $num = strtr( $isbn, array(
1230 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1232 htmlspecialchars( $titleObj->getLocalUrl() ) .
1233 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1240 * Make a free external link, given a user-supplied URL
1242 * @param $url string
1244 * @return string HTML
1247 function makeFreeExternalLink( $url ) {
1248 wfProfileIn( __METHOD__
);
1252 # The characters '<' and '>' (which were escaped by
1253 # removeHTMLtags()) should not be included in
1254 # URLs, per RFC 2396.
1256 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1257 $trail = substr( $url, $m2[0][1] ) . $trail;
1258 $url = substr( $url, 0, $m2[0][1] );
1261 # Move trailing punctuation to $trail
1263 # If there is no left bracket, then consider right brackets fair game too
1264 if ( strpos( $url, '(' ) === false ) {
1268 $numSepChars = strspn( strrev( $url ), $sep );
1269 if ( $numSepChars ) {
1270 $trail = substr( $url, -$numSepChars ) . $trail;
1271 $url = substr( $url, 0, -$numSepChars );
1274 $url = Sanitizer
::cleanUrl( $url );
1276 # Is this an external image?
1277 $text = $this->maybeMakeExternalImage( $url );
1278 if ( $text === false ) {
1279 # Not an image, make a link
1280 $text = Linker
::makeExternalLink( $url,
1281 $this->getConverterLanguage()->markNoConversion($url), true, 'free',
1282 $this->getExternalLinkAttribs( $url ) );
1283 # Register it in the output object...
1284 # Replace unnecessary URL escape codes with their equivalent characters
1285 $pasteurized = self
::replaceUnusualEscapes( $url );
1286 $this->mOutput
->addExternalLink( $pasteurized );
1288 wfProfileOut( __METHOD__
);
1289 return $text . $trail;
1294 * Parse headers and return html
1298 * @param $text string
1302 function doHeadings( $text ) {
1303 wfProfileIn( __METHOD__
);
1304 for ( $i = 6; $i >= 1; --$i ) {
1305 $h = str_repeat( '=', $i );
1306 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1307 "<h$i>\\1</h$i>", $text );
1309 wfProfileOut( __METHOD__
);
1314 * Replace single quotes with HTML markup
1317 * @param $text string
1319 * @return string the altered text
1321 function doAllQuotes( $text ) {
1322 wfProfileIn( __METHOD__
);
1324 $lines = StringUtils
::explode( "\n", $text );
1325 foreach ( $lines as $line ) {
1326 $outtext .= $this->doQuotes( $line ) . "\n";
1328 $outtext = substr( $outtext, 0,-1 );
1329 wfProfileOut( __METHOD__
);
1334 * Helper function for doAllQuotes()
1336 * @param $text string
1340 public function doQuotes( $text ) {
1341 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1342 if ( count( $arr ) == 1 ) {
1345 # First, do some preliminary work. This may shift some apostrophes from
1346 # being mark-up to being text. It also counts the number of occurrences
1347 # of bold and italics mark-ups.
1350 for ( $i = 0; $i < count( $arr ); $i++
) {
1351 if ( ( $i %
2 ) == 1 ) {
1352 # If there are ever four apostrophes, assume the first is supposed to
1353 # be text, and the remaining three constitute mark-up for bold text.
1354 if ( strlen( $arr[$i] ) == 4 ) {
1357 } elseif ( strlen( $arr[$i] ) > 5 ) {
1358 # If there are more than 5 apostrophes in a row, assume they're all
1359 # text except for the last 5.
1360 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1363 # Count the number of occurrences of bold and italics mark-ups.
1364 # We are not counting sequences of five apostrophes.
1365 if ( strlen( $arr[$i] ) == 2 ) {
1367 } elseif ( strlen( $arr[$i] ) == 3 ) {
1369 } elseif ( strlen( $arr[$i] ) == 5 ) {
1376 # If there is an odd number of both bold and italics, it is likely
1377 # that one of the bold ones was meant to be an apostrophe followed
1378 # by italics. Which one we cannot know for certain, but it is more
1379 # likely to be one that has a single-letter word before it.
1380 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1382 $firstsingleletterword = -1;
1383 $firstmultiletterword = -1;
1385 foreach ( $arr as $r ) {
1386 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1387 $x1 = substr( $arr[$i-1], -1 );
1388 $x2 = substr( $arr[$i-1], -2, 1 );
1389 if ( $x1 === ' ' ) {
1390 if ( $firstspace == -1 ) {
1393 } elseif ( $x2 === ' ') {
1394 if ( $firstsingleletterword == -1 ) {
1395 $firstsingleletterword = $i;
1398 if ( $firstmultiletterword == -1 ) {
1399 $firstmultiletterword = $i;
1406 # If there is a single-letter word, use it!
1407 if ( $firstsingleletterword > -1 ) {
1408 $arr[$firstsingleletterword] = "''";
1409 $arr[$firstsingleletterword-1] .= "'";
1410 } elseif ( $firstmultiletterword > -1 ) {
1411 # If not, but there's a multi-letter word, use that one.
1412 $arr[$firstmultiletterword] = "''";
1413 $arr[$firstmultiletterword-1] .= "'";
1414 } elseif ( $firstspace > -1 ) {
1415 # ... otherwise use the first one that has neither.
1416 # (notice that it is possible for all three to be -1 if, for example,
1417 # there is only one pentuple-apostrophe in the line)
1418 $arr[$firstspace] = "''";
1419 $arr[$firstspace-1] .= "'";
1423 # Now let's actually convert our apostrophic mush to HTML!
1428 foreach ( $arr as $r ) {
1429 if ( ( $i %
2 ) == 0 ) {
1430 if ( $state === 'both' ) {
1436 if ( strlen( $r ) == 2 ) {
1437 if ( $state === 'i' ) {
1438 $output .= '</i>'; $state = '';
1439 } elseif ( $state === 'bi' ) {
1440 $output .= '</i>'; $state = 'b';
1441 } elseif ( $state === 'ib' ) {
1442 $output .= '</b></i><b>'; $state = 'b';
1443 } elseif ( $state === 'both' ) {
1444 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1445 } else { # $state can be 'b' or ''
1446 $output .= '<i>'; $state .= 'i';
1448 } elseif ( strlen( $r ) == 3 ) {
1449 if ( $state === 'b' ) {
1450 $output .= '</b>'; $state = '';
1451 } elseif ( $state === 'bi' ) {
1452 $output .= '</i></b><i>'; $state = 'i';
1453 } elseif ( $state === 'ib' ) {
1454 $output .= '</b>'; $state = 'i';
1455 } elseif ( $state === 'both' ) {
1456 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1457 } else { # $state can be 'i' or ''
1458 $output .= '<b>'; $state .= 'b';
1460 } elseif ( strlen( $r ) == 5 ) {
1461 if ( $state === 'b' ) {
1462 $output .= '</b><i>'; $state = 'i';
1463 } elseif ( $state === 'i' ) {
1464 $output .= '</i><b>'; $state = 'b';
1465 } elseif ( $state === 'bi' ) {
1466 $output .= '</i></b>'; $state = '';
1467 } elseif ( $state === 'ib' ) {
1468 $output .= '</b></i>'; $state = '';
1469 } elseif ( $state === 'both' ) {
1470 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1471 } else { # ($state == '')
1472 $buffer = ''; $state = 'both';
1478 # Now close all remaining tags. Notice that the order is important.
1479 if ( $state === 'b' ||
$state === 'ib' ) {
1482 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1485 if ( $state === 'bi' ) {
1488 # There might be lonely ''''', so make sure we have a buffer
1489 if ( $state === 'both' && $buffer ) {
1490 $output .= '<b><i>'.$buffer.'</i></b>';
1497 * Replace external links (REL)
1499 * Note: this is all very hackish and the order of execution matters a lot.
1500 * Make sure to run maintenance/parserTests.php if you change this code.
1504 * @param $text string
1508 function replaceExternalLinks( $text ) {
1509 wfProfileIn( __METHOD__
);
1511 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1512 $s = array_shift( $bits );
1515 while ( $i<count( $bits ) ) {
1517 $protocol = $bits[$i++
];
1518 $text = $bits[$i++
];
1519 $trail = $bits[$i++
];
1521 # The characters '<' and '>' (which were escaped by
1522 # removeHTMLtags()) should not be included in
1523 # URLs, per RFC 2396.
1525 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1526 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1527 $url = substr( $url, 0, $m2[0][1] );
1530 # If the link text is an image URL, replace it with an <img> tag
1531 # This happened by accident in the original parser, but some people used it extensively
1532 $img = $this->maybeMakeExternalImage( $text );
1533 if ( $img !== false ) {
1539 # Set linktype for CSS - if URL==text, link is essentially free
1540 $linktype = ( $text === $url ) ?
'free' : 'text';
1542 # No link text, e.g. [http://domain.tld/some.link]
1543 if ( $text == '' ) {
1545 $langObj = $this->getTargetLanguage();
1546 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1547 $linktype = 'autonumber';
1549 # Have link text, e.g. [http://domain.tld/some.link text]s
1551 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1554 $text = $this->getConverterLanguage()->markNoConversion( $text );
1556 $url = Sanitizer
::cleanUrl( $url );
1558 # Use the encoded URL
1559 # This means that users can paste URLs directly into the text
1560 # Funny characters like ö aren't valid in URLs anyway
1561 # This was changed in August 2004
1562 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1563 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1565 # Register link in the output object.
1566 # Replace unnecessary URL escape codes with the referenced character
1567 # This prevents spammers from hiding links from the filters
1568 $pasteurized = self
::replaceUnusualEscapes( $url );
1569 $this->mOutput
->addExternalLink( $pasteurized );
1572 wfProfileOut( __METHOD__
);
1577 * Get an associative array of additional HTML attributes appropriate for a
1578 * particular external link. This currently may include rel => nofollow
1579 * (depending on configuration, namespace, and the URL's domain) and/or a
1580 * target attribute (depending on configuration).
1582 * @param $url String|bool optional URL, to extract the domain from for rel =>
1583 * nofollow if appropriate
1584 * @return Array associative array of HTML attributes
1586 function getExternalLinkAttribs( $url = false ) {
1588 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1589 $ns = $this->mTitle
->getNamespace();
1590 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) &&
1591 !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions ) )
1593 $attribs['rel'] = 'nofollow';
1595 if ( $this->mOptions
->getExternalLinkTarget() ) {
1596 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1602 * Replace unusual URL escape codes with their equivalent characters
1604 * @param $url String
1607 * @todo This can merge genuinely required bits in the path or query string,
1608 * breaking legit URLs. A proper fix would treat the various parts of
1609 * the URL differently; as a workaround, just use the output for
1610 * statistical records, not for actual linking/output.
1612 static function replaceUnusualEscapes( $url ) {
1613 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1614 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1618 * Callback function used in replaceUnusualEscapes().
1619 * Replaces unusual URL escape codes with their equivalent character
1621 * @param $matches array
1625 private static function replaceUnusualEscapesCallback( $matches ) {
1626 $char = urldecode( $matches[0] );
1627 $ord = ord( $char );
1628 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1629 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1630 # No, shouldn't be escaped
1633 # Yes, leave it escaped
1639 * make an image if it's allowed, either through the global
1640 * option, through the exception, or through the on-wiki whitelist
1643 * $param $url string
1647 function maybeMakeExternalImage( $url ) {
1648 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1649 $imagesexception = !empty( $imagesfrom );
1651 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1652 if ( $imagesexception && is_array( $imagesfrom ) ) {
1653 $imagematch = false;
1654 foreach ( $imagesfrom as $match ) {
1655 if ( strpos( $url, $match ) === 0 ) {
1660 } elseif ( $imagesexception ) {
1661 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1663 $imagematch = false;
1665 if ( $this->mOptions
->getAllowExternalImages()
1666 ||
( $imagesexception && $imagematch ) ) {
1667 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1669 $text = Linker
::makeExternalImage( $url );
1672 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1673 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1674 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1675 foreach ( $whitelist as $entry ) {
1676 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1677 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1680 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1681 # Image matches a whitelist entry
1682 $text = Linker
::makeExternalImage( $url );
1691 * Process [[ ]] wikilinks
1695 * @return String: processed text
1699 function replaceInternalLinks( $s ) {
1700 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1705 * Process [[ ]] wikilinks (RIL)
1706 * @return LinkHolderArray
1710 function replaceInternalLinks2( &$s ) {
1711 wfProfileIn( __METHOD__
);
1713 wfProfileIn( __METHOD__
.'-setup' );
1714 static $tc = FALSE, $e1, $e1_img;
1715 # the % is needed to support urlencoded titles as well
1717 $tc = Title
::legalChars() . '#%';
1718 # Match a link having the form [[namespace:link|alternate]]trail
1719 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1720 # Match cases where there is no "]]", which might still be images
1721 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1724 $holders = new LinkHolderArray( $this );
1726 # split the entire text string on occurrences of [[
1727 $a = StringUtils
::explode( '[[', ' ' . $s );
1728 # get the first element (all text up to first [[), and remove the space we added
1731 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1732 $s = substr( $s, 1 );
1734 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1736 if ( $useLinkPrefixExtension ) {
1737 # Match the end of a line for a word that's not followed by whitespace,
1738 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1739 $e2 = wfMsgForContent( 'linkprefix' );
1742 if ( is_null( $this->mTitle
) ) {
1743 wfProfileOut( __METHOD__
.'-setup' );
1744 wfProfileOut( __METHOD__
);
1745 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1747 $nottalk = !$this->mTitle
->isTalkPage();
1749 if ( $useLinkPrefixExtension ) {
1751 if ( preg_match( $e2, $s, $m ) ) {
1752 $first_prefix = $m[2];
1754 $first_prefix = false;
1760 if ( $this->getConverterLanguage()->hasVariants() ) {
1761 $selflink = $this->getConverterLanguage()->autoConvertToAllVariants(
1762 $this->mTitle
->getPrefixedText() );
1764 $selflink = array( $this->mTitle
->getPrefixedText() );
1766 $useSubpages = $this->areSubpagesAllowed();
1767 wfProfileOut( __METHOD__
.'-setup' );
1769 # Loop for each link
1770 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1771 # Check for excessive memory usage
1772 if ( $holders->isBig() ) {
1774 # Do the existence check, replace the link holders and clear the array
1775 $holders->replace( $s );
1779 if ( $useLinkPrefixExtension ) {
1780 wfProfileIn( __METHOD__
.'-prefixhandling' );
1781 if ( preg_match( $e2, $s, $m ) ) {
1788 if ( $first_prefix ) {
1789 $prefix = $first_prefix;
1790 $first_prefix = false;
1792 wfProfileOut( __METHOD__
.'-prefixhandling' );
1795 $might_be_img = false;
1797 wfProfileIn( __METHOD__
."-e1" );
1798 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1800 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1801 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1802 # the real problem is with the $e1 regex
1805 # Still some problems for cases where the ] is meant to be outside punctuation,
1806 # and no image is in sight. See bug 2095.
1808 if ( $text !== '' &&
1809 substr( $m[3], 0, 1 ) === ']' &&
1810 strpos( $text, '[' ) !== false
1813 $text .= ']'; # so that replaceExternalLinks($text) works later
1814 $m[3] = substr( $m[3], 1 );
1816 # fix up urlencoded title texts
1817 if ( strpos( $m[1], '%' ) !== false ) {
1818 # Should anchors '#' also be rejected?
1819 $m[1] = str_replace( array('<', '>'), array('<', '>'), rawurldecode( $m[1] ) );
1822 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1823 $might_be_img = true;
1825 if ( strpos( $m[1], '%' ) !== false ) {
1826 $m[1] = rawurldecode( $m[1] );
1829 } else { # Invalid form; output directly
1830 $s .= $prefix . '[[' . $line ;
1831 wfProfileOut( __METHOD__
."-e1" );
1834 wfProfileOut( __METHOD__
."-e1" );
1835 wfProfileIn( __METHOD__
."-misc" );
1837 # Don't allow internal links to pages containing
1838 # PROTO: where PROTO is a valid URL protocol; these
1839 # should be external links.
1840 if ( preg_match( '/^(?:' . $this->mUrlProtocols
. ')/', $m[1] ) ) {
1841 $s .= $prefix . '[[' . $line ;
1842 wfProfileOut( __METHOD__
."-misc" );
1846 # Make subpage if necessary
1847 if ( $useSubpages ) {
1848 $link = $this->maybeDoSubpageLink( $m[1], $text );
1853 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1855 # Strip off leading ':'
1856 $link = substr( $link, 1 );
1859 wfProfileOut( __METHOD__
."-misc" );
1860 wfProfileIn( __METHOD__
."-title" );
1861 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1862 if ( $nt === null ) {
1863 $s .= $prefix . '[[' . $line;
1864 wfProfileOut( __METHOD__
."-title" );
1868 $ns = $nt->getNamespace();
1869 $iw = $nt->getInterWiki();
1870 wfProfileOut( __METHOD__
."-title" );
1872 if ( $might_be_img ) { # if this is actually an invalid link
1873 wfProfileIn( __METHOD__
."-might_be_img" );
1874 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1877 # look at the next 'line' to see if we can close it there
1879 $next_line = $a->current();
1880 if ( $next_line === false ||
$next_line === null ) {
1883 $m = explode( ']]', $next_line, 3 );
1884 if ( count( $m ) == 3 ) {
1885 # the first ]] closes the inner link, the second the image
1887 $text .= "[[{$m[0]}]]{$m[1]}";
1890 } elseif ( count( $m ) == 2 ) {
1891 # if there's exactly one ]] that's fine, we'll keep looking
1892 $text .= "[[{$m[0]}]]{$m[1]}";
1894 # if $next_line is invalid too, we need look no further
1895 $text .= '[[' . $next_line;
1900 # we couldn't find the end of this imageLink, so output it raw
1901 # but don't ignore what might be perfectly normal links in the text we've examined
1902 $holders->merge( $this->replaceInternalLinks2( $text ) );
1903 $s .= "{$prefix}[[$link|$text";
1904 # note: no $trail, because without an end, there *is* no trail
1905 wfProfileOut( __METHOD__
."-might_be_img" );
1908 } else { # it's not an image, so output it raw
1909 $s .= "{$prefix}[[$link|$text";
1910 # note: no $trail, because without an end, there *is* no trail
1911 wfProfileOut( __METHOD__
."-might_be_img" );
1914 wfProfileOut( __METHOD__
."-might_be_img" );
1917 $wasblank = ( $text == '' );
1921 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1922 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1923 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1924 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1925 $text = $this->doQuotes( $text );
1928 # Link not escaped by : , create the various objects
1931 wfProfileIn( __METHOD__
."-interwiki" );
1932 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && Language
::fetchLanguageName( $iw, null, 'mw' ) ) {
1933 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1934 $s = rtrim( $s . $prefix );
1935 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1936 wfProfileOut( __METHOD__
."-interwiki" );
1939 wfProfileOut( __METHOD__
."-interwiki" );
1941 if ( $ns == NS_FILE
) {
1942 wfProfileIn( __METHOD__
."-image" );
1943 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1945 # if no parameters were passed, $text
1946 # becomes something like "File:Foo.png",
1947 # which we don't want to pass on to the
1951 # recursively parse links inside the image caption
1952 # actually, this will parse them in any other parameters, too,
1953 # but it might be hard to fix that, and it doesn't matter ATM
1954 $text = $this->replaceExternalLinks( $text );
1955 $holders->merge( $this->replaceInternalLinks2( $text ) );
1957 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1958 $s .= $prefix . $this->armorLinks(
1959 $this->makeImage( $nt, $text, $holders ) ) . $trail;
1961 $s .= $prefix . $trail;
1963 wfProfileOut( __METHOD__
."-image" );
1967 if ( $ns == NS_CATEGORY
) {
1968 wfProfileIn( __METHOD__
."-category" );
1969 $s = rtrim( $s . "\n" ); # bug 87
1972 $sortkey = $this->getDefaultSort();
1976 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1977 $sortkey = str_replace( "\n", '', $sortkey );
1978 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
1979 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1982 * Strip the whitespace Category links produce, see bug 87
1983 * @todo We might want to use trim($tmp, "\n") here.
1985 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
1987 wfProfileOut( __METHOD__
."-category" );
1992 # Self-link checking
1993 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1994 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1995 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2000 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2001 # @todo FIXME: Should do batch file existence checks, see comment below
2002 if ( $ns == NS_MEDIA
) {
2003 wfProfileIn( __METHOD__
."-media" );
2004 # Give extensions a chance to select the file revision for us
2007 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2008 array( $this, $nt, &$options, &$descQuery ) );
2009 # Fetch and register the file (file title may be different via hooks)
2010 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2011 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2012 $s .= $prefix . $this->armorLinks(
2013 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2014 wfProfileOut( __METHOD__
."-media" );
2018 wfProfileIn( __METHOD__
."-always_known" );
2019 # Some titles, such as valid special pages or files in foreign repos, should
2020 # be shown as bluelinks even though they're not included in the page table
2022 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2023 # batch file existence checks for NS_FILE and NS_MEDIA
2024 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2025 $this->mOutput
->addLink( $nt );
2026 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2028 # Links will be added to the output link list after checking
2029 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2031 wfProfileOut( __METHOD__
."-always_known" );
2033 wfProfileOut( __METHOD__
);
2038 * Render a forced-blue link inline; protect against double expansion of
2039 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2040 * Since this little disaster has to split off the trail text to avoid
2041 * breaking URLs in the following text without breaking trails on the
2042 * wiki links, it's been made into a horrible function.
2045 * @param $text String
2046 * @param $query Array or String
2047 * @param $trail String
2048 * @param $prefix String
2049 * @return String: HTML-wikitext mix oh yuck
2051 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2052 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2054 if ( is_string( $query ) ) {
2055 $query = wfCgiToArray( $query );
2057 if ( $text == '' ) {
2058 $text = htmlspecialchars( $nt->getPrefixedText() );
2061 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2063 return $this->armorLinks( $link ) . $trail;
2067 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2068 * going to go through further parsing steps before inline URL expansion.
2070 * Not needed quite as much as it used to be since free links are a bit
2071 * more sensible these days. But bracketed links are still an issue.
2073 * @param $text String: more-or-less HTML
2074 * @return String: less-or-more HTML with NOPARSE bits
2076 function armorLinks( $text ) {
2077 return preg_replace( '/\b(' . $this->mUrlProtocols
. ')/',
2078 "{$this->mUniqPrefix}NOPARSE$1", $text );
2082 * Return true if subpage links should be expanded on this page.
2085 function areSubpagesAllowed() {
2086 # Some namespaces don't allow subpages
2087 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2091 * Handle link to subpage if necessary
2093 * @param $target String: the source of the link
2094 * @param &$text String: the link text, modified as necessary
2095 * @return string the full name of the link
2098 function maybeDoSubpageLink( $target, &$text ) {
2099 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2103 * Used by doBlockLevels()
2108 function closeParagraph() {
2110 if ( $this->mLastSection
!= '' ) {
2111 $result = '</' . $this->mLastSection
. ">\n";
2113 $this->mInPre
= false;
2114 $this->mLastSection
= '';
2119 * getCommon() returns the length of the longest common substring
2120 * of both arguments, starting at the beginning of both.
2123 * @param $st1 string
2124 * @param $st2 string
2128 function getCommon( $st1, $st2 ) {
2129 $fl = strlen( $st1 );
2130 $shorter = strlen( $st2 );
2131 if ( $fl < $shorter ) {
2135 for ( $i = 0; $i < $shorter; ++
$i ) {
2136 if ( $st1[$i] != $st2[$i] ) {
2144 * These next three functions open, continue, and close the list
2145 * element appropriate to the prefix character passed into them.
2148 * @param $char string
2152 function openList( $char ) {
2153 $result = $this->closeParagraph();
2155 if ( '*' === $char ) {
2156 $result .= '<ul><li>';
2157 } elseif ( '#' === $char ) {
2158 $result .= '<ol><li>';
2159 } elseif ( ':' === $char ) {
2160 $result .= '<dl><dd>';
2161 } elseif ( ';' === $char ) {
2162 $result .= '<dl><dt>';
2163 $this->mDTopen
= true;
2165 $result = '<!-- ERR 1 -->';
2173 * @param $char String
2178 function nextItem( $char ) {
2179 if ( '*' === $char ||
'#' === $char ) {
2181 } elseif ( ':' === $char ||
';' === $char ) {
2183 if ( $this->mDTopen
) {
2186 if ( ';' === $char ) {
2187 $this->mDTopen
= true;
2188 return $close . '<dt>';
2190 $this->mDTopen
= false;
2191 return $close . '<dd>';
2194 return '<!-- ERR 2 -->';
2199 * @param $char String
2204 function closeList( $char ) {
2205 if ( '*' === $char ) {
2206 $text = '</li></ul>';
2207 } elseif ( '#' === $char ) {
2208 $text = '</li></ol>';
2209 } elseif ( ':' === $char ) {
2210 if ( $this->mDTopen
) {
2211 $this->mDTopen
= false;
2212 $text = '</dt></dl>';
2214 $text = '</dd></dl>';
2217 return '<!-- ERR 3 -->';
2224 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2226 * @param $text String
2227 * @param $linestart Boolean: whether or not this is at the start of a line.
2229 * @return string the lists rendered as HTML
2231 function doBlockLevels( $text, $linestart ) {
2232 wfProfileIn( __METHOD__
);
2234 # Parsing through the text line by line. The main thing
2235 # happening here is handling of block-level elements p, pre,
2236 # and making lists from lines starting with * # : etc.
2238 $textLines = StringUtils
::explode( "\n", $text );
2240 $lastPrefix = $output = '';
2241 $this->mDTopen
= $inBlockElem = false;
2243 $paragraphStack = false;
2245 foreach ( $textLines as $oLine ) {
2247 if ( !$linestart ) {
2257 $lastPrefixLength = strlen( $lastPrefix );
2258 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2259 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2260 # If not in a <pre> element, scan for and figure out what prefixes are there.
2261 if ( !$this->mInPre
) {
2262 # Multiple prefixes may abut each other for nested lists.
2263 $prefixLength = strspn( $oLine, '*#:;' );
2264 $prefix = substr( $oLine, 0, $prefixLength );
2267 # ; and : are both from definition-lists, so they're equivalent
2268 # for the purposes of determining whether or not we need to open/close
2270 $prefix2 = str_replace( ';', ':', $prefix );
2271 $t = substr( $oLine, $prefixLength );
2272 $this->mInPre
= (bool)$preOpenMatch;
2274 # Don't interpret any other prefixes in preformatted text
2276 $prefix = $prefix2 = '';
2281 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2282 # Same as the last item, so no need to deal with nesting or opening stuff
2283 $output .= $this->nextItem( substr( $prefix, -1 ) );
2284 $paragraphStack = false;
2286 if ( substr( $prefix, -1 ) === ';') {
2287 # The one nasty exception: definition lists work like this:
2288 # ; title : definition text
2289 # So we check for : in the remainder text to split up the
2290 # title and definition, without b0rking links.
2292 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2294 $output .= $term . $this->nextItem( ':' );
2297 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2298 # We need to open or close prefixes, or both.
2300 # Either open or close a level...
2301 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2302 $paragraphStack = false;
2304 # Close all the prefixes which aren't shared.
2305 while ( $commonPrefixLength < $lastPrefixLength ) {
2306 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2307 --$lastPrefixLength;
2310 # Continue the current prefix if appropriate.
2311 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2312 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2315 # Open prefixes where appropriate.
2316 while ( $prefixLength > $commonPrefixLength ) {
2317 $char = substr( $prefix, $commonPrefixLength, 1 );
2318 $output .= $this->openList( $char );
2320 if ( ';' === $char ) {
2321 # @todo FIXME: This is dupe of code above
2322 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2324 $output .= $term . $this->nextItem( ':' );
2327 ++
$commonPrefixLength;
2329 $lastPrefix = $prefix2;
2332 # If we have no prefixes, go to paragraph mode.
2333 if ( 0 == $prefixLength ) {
2334 wfProfileIn( __METHOD__
."-paragraph" );
2335 # No prefix (not in list)--go to paragraph mode
2336 # XXX: use a stack for nestable elements like span, table and div
2337 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2338 $closematch = preg_match(
2339 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2340 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2341 if ( $openmatch or $closematch ) {
2342 $paragraphStack = false;
2343 # TODO bug 5718: paragraph closed
2344 $output .= $this->closeParagraph();
2345 if ( $preOpenMatch and !$preCloseMatch ) {
2346 $this->mInPre
= true;
2348 $inBlockElem = !$closematch;
2349 } elseif ( !$inBlockElem && !$this->mInPre
) {
2350 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2352 if ( $this->mLastSection
!== 'pre' ) {
2353 $paragraphStack = false;
2354 $output .= $this->closeParagraph().'<pre>';
2355 $this->mLastSection
= 'pre';
2357 $t = substr( $t, 1 );
2360 if ( trim( $t ) === '' ) {
2361 if ( $paragraphStack ) {
2362 $output .= $paragraphStack.'<br />';
2363 $paragraphStack = false;
2364 $this->mLastSection
= 'p';
2366 if ( $this->mLastSection
!== 'p' ) {
2367 $output .= $this->closeParagraph();
2368 $this->mLastSection
= '';
2369 $paragraphStack = '<p>';
2371 $paragraphStack = '</p><p>';
2375 if ( $paragraphStack ) {
2376 $output .= $paragraphStack;
2377 $paragraphStack = false;
2378 $this->mLastSection
= 'p';
2379 } elseif ( $this->mLastSection
!== 'p' ) {
2380 $output .= $this->closeParagraph().'<p>';
2381 $this->mLastSection
= 'p';
2386 wfProfileOut( __METHOD__
."-paragraph" );
2388 # somewhere above we forget to get out of pre block (bug 785)
2389 if ( $preCloseMatch && $this->mInPre
) {
2390 $this->mInPre
= false;
2392 if ( $paragraphStack === false ) {
2396 while ( $prefixLength ) {
2397 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2400 if ( $this->mLastSection
!= '' ) {
2401 $output .= '</' . $this->mLastSection
. '>';
2402 $this->mLastSection
= '';
2405 wfProfileOut( __METHOD__
);
2410 * Split up a string on ':', ignoring any occurrences inside tags
2411 * to prevent illegal overlapping.
2413 * @param $str String the string to split
2414 * @param &$before String set to everything before the ':'
2415 * @param &$after String set to everything after the ':'
2416 * @return String the position of the ':', or false if none found
2418 function findColonNoLinks( $str, &$before, &$after ) {
2419 wfProfileIn( __METHOD__
);
2421 $pos = strpos( $str, ':' );
2422 if ( $pos === false ) {
2424 wfProfileOut( __METHOD__
);
2428 $lt = strpos( $str, '<' );
2429 if ( $lt === false ||
$lt > $pos ) {
2430 # Easy; no tag nesting to worry about
2431 $before = substr( $str, 0, $pos );
2432 $after = substr( $str, $pos+
1 );
2433 wfProfileOut( __METHOD__
);
2437 # Ugly state machine to walk through avoiding tags.
2438 $state = self
::COLON_STATE_TEXT
;
2440 $len = strlen( $str );
2441 for( $i = 0; $i < $len; $i++
) {
2445 # (Using the number is a performance hack for common cases)
2446 case 0: # self::COLON_STATE_TEXT:
2449 # Could be either a <start> tag or an </end> tag
2450 $state = self
::COLON_STATE_TAGSTART
;
2453 if ( $stack == 0 ) {
2455 $before = substr( $str, 0, $i );
2456 $after = substr( $str, $i +
1 );
2457 wfProfileOut( __METHOD__
);
2460 # Embedded in a tag; don't break it.
2463 # Skip ahead looking for something interesting
2464 $colon = strpos( $str, ':', $i );
2465 if ( $colon === false ) {
2466 # Nothing else interesting
2467 wfProfileOut( __METHOD__
);
2470 $lt = strpos( $str, '<', $i );
2471 if ( $stack === 0 ) {
2472 if ( $lt === false ||
$colon < $lt ) {
2474 $before = substr( $str, 0, $colon );
2475 $after = substr( $str, $colon +
1 );
2476 wfProfileOut( __METHOD__
);
2480 if ( $lt === false ) {
2481 # Nothing else interesting to find; abort!
2482 # We're nested, but there's no close tags left. Abort!
2485 # Skip ahead to next tag start
2487 $state = self
::COLON_STATE_TAGSTART
;
2490 case 1: # self::COLON_STATE_TAG:
2495 $state = self
::COLON_STATE_TEXT
;
2498 # Slash may be followed by >?
2499 $state = self
::COLON_STATE_TAGSLASH
;
2505 case 2: # self::COLON_STATE_TAGSTART:
2508 $state = self
::COLON_STATE_CLOSETAG
;
2511 $state = self
::COLON_STATE_COMMENT
;
2514 # Illegal early close? This shouldn't happen D:
2515 $state = self
::COLON_STATE_TEXT
;
2518 $state = self
::COLON_STATE_TAG
;
2521 case 3: # self::COLON_STATE_CLOSETAG:
2526 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2527 wfProfileOut( __METHOD__
);
2530 $state = self
::COLON_STATE_TEXT
;
2533 case self
::COLON_STATE_TAGSLASH
:
2535 # Yes, a self-closed tag <blah/>
2536 $state = self
::COLON_STATE_TEXT
;
2538 # Probably we're jumping the gun, and this is an attribute
2539 $state = self
::COLON_STATE_TAG
;
2542 case 5: # self::COLON_STATE_COMMENT:
2544 $state = self
::COLON_STATE_COMMENTDASH
;
2547 case self
::COLON_STATE_COMMENTDASH
:
2549 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2551 $state = self
::COLON_STATE_COMMENT
;
2554 case self
::COLON_STATE_COMMENTDASHDASH
:
2556 $state = self
::COLON_STATE_TEXT
;
2558 $state = self
::COLON_STATE_COMMENT
;
2562 throw new MWException( "State machine error in " . __METHOD__
);
2566 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2567 wfProfileOut( __METHOD__
);
2570 wfProfileOut( __METHOD__
);
2575 * Return value of a magic variable (like PAGENAME)
2579 * @param $index integer
2580 * @param $frame PPFrame
2584 function getVariableValue( $index, $frame = false ) {
2585 global $wgContLang, $wgSitename, $wgServer;
2586 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2588 if ( is_null( $this->mTitle
) ) {
2589 // If no title set, bad things are going to happen
2590 // later. Title should always be set since this
2591 // should only be called in the middle of a parse
2592 // operation (but the unit-tests do funky stuff)
2593 throw new MWException( __METHOD__
. ' Should only be '
2594 . ' called while parsing (no title set)' );
2598 * Some of these require message or data lookups and can be
2599 * expensive to check many times.
2601 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2602 if ( isset( $this->mVarCache
[$index] ) ) {
2603 return $this->mVarCache
[$index];
2607 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2608 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2611 global $wgLocaltimezone;
2612 if ( isset( $wgLocaltimezone ) ) {
2613 $oldtz = date_default_timezone_get();
2614 date_default_timezone_set( $wgLocaltimezone );
2617 $localTimestamp = date( 'YmdHis', $ts );
2618 $localMonth = date( 'm', $ts );
2619 $localMonth1 = date( 'n', $ts );
2620 $localMonthName = date( 'n', $ts );
2621 $localDay = date( 'j', $ts );
2622 $localDay2 = date( 'd', $ts );
2623 $localDayOfWeek = date( 'w', $ts );
2624 $localWeek = date( 'W', $ts );
2625 $localYear = date( 'Y', $ts );
2626 $localHour = date( 'H', $ts );
2627 if ( isset( $wgLocaltimezone ) ) {
2628 date_default_timezone_set( $oldtz );
2631 $pageLang = $this->getFunctionLang();
2634 case 'currentmonth':
2635 $value = $pageLang->formatNum( gmdate( 'm', $ts ) );
2637 case 'currentmonth1':
2638 $value = $pageLang->formatNum( gmdate( 'n', $ts ) );
2640 case 'currentmonthname':
2641 $value = $pageLang->getMonthName( gmdate( 'n', $ts ) );
2643 case 'currentmonthnamegen':
2644 $value = $pageLang->getMonthNameGen( gmdate( 'n', $ts ) );
2646 case 'currentmonthabbrev':
2647 $value = $pageLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2650 $value = $pageLang->formatNum( gmdate( 'j', $ts ) );
2653 $value = $pageLang->formatNum( gmdate( 'd', $ts ) );
2656 $value = $pageLang->formatNum( $localMonth );
2659 $value = $pageLang->formatNum( $localMonth1 );
2661 case 'localmonthname':
2662 $value = $pageLang->getMonthName( $localMonthName );
2664 case 'localmonthnamegen':
2665 $value = $pageLang->getMonthNameGen( $localMonthName );
2667 case 'localmonthabbrev':
2668 $value = $pageLang->getMonthAbbreviation( $localMonthName );
2671 $value = $pageLang->formatNum( $localDay );
2674 $value = $pageLang->formatNum( $localDay2 );
2677 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2680 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2682 case 'fullpagename':
2683 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2685 case 'fullpagenamee':
2686 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2689 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2691 case 'subpagenamee':
2692 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2694 case 'basepagename':
2695 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2697 case 'basepagenamee':
2698 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2700 case 'talkpagename':
2701 if ( $this->mTitle
->canTalk() ) {
2702 $talkPage = $this->mTitle
->getTalkPage();
2703 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2708 case 'talkpagenamee':
2709 if ( $this->mTitle
->canTalk() ) {
2710 $talkPage = $this->mTitle
->getTalkPage();
2711 $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() );
2716 case 'subjectpagename':
2717 $subjPage = $this->mTitle
->getSubjectPage();
2718 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2720 case 'subjectpagenamee':
2721 $subjPage = $this->mTitle
->getSubjectPage();
2722 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() );
2724 case 'pageid': // requested in bug 23427
2725 $pageid = $this->getTitle()->getArticleId();
2726 if( $pageid == 0 ) {
2727 # 0 means the page doesn't exist in the database,
2728 # which means the user is previewing a new page.
2729 # The vary-revision flag must be set, because the magic word
2730 # will have a different value once the page is saved.
2731 $this->mOutput
->setFlag( 'vary-revision' );
2732 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2734 $value = $pageid ?
$pageid : null;
2737 # Let the edit saving system know we should parse the page
2738 # *after* a revision ID has been assigned.
2739 $this->mOutput
->setFlag( 'vary-revision' );
2740 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2741 $value = $this->mRevisionId
;
2744 # Let the edit saving system know we should parse the page
2745 # *after* a revision ID has been assigned. This is for null edits.
2746 $this->mOutput
->setFlag( 'vary-revision' );
2747 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2748 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2750 case 'revisionday2':
2751 # Let the edit saving system know we should parse the page
2752 # *after* a revision ID has been assigned. This is for null edits.
2753 $this->mOutput
->setFlag( 'vary-revision' );
2754 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2755 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2757 case 'revisionmonth':
2758 # Let the edit saving system know we should parse the page
2759 # *after* a revision ID has been assigned. This is for null edits.
2760 $this->mOutput
->setFlag( 'vary-revision' );
2761 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2762 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2764 case 'revisionmonth1':
2765 # Let the edit saving system know we should parse the page
2766 # *after* a revision ID has been assigned. This is for null edits.
2767 $this->mOutput
->setFlag( 'vary-revision' );
2768 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2769 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2771 case 'revisionyear':
2772 # Let the edit saving system know we should parse the page
2773 # *after* a revision ID has been assigned. This is for null edits.
2774 $this->mOutput
->setFlag( 'vary-revision' );
2775 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2776 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2778 case 'revisiontimestamp':
2779 # Let the edit saving system know we should parse the page
2780 # *after* a revision ID has been assigned. This is for null edits.
2781 $this->mOutput
->setFlag( 'vary-revision' );
2782 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2783 $value = $this->getRevisionTimestamp();
2785 case 'revisionuser':
2786 # Let the edit saving system know we should parse the page
2787 # *after* a revision ID has been assigned. This is for null edits.
2788 $this->mOutput
->setFlag( 'vary-revision' );
2789 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2790 $value = $this->getRevisionUser();
2793 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2796 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2798 case 'namespacenumber':
2799 $value = $this->mTitle
->getNamespace();
2802 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2805 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2807 case 'subjectspace':
2808 $value = $this->mTitle
->getSubjectNsText();
2810 case 'subjectspacee':
2811 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2813 case 'currentdayname':
2814 $value = $pageLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2817 $value = $pageLang->formatNum( gmdate( 'Y', $ts ), true );
2820 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2823 $value = $pageLang->formatNum( gmdate( 'H', $ts ), true );
2826 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2827 # int to remove the padding
2828 $value = $pageLang->formatNum( (int)gmdate( 'W', $ts ) );
2831 $value = $pageLang->formatNum( gmdate( 'w', $ts ) );
2833 case 'localdayname':
2834 $value = $pageLang->getWeekdayName( $localDayOfWeek +
1 );
2837 $value = $pageLang->formatNum( $localYear, true );
2840 $value = $pageLang->time( $localTimestamp, false, false );
2843 $value = $pageLang->formatNum( $localHour, true );
2846 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2847 # int to remove the padding
2848 $value = $pageLang->formatNum( (int)$localWeek );
2851 $value = $pageLang->formatNum( $localDayOfWeek );
2853 case 'numberofarticles':
2854 $value = $pageLang->formatNum( SiteStats
::articles() );
2856 case 'numberoffiles':
2857 $value = $pageLang->formatNum( SiteStats
::images() );
2859 case 'numberofusers':
2860 $value = $pageLang->formatNum( SiteStats
::users() );
2862 case 'numberofactiveusers':
2863 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2865 case 'numberofpages':
2866 $value = $pageLang->formatNum( SiteStats
::pages() );
2868 case 'numberofadmins':
2869 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2871 case 'numberofedits':
2872 $value = $pageLang->formatNum( SiteStats
::edits() );
2874 case 'numberofviews':
2875 global $wgDisableCounters;
2876 $value = !$wgDisableCounters ?
$pageLang->formatNum( SiteStats
::views() ) : '';
2878 case 'currenttimestamp':
2879 $value = wfTimestamp( TS_MW
, $ts );
2881 case 'localtimestamp':
2882 $value = $localTimestamp;
2884 case 'currentversion':
2885 $value = SpecialVersion
::getVersion();
2888 return $wgArticlePath;
2894 $serverParts = wfParseUrl( $wgServer );
2895 return $serverParts && isset( $serverParts['host'] ) ?
$serverParts['host'] : $wgServer;
2897 return $wgScriptPath;
2899 return $wgStylePath;
2900 case 'directionmark':
2901 return $pageLang->getDirMark();
2902 case 'contentlanguage':
2903 global $wgLanguageCode;
2904 return $wgLanguageCode;
2907 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2915 $this->mVarCache
[$index] = $value;
2922 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2926 function initialiseVariables() {
2927 wfProfileIn( __METHOD__
);
2928 $variableIDs = MagicWord
::getVariableIDs();
2929 $substIDs = MagicWord
::getSubstIDs();
2931 $this->mVariables
= new MagicWordArray( $variableIDs );
2932 $this->mSubstWords
= new MagicWordArray( $substIDs );
2933 wfProfileOut( __METHOD__
);
2937 * Preprocess some wikitext and return the document tree.
2938 * This is the ghost of replace_variables().
2940 * @param $text String: The text to parse
2941 * @param $flags Integer: bitwise combination of:
2942 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2943 * included. Default is to assume a direct page view.
2945 * The generated DOM tree must depend only on the input text and the flags.
2946 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2948 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2949 * change in the DOM tree for a given text, must be passed through the section identifier
2950 * in the section edit link and thus back to extractSections().
2952 * The output of this function is currently only cached in process memory, but a persistent
2953 * cache may be implemented at a later date which takes further advantage of these strict
2954 * dependency requirements.
2960 function preprocessToDom( $text, $flags = 0 ) {
2961 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2966 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2972 public static function splitWhitespace( $s ) {
2973 $ltrimmed = ltrim( $s );
2974 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2975 $trimmed = rtrim( $ltrimmed );
2976 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2978 $w2 = substr( $ltrimmed, -$diff );
2982 return array( $w1, $trimmed, $w2 );
2986 * Replace magic variables, templates, and template arguments
2987 * with the appropriate text. Templates are substituted recursively,
2988 * taking care to avoid infinite loops.
2990 * Note that the substitution depends on value of $mOutputType:
2991 * self::OT_WIKI: only {{subst:}} templates
2992 * self::OT_PREPROCESS: templates but not extension tags
2993 * self::OT_HTML: all templates and extension tags
2995 * @param $text String the text to transform
2996 * @param $frame PPFrame Object describing the arguments passed to the template.
2997 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2998 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2999 * @param $argsOnly Boolean only do argument (triple-brace) expansion, not double-brace expansion
3004 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3005 # Is there any text? Also, Prevent too big inclusions!
3006 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3009 wfProfileIn( __METHOD__
);
3011 if ( $frame === false ) {
3012 $frame = $this->getPreprocessor()->newFrame();
3013 } elseif ( !( $frame instanceof PPFrame
) ) {
3014 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
3015 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3018 $dom = $this->preprocessToDom( $text );
3019 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3020 $text = $frame->expand( $dom, $flags );
3022 wfProfileOut( __METHOD__
);
3027 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3029 * @param $args array
3033 static function createAssocArgs( $args ) {
3034 $assocArgs = array();
3036 foreach ( $args as $arg ) {
3037 $eqpos = strpos( $arg, '=' );
3038 if ( $eqpos === false ) {
3039 $assocArgs[$index++
] = $arg;
3041 $name = trim( substr( $arg, 0, $eqpos ) );
3042 $value = trim( substr( $arg, $eqpos+
1 ) );
3043 if ( $value === false ) {
3046 if ( $name !== false ) {
3047 $assocArgs[$name] = $value;
3056 * Warn the user when a parser limitation is reached
3057 * Will warn at most once the user per limitation type
3059 * @param $limitationType String: should be one of:
3060 * 'expensive-parserfunction' (corresponding messages:
3061 * 'expensive-parserfunction-warning',
3062 * 'expensive-parserfunction-category')
3063 * 'post-expand-template-argument' (corresponding messages:
3064 * 'post-expand-template-argument-warning',
3065 * 'post-expand-template-argument-category')
3066 * 'post-expand-template-inclusion' (corresponding messages:
3067 * 'post-expand-template-inclusion-warning',
3068 * 'post-expand-template-inclusion-category')
3069 * @param $current int|null Current value
3070 * @param $max int|null Maximum allowed, when an explicit limit has been
3071 * exceeded, provide the values (optional)
3073 function limitationWarn( $limitationType, $current = null, $max = null) {
3074 # does no harm if $current and $max are present but are unnecessary for the message
3075 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
3076 $this->mOutput
->addWarning( $warning );
3077 $this->addTrackingCategory( "$limitationType-category" );
3081 * Return the text of a template, after recursively
3082 * replacing any variables or templates within the template.
3084 * @param $piece Array: the parts of the template
3085 * $piece['title']: the title, i.e. the part before the |
3086 * $piece['parts']: the parameter array
3087 * $piece['lineStart']: whether the brace was at the start of a line
3088 * @param $frame PPFrame The current frame, contains template arguments
3089 * @return String: the text of the template
3092 function braceSubstitution( $piece, $frame ) {
3094 wfProfileIn( __METHOD__
);
3095 wfProfileIn( __METHOD__
.'-setup' );
3098 $found = false; # $text has been filled
3099 $nowiki = false; # wiki markup in $text should be escaped
3100 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3101 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3102 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3103 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3105 # Title object, where $text came from
3108 # $part1 is the bit before the first |, and must contain only title characters.
3109 # Various prefixes will be stripped from it later.
3110 $titleWithSpaces = $frame->expand( $piece['title'] );
3111 $part1 = trim( $titleWithSpaces );
3114 # Original title text preserved for various purposes
3115 $originalTitle = $part1;
3117 # $args is a list of argument nodes, starting from index 0, not including $part1
3118 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3119 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3120 wfProfileOut( __METHOD__
.'-setup' );
3122 $titleProfileIn = null; // profile templates
3125 wfProfileIn( __METHOD__
.'-modifiers' );
3128 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3130 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3131 # Decide whether to expand template or keep wikitext as-is.
3132 if ( $this->ot
['wiki'] ) {
3133 if ( $substMatch === false ) {
3134 $literal = true; # literal when in PST with no prefix
3136 $literal = false; # expand when in PST with subst: or safesubst:
3139 if ( $substMatch == 'subst' ) {
3140 $literal = true; # literal when not in PST with plain subst:
3142 $literal = false; # expand when not in PST with safesubst: or no prefix
3146 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3153 if ( !$found && $args->getLength() == 0 ) {
3154 $id = $this->mVariables
->matchStartToEnd( $part1 );
3155 if ( $id !== false ) {
3156 $text = $this->getVariableValue( $id, $frame );
3157 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3158 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3164 # MSG, MSGNW and RAW
3167 $mwMsgnw = MagicWord
::get( 'msgnw' );
3168 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3171 # Remove obsolete MSG:
3172 $mwMsg = MagicWord
::get( 'msg' );
3173 $mwMsg->matchStartAndRemove( $part1 );
3177 $mwRaw = MagicWord
::get( 'raw' );
3178 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3179 $forceRawInterwiki = true;
3182 wfProfileOut( __METHOD__
.'-modifiers' );
3186 wfProfileIn( __METHOD__
. '-pfunc' );
3188 $colonPos = strpos( $part1, ':' );
3189 if ( $colonPos !== false ) {
3190 # Case sensitive functions
3191 $function = substr( $part1, 0, $colonPos );
3192 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3193 $function = $this->mFunctionSynonyms
[1][$function];
3195 # Case insensitive functions
3196 $function = $wgContLang->lc( $function );
3197 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3198 $function = $this->mFunctionSynonyms
[0][$function];
3204 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3205 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3206 $initialArgs = array( &$this );
3207 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3208 if ( $flags & SFH_OBJECT_ARGS
) {
3209 # Add a frame parameter, and pass the arguments as an array
3210 $allArgs = $initialArgs;
3211 $allArgs[] = $frame;
3212 for ( $i = 0; $i < $args->getLength(); $i++
) {
3213 $funcArgs[] = $args->item( $i );
3215 $allArgs[] = $funcArgs;
3217 # Convert arguments to plain text
3218 for ( $i = 0; $i < $args->getLength(); $i++
) {
3219 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3221 $allArgs = array_merge( $initialArgs, $funcArgs );
3224 # Workaround for PHP bug 35229 and similar
3225 if ( !is_callable( $callback ) ) {
3226 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3227 wfProfileOut( __METHOD__
. '-pfunc' );
3228 wfProfileOut( __METHOD__
);
3229 throw new MWException( "Tag hook for $function is not callable\n" );
3231 $result = call_user_func_array( $callback, $allArgs );
3234 $preprocessFlags = 0;
3236 if ( is_array( $result ) ) {
3237 if ( isset( $result[0] ) ) {
3239 unset( $result[0] );
3242 # Extract flags into the local scope
3243 # This allows callers to set flags such as nowiki, found, etc.
3249 $text = $this->preprocessToDom( $text, $preprocessFlags );
3252 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3255 wfProfileOut( __METHOD__
. '-pfunc' );
3258 # Finish mangling title and then check for loops.
3259 # Set $title to a Title object and $titleText to the PDBK
3262 # Split the title into page and subpage
3264 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3265 if ( $subpage !== '' ) {
3266 $ns = $this->mTitle
->getNamespace();
3268 $title = Title
::newFromText( $part1, $ns );
3270 $titleText = $title->getPrefixedText();
3271 # Check for language variants if the template is not found
3272 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3273 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3275 # Do recursion depth check
3276 $limit = $this->mOptions
->getMaxTemplateDepth();
3277 if ( $frame->depth
>= $limit ) {
3279 $text = '<span class="error">'
3280 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
3286 # Load from database
3287 if ( !$found && $title ) {
3288 if ( !Profiler
::instance()->isPersistent() ) {
3289 # Too many unique items can kill profiling DBs/collectors
3290 $titleProfileIn = __METHOD__
. "-title-" . $title->getDBKey();
3291 wfProfileIn( $titleProfileIn ); // template in
3293 wfProfileIn( __METHOD__
. '-loadtpl' );
3294 if ( !$title->isExternal() ) {
3295 if ( $title->isSpecialPage()
3296 && $this->mOptions
->getAllowSpecialInclusion()
3297 && $this->ot
['html'] )
3299 // Pass the template arguments as URL parameters.
3300 // "uselang" will have no effect since the Language object
3301 // is forced to the one defined in ParserOptions.
3302 $pageArgs = array();
3303 for ( $i = 0; $i < $args->getLength(); $i++
) {
3304 $bits = $args->item( $i )->splitArg();
3305 if ( strval( $bits['index'] ) === '' ) {
3306 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3307 $value = trim( $frame->expand( $bits['value'] ) );
3308 $pageArgs[$name] = $value;
3312 // Create a new context to execute the special page
3313 $context = new RequestContext
;
3314 $context->setTitle( $title );
3315 $context->setRequest( new FauxRequest( $pageArgs ) );
3316 $context->setUser( $this->getUser() );
3317 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3318 $ret = SpecialPageFactory
::capturePath( $title, $context );
3320 $text = $context->getOutput()->getHTML();
3321 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3324 $this->disableCache();
3326 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3327 $found = false; # access denied
3328 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3330 list( $text, $title ) = $this->getTemplateDom( $title );
3331 if ( $text !== false ) {
3337 # If the title is valid but undisplayable, make a link to it
3338 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3339 $text = "[[:$titleText]]";
3342 } elseif ( $title->isTrans() ) {
3343 # Interwiki transclusion
3344 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3345 $text = $this->interwikiTransclude( $title, 'render' );
3348 $text = $this->interwikiTransclude( $title, 'raw' );
3349 # Preprocess it like a template
3350 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3356 # Do infinite loop check
3357 # This has to be done after redirect resolution to avoid infinite loops via redirects
3358 if ( !$frame->loopCheck( $title ) ) {
3360 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3361 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3363 wfProfileOut( __METHOD__
. '-loadtpl' );
3366 # If we haven't found text to substitute by now, we're done
3367 # Recover the source wikitext and return it
3369 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3370 if ( $titleProfileIn ) {
3371 wfProfileOut( $titleProfileIn ); // template out
3373 wfProfileOut( __METHOD__
);
3374 return array( 'object' => $text );
3377 # Expand DOM-style return values in a child frame
3378 if ( $isChildObj ) {
3379 # Clean up argument array
3380 $newFrame = $frame->newChild( $args, $title );
3383 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3384 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3385 # Expansion is eligible for the empty-frame cache
3386 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3387 $text = $this->mTplExpandCache
[$titleText];
3389 $text = $newFrame->expand( $text );
3390 $this->mTplExpandCache
[$titleText] = $text;
3393 # Uncached expansion
3394 $text = $newFrame->expand( $text );
3397 if ( $isLocalObj && $nowiki ) {
3398 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3399 $isLocalObj = false;
3402 if ( $titleProfileIn ) {
3403 wfProfileOut( $titleProfileIn ); // template out
3406 # Replace raw HTML by a placeholder
3408 $text = $this->insertStripItem( $text );
3409 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3410 # Escape nowiki-style return values
3411 $text = wfEscapeWikiText( $text );
3412 } elseif ( is_string( $text )
3413 && !$piece['lineStart']
3414 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3416 # Bug 529: if the template begins with a table or block-level
3417 # element, it should be treated as beginning a new line.
3418 # This behaviour is somewhat controversial.
3419 $text = "\n" . $text;
3422 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3423 # Error, oversize inclusion
3424 if ( $titleText !== false ) {
3425 # Make a working, properly escaped link if possible (bug 23588)
3426 $text = "[[:$titleText]]";
3428 # This will probably not be a working link, but at least it may
3429 # provide some hint of where the problem is
3430 preg_replace( '/^:/', '', $originalTitle );
3431 $text = "[[:$originalTitle]]";
3433 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3434 $this->limitationWarn( 'post-expand-template-inclusion' );
3437 if ( $isLocalObj ) {
3438 $ret = array( 'object' => $text );
3440 $ret = array( 'text' => $text );
3443 wfProfileOut( __METHOD__
);
3448 * Get the semi-parsed DOM representation of a template with a given title,
3449 * and its redirect destination title. Cached.
3451 * @param $title Title
3455 function getTemplateDom( $title ) {
3456 $cacheTitle = $title;
3457 $titleText = $title->getPrefixedDBkey();
3459 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3460 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3461 $title = Title
::makeTitle( $ns, $dbk );
3462 $titleText = $title->getPrefixedDBkey();
3464 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3465 return array( $this->mTplDomCache
[$titleText], $title );
3468 # Cache miss, go to the database
3469 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3471 if ( $text === false ) {
3472 $this->mTplDomCache
[$titleText] = false;
3473 return array( false, $title );
3476 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3477 $this->mTplDomCache
[ $titleText ] = $dom;
3479 if ( !$title->equals( $cacheTitle ) ) {
3480 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3481 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3484 return array( $dom, $title );
3488 * Fetch the unparsed text of a template and register a reference to it.
3489 * @param Title $title
3490 * @return Array ( string or false, Title )
3492 function fetchTemplateAndTitle( $title ) {
3493 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3494 $stuff = call_user_func( $templateCb, $title, $this );
3495 $text = $stuff['text'];
3496 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3497 if ( isset( $stuff['deps'] ) ) {
3498 foreach ( $stuff['deps'] as $dep ) {
3499 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3502 return array( $text, $finalTitle );
3506 * Fetch the unparsed text of a template and register a reference to it.
3507 * @param Title $title
3508 * @return mixed string or false
3510 function fetchTemplate( $title ) {
3511 $rv = $this->fetchTemplateAndTitle( $title );
3516 * Static function to get a template
3517 * Can be overridden via ParserOptions::setTemplateCallback().
3519 * @parma $title Title
3520 * @param $parser Parser
3524 static function statelessFetchTemplate( $title, $parser = false ) {
3525 $text = $skip = false;
3526 $finalTitle = $title;
3529 # Loop to fetch the article, with up to 1 redirect
3530 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3531 # Give extensions a chance to select the revision instead
3532 $id = false; # Assume current
3533 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3534 array( $parser, $title, &$skip, &$id ) );
3540 'page_id' => $title->getArticleID(),
3547 ? Revision
::newFromId( $id )
3548 : Revision
::newFromTitle( $title );
3549 $rev_id = $rev ?
$rev->getId() : 0;
3550 # If there is no current revision, there is no page
3551 if ( $id === false && !$rev ) {
3552 $linkCache = LinkCache
::singleton();
3553 $linkCache->addBadLinkObj( $title );
3558 'page_id' => $title->getArticleID(),
3559 'rev_id' => $rev_id );
3560 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3561 # We fetched a rev from a different title; register it too...
3563 'title' => $rev->getTitle(),
3564 'page_id' => $rev->getPage(),
3565 'rev_id' => $rev_id );
3569 $text = $rev->getText();
3570 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3572 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3573 if ( !$message->exists() ) {
3577 $text = $message->plain();
3581 if ( $text === false ) {
3585 $finalTitle = $title;
3586 $title = Title
::newFromRedirect( $text );
3590 'finalTitle' => $finalTitle,
3595 * Fetch a file and its title and register a reference to it.
3596 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3597 * @param Title $title
3598 * @param Array $options Array of options to RepoGroup::findFile
3601 function fetchFile( $title, $options = array() ) {
3602 $res = $this->fetchFileAndTitle( $title, $options );
3607 * Fetch a file and its title and register a reference to it.
3608 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3609 * @param Title $title
3610 * @param Array $options Array of options to RepoGroup::findFile
3611 * @return Array ( File or false, Title of file )
3613 function fetchFileAndTitle( $title, $options = array() ) {
3614 if ( isset( $options['broken'] ) ) {
3615 $file = false; // broken thumbnail forced by hook
3616 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3617 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3618 } else { // get by (name,timestamp)
3619 $file = wfFindFile( $title, $options );
3621 $time = $file ?
$file->getTimestamp() : false;
3622 $sha1 = $file ?
$file->getSha1() : false;
3623 # Register the file as a dependency...
3624 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3625 if ( $file && !$title->equals( $file->getTitle() ) ) {
3626 # Update fetched file title
3627 $title = $file->getTitle();
3628 if ( is_null( $file->getRedirectedTitle() ) ) {
3629 # This file was not a redirect, but the title does not match.
3630 # Register under the new name because otherwise the link will
3632 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3635 return array( $file, $title );
3639 * Transclude an interwiki link.
3641 * @param $title Title
3646 function interwikiTransclude( $title, $action ) {
3647 global $wgEnableScaryTranscluding;
3649 if ( !$wgEnableScaryTranscluding ) {
3650 return wfMsgForContent('scarytranscludedisabled');
3653 $url = $title->getFullUrl( "action=$action" );
3655 if ( strlen( $url ) > 255 ) {
3656 return wfMsgForContent( 'scarytranscludetoolong' );
3658 return $this->fetchScaryTemplateMaybeFromCache( $url );
3662 * @param $url string
3663 * @return Mixed|String
3665 function fetchScaryTemplateMaybeFromCache( $url ) {
3666 global $wgTranscludeCacheExpiry;
3667 $dbr = wfGetDB( DB_SLAVE
);
3668 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3669 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3670 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3672 return $obj->tc_contents
;
3675 $text = Http
::get( $url );
3677 return wfMsgForContent( 'scarytranscludefailed', $url );
3680 $dbw = wfGetDB( DB_MASTER
);
3681 $dbw->replace( 'transcache', array('tc_url'), array(
3683 'tc_time' => $dbw->timestamp( time() ),
3684 'tc_contents' => $text)
3690 * Triple brace replacement -- used for template arguments
3693 * @param $peice array
3694 * @param $frame PPFrame
3698 function argSubstitution( $piece, $frame ) {
3699 wfProfileIn( __METHOD__
);
3702 $parts = $piece['parts'];
3703 $nameWithSpaces = $frame->expand( $piece['title'] );
3704 $argName = trim( $nameWithSpaces );
3706 $text = $frame->getArgument( $argName );
3707 if ( $text === false && $parts->getLength() > 0
3711 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3714 # No match in frame, use the supplied default
3715 $object = $parts->item( 0 )->getChildren();
3717 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3718 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3719 $this->limitationWarn( 'post-expand-template-argument' );
3722 if ( $text === false && $object === false ) {
3724 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3726 if ( $error !== false ) {
3729 if ( $object !== false ) {
3730 $ret = array( 'object' => $object );
3732 $ret = array( 'text' => $text );
3735 wfProfileOut( __METHOD__
);
3740 * Return the text to be used for a given extension tag.
3741 * This is the ghost of strip().
3743 * @param $params array Associative array of parameters:
3744 * name PPNode for the tag name
3745 * attr PPNode for unparsed text where tag attributes are thought to be
3746 * attributes Optional associative array of parsed attributes
3747 * inner Contents of extension element
3748 * noClose Original text did not have a close tag
3749 * @param $frame PPFrame
3753 function extensionSubstitution( $params, $frame ) {
3754 $name = $frame->expand( $params['name'] );
3755 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3756 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3757 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3759 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3760 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3761 if ( $isFunctionTag ) {
3762 $markerType = 'none';
3764 $markerType = 'general';
3766 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3767 $name = strtolower( $name );
3768 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3769 if ( isset( $params['attributes'] ) ) {
3770 $attributes = $attributes +
$params['attributes'];
3773 if ( isset( $this->mTagHooks
[$name] ) ) {
3774 # Workaround for PHP bug 35229 and similar
3775 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3776 throw new MWException( "Tag hook for $name is not callable\n" );
3778 $output = call_user_func_array( $this->mTagHooks
[$name],
3779 array( $content, $attributes, $this, $frame ) );
3780 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3781 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3782 if ( !is_callable( $callback ) ) {
3783 throw new MWException( "Tag hook for $name is not callable\n" );
3786 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3788 $output = '<span class="error">Invalid tag extension name: ' .
3789 htmlspecialchars( $name ) . '</span>';
3792 if ( is_array( $output ) ) {
3793 # Extract flags to local scope (to override $markerType)
3795 $output = $flags[0];
3800 if ( is_null( $attrText ) ) {
3803 if ( isset( $params['attributes'] ) ) {
3804 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3805 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3806 htmlspecialchars( $attrValue ) . '"';
3809 if ( $content === null ) {
3810 $output = "<$name$attrText/>";
3812 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3813 $output = "<$name$attrText>$content$close";
3817 if ( $markerType === 'none' ) {
3819 } elseif ( $markerType === 'nowiki' ) {
3820 $this->mStripState
->addNoWiki( $marker, $output );
3821 } elseif ( $markerType === 'general' ) {
3822 $this->mStripState
->addGeneral( $marker, $output );
3824 throw new MWException( __METHOD__
.': invalid marker type' );
3830 * Increment an include size counter
3832 * @param $type String: the type of expansion
3833 * @param $size Integer: the size of the text
3834 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3836 function incrementIncludeSize( $type, $size ) {
3837 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3840 $this->mIncludeSizes
[$type] +
= $size;
3846 * Increment the expensive function count
3848 * @return Boolean: false if the limit has been exceeded
3850 function incrementExpensiveFunctionCount() {
3851 $this->mExpensiveFunctionCount++
;
3852 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
3856 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3857 * Fills $this->mDoubleUnderscores, returns the modified text
3859 * @param $text string
3863 function doDoubleUnderscore( $text ) {
3864 wfProfileIn( __METHOD__
);
3866 # The position of __TOC__ needs to be recorded
3867 $mw = MagicWord
::get( 'toc' );
3868 if ( $mw->match( $text ) ) {
3869 $this->mShowToc
= true;
3870 $this->mForceTocPosition
= true;
3872 # Set a placeholder. At the end we'll fill it in with the TOC.
3873 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3875 # Only keep the first one.
3876 $text = $mw->replace( '', $text );
3879 # Now match and remove the rest of them
3880 $mwa = MagicWord
::getDoubleUnderscoreArray();
3881 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3883 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3884 $this->mOutput
->mNoGallery
= true;
3886 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3887 $this->mShowToc
= false;
3889 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3890 $this->addTrackingCategory( 'hidden-category-category' );
3892 # (bug 8068) Allow control over whether robots index a page.
3894 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
3895 # is not desirable, the last one on the page should win.
3896 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3897 $this->mOutput
->setIndexPolicy( 'noindex' );
3898 $this->addTrackingCategory( 'noindex-category' );
3900 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3901 $this->mOutput
->setIndexPolicy( 'index' );
3902 $this->addTrackingCategory( 'index-category' );
3905 # Cache all double underscores in the database
3906 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
3907 $this->mOutput
->setProperty( $key, '' );
3910 wfProfileOut( __METHOD__
);
3915 * Add a tracking category, getting the title from a system message,
3916 * or print a debug message if the title is invalid.
3918 * @param $msg String: message key
3919 * @return Boolean: whether the addition was successful
3921 public function addTrackingCategory( $msg ) {
3922 if ( $this->mTitle
->getNamespace() === NS_SPECIAL
) {
3923 wfDebug( __METHOD__
.": Not adding tracking category $msg to special page!\n" );
3926 // Important to parse with correct title (bug 31469)
3927 $cat = wfMessage( $msg )
3928 ->title( $this->getTitle() )
3929 ->inContentLanguage()
3932 # Allow tracking categories to be disabled by setting them to "-"
3933 if ( $cat === '-' ) {
3937 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3938 if ( $containerCategory ) {
3939 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3942 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3948 * This function accomplishes several tasks:
3949 * 1) Auto-number headings if that option is enabled
3950 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3951 * 3) Add a Table of contents on the top for users who have enabled the option
3952 * 4) Auto-anchor headings
3954 * It loops through all headlines, collects the necessary data, then splits up the
3955 * string and re-inserts the newly formatted headlines.
3957 * @param $text String
3958 * @param $origText String: original, untouched wikitext
3959 * @param $isMain Boolean
3960 * @return mixed|string
3963 function formatHeadings( $text, $origText, $isMain=true ) {
3964 global $wgMaxTocLevel, $wgHtml5, $wgExperimentalHtmlIds;
3966 # Inhibit editsection links if requested in the page
3967 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3968 $maybeShowEditLink = $showEditLink = false;
3970 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
3971 $showEditLink = $this->mOptions
->getEditSection();
3973 if ( $showEditLink ) {
3974 $this->mOutput
->setEditSectionTokens( true );
3977 # Get all headlines for numbering them and adding funky stuff like [edit]
3978 # links - this is for later, but we need the number of headlines right now
3980 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3982 # if there are fewer than 4 headlines in the article, do not show TOC
3983 # unless it's been explicitly enabled.
3984 $enoughToc = $this->mShowToc
&&
3985 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
3987 # Allow user to stipulate that a page should have a "new section"
3988 # link added via __NEWSECTIONLINK__
3989 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3990 $this->mOutput
->setNewSection( true );
3993 # Allow user to remove the "new section"
3994 # link via __NONEWSECTIONLINK__
3995 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3996 $this->mOutput
->hideNewSection( true );
3999 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
4000 # override above conditions and always show TOC above first header
4001 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4002 $this->mShowToc
= true;
4010 # Ugh .. the TOC should have neat indentation levels which can be
4011 # passed to the skin functions. These are determined here
4015 $sublevelCount = array();
4016 $levelCount = array();
4021 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4022 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4023 $oldType = $this->mOutputType
;
4024 $this->setOutputType( self
::OT_WIKI
);
4025 $frame = $this->getPreprocessor()->newFrame();
4026 $root = $this->preprocessToDom( $origText );
4027 $node = $root->getFirstChild();
4032 foreach ( $matches[3] as $headline ) {
4033 $isTemplate = false;
4035 $sectionIndex = false;
4037 $markerMatches = array();
4038 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
4039 $serial = $markerMatches[1];
4040 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4041 $isTemplate = ( $titleText != $baseTitleText );
4042 $headline = preg_replace( "/^$markerRegex/", "", $headline );
4046 $prevlevel = $level;
4048 $level = $matches[1][$headlineCount];
4050 if ( $level > $prevlevel ) {
4051 # Increase TOC level
4053 $sublevelCount[$toclevel] = 0;
4054 if ( $toclevel<$wgMaxTocLevel ) {
4055 $prevtoclevel = $toclevel;
4056 $toc .= Linker
::tocIndent();
4059 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4060 # Decrease TOC level, find level to jump to
4062 for ( $i = $toclevel; $i > 0; $i-- ) {
4063 if ( $levelCount[$i] == $level ) {
4064 # Found last matching level
4067 } elseif ( $levelCount[$i] < $level ) {
4068 # Found first matching level below current level
4076 if ( $toclevel<$wgMaxTocLevel ) {
4077 if ( $prevtoclevel < $wgMaxTocLevel ) {
4078 # Unindent only if the previous toc level was shown :p
4079 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4080 $prevtoclevel = $toclevel;
4082 $toc .= Linker
::tocLineEnd();
4086 # No change in level, end TOC line
4087 if ( $toclevel<$wgMaxTocLevel ) {
4088 $toc .= Linker
::tocLineEnd();
4092 $levelCount[$toclevel] = $level;
4094 # count number of headlines for each level
4095 @$sublevelCount[$toclevel]++
;
4097 for( $i = 1; $i <= $toclevel; $i++
) {
4098 if ( !empty( $sublevelCount[$i] ) ) {
4102 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4107 # The safe header is a version of the header text safe to use for links
4109 # Remove link placeholders by the link text.
4110 # <!--LINK number-->
4112 # link text with suffix
4113 # Do this before unstrip since link text can contain strip markers
4114 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4116 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4117 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4119 # Strip out HTML (first regex removes any tag not allowed)
4120 # Allowed tags are <sup> and <sub> (bug 8393), <i> (bug 26375) and <b> (r105284)
4121 # We strip any parameter from accepted tags (second regex)
4122 $tocline = preg_replace(
4123 array( '#<(?!/?(sup|sub|i|b)(?: [^>]*)?>).*?'.'>#', '#<(/?(sup|sub|i|b))(?: .*?)?'.'>#' ),
4124 array( '', '<$1>' ),
4127 $tocline = trim( $tocline );
4129 # For the anchor, strip out HTML-y stuff period
4130 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
4131 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4133 # Save headline for section edit hint before it's escaped
4134 $headlineHint = $safeHeadline;
4136 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
4137 # For reverse compatibility, provide an id that's
4138 # HTML4-compatible, like we used to.
4140 # It may be worth noting, academically, that it's possible for
4141 # the legacy anchor to conflict with a non-legacy headline
4142 # anchor on the page. In this case likely the "correct" thing
4143 # would be to either drop the legacy anchors or make sure
4144 # they're numbered first. However, this would require people
4145 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4146 # manually, so let's not bother worrying about it.
4147 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4148 array( 'noninitial', 'legacy' ) );
4149 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4151 if ( $legacyHeadline == $safeHeadline ) {
4152 # No reason to have both (in fact, we can't)
4153 $legacyHeadline = false;
4156 $legacyHeadline = false;
4157 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4161 # HTML names must be case-insensitively unique (bug 10721).
4162 # This does not apply to Unicode characters per
4163 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4164 # @todo FIXME: We may be changing them depending on the current locale.
4165 $arrayKey = strtolower( $safeHeadline );
4166 if ( $legacyHeadline === false ) {
4167 $legacyArrayKey = false;
4169 $legacyArrayKey = strtolower( $legacyHeadline );
4172 # count how many in assoc. array so we can track dupes in anchors
4173 if ( isset( $refers[$arrayKey] ) ) {
4174 $refers[$arrayKey]++
;
4176 $refers[$arrayKey] = 1;
4178 if ( isset( $refers[$legacyArrayKey] ) ) {
4179 $refers[$legacyArrayKey]++
;
4181 $refers[$legacyArrayKey] = 1;
4184 # Don't number the heading if it is the only one (looks silly)
4185 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4186 # the two are different if the line contains a link
4187 $headline = Html
::element( 'span', array( 'class' => 'mw-headline-number' ), $numbering ) . ' ' . $headline;
4190 # Create the anchor for linking from the TOC to the section
4191 $anchor = $safeHeadline;
4192 $legacyAnchor = $legacyHeadline;
4193 if ( $refers[$arrayKey] > 1 ) {
4194 $anchor .= '_' . $refers[$arrayKey];
4196 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4197 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4199 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4200 $toc .= Linker
::tocLine( $anchor, $tocline,
4201 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4204 # Add the section to the section tree
4205 # Find the DOM node for this header
4206 while ( $node && !$isTemplate ) {
4207 if ( $node->getName() === 'h' ) {
4208 $bits = $node->splitHeading();
4209 if ( $bits['i'] == $sectionIndex ) {
4213 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4214 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4215 $node = $node->getNextSibling();
4218 'toclevel' => $toclevel,
4221 'number' => $numbering,
4222 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4223 'fromtitle' => $titleText,
4224 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
4225 'anchor' => $anchor,
4228 # give headline the correct <h#> tag
4229 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4230 // Output edit section links as markers with styles that can be customized by skins
4231 if ( $isTemplate ) {
4232 # Put a T flag in the section identifier, to indicate to extractSections()
4233 # that sections inside <includeonly> should be counted.
4234 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4236 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
4238 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4239 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4240 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4241 // so we don't have to worry about a user trying to input one of these markers directly.
4242 // We use a page and section attribute to stop the language converter from converting these important bits
4243 // of data, but put the headline hint inside a content block because the language converter is supposed to
4244 // be able to convert that piece of data.
4245 $editlink = '<mw:editsection page="' . htmlspecialchars($editlinkArgs[0]);
4246 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"';
4247 if ( isset($editlinkArgs[2]) ) {
4248 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4255 $head[$headlineCount] = Linker
::makeHeadline( $level,
4256 $matches['attrib'][$headlineCount], $anchor, $headline,
4257 $editlink, $legacyAnchor );
4262 $this->setOutputType( $oldType );
4264 # Never ever show TOC if no headers
4265 if ( $numVisible < 1 ) {
4270 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4271 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4273 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4274 $this->mOutput
->setTOCHTML( $toc );
4278 $this->mOutput
->setSections( $tocraw );
4281 # split up and insert constructed headlines
4282 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4285 // build an array of document sections
4286 $sections = array();
4287 foreach ( $blocks as $block ) {
4288 // $head is zero-based, sections aren't.
4289 if ( empty( $head[$i - 1] ) ) {
4290 $sections[$i] = $block;
4292 $sections[$i] = $head[$i - 1] . $block;
4296 * Send a hook, one per section.
4297 * The idea here is to be able to make section-level DIVs, but to do so in a
4298 * lower-impact, more correct way than r50769
4301 * $section : the section number
4302 * &$sectionContent : ref to the content of the section
4303 * $showEditLinks : boolean describing whether this section has an edit link
4305 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4310 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4311 // append the TOC at the beginning
4312 // Top anchor now in skin
4313 $sections[0] = $sections[0] . $toc . "\n";
4316 $full .= join( '', $sections );
4318 if ( $this->mForceTocPosition
) {
4319 return str_replace( '<!--MWTOC-->', $toc, $full );
4326 * Transform wiki markup when saving a page by doing \r\n -> \n
4327 * conversion, substitting signatures, {{subst:}} templates, etc.
4329 * @param $text String: the text to transform
4330 * @param $title Title: the Title object for the current article
4331 * @param $user User: the User object describing the current user
4332 * @param $options ParserOptions: parsing options
4333 * @param $clearState Boolean: whether to clear the parser state first
4334 * @return String: the altered wiki markup
4336 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4337 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4338 $this->setUser( $user );
4343 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4344 if( $options->getPreSaveTransform() ) {
4345 $text = $this->pstPass2( $text, $user );
4347 $text = $this->mStripState
->unstripBoth( $text );
4349 $this->setUser( null ); #Reset
4355 * Pre-save transform helper function
4358 * @param $text string
4363 function pstPass2( $text, $user ) {
4364 global $wgContLang, $wgLocaltimezone;
4366 # Note: This is the timestamp saved as hardcoded wikitext to
4367 # the database, we use $wgContLang here in order to give
4368 # everyone the same signature and use the default one rather
4369 # than the one selected in each user's preferences.
4370 # (see also bug 12815)
4371 $ts = $this->mOptions
->getTimestamp();
4372 if ( isset( $wgLocaltimezone ) ) {
4373 $tz = $wgLocaltimezone;
4375 $tz = date_default_timezone_get();
4378 $unixts = wfTimestamp( TS_UNIX
, $ts );
4379 $oldtz = date_default_timezone_get();
4380 date_default_timezone_set( $tz );
4381 $ts = date( 'YmdHis', $unixts );
4382 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4384 # Allow translation of timezones through wiki. date() can return
4385 # whatever crap the system uses, localised or not, so we cannot
4386 # ship premade translations.
4387 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4388 $msg = wfMessage( $key )->inContentLanguage();
4389 if ( $msg->exists() ) {
4390 $tzMsg = $msg->text();
4393 date_default_timezone_set( $oldtz );
4395 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4397 # Variable replacement
4398 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4399 $text = $this->replaceVariables( $text );
4401 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4402 # which may corrupt this parser instance via its wfMsgExt( parsemag ) call-
4405 $sigText = $this->getUserSig( $user );
4406 $text = strtr( $text, array(
4408 '~~~~' => "$sigText $d",
4412 # Context links: [[|name]] and [[name (context)|]]
4413 $tc = '[' . Title
::legalChars() . ']';
4414 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4416 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4417 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]]
4418 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/"; # [[ns:page (context), context|]]
4419 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4421 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4422 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4423 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4424 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4426 $t = $this->mTitle
->getText();
4428 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4429 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4430 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4431 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4433 # if there's no context, don't bother duplicating the title
4434 $text = preg_replace( $p2, '[[\\1]]', $text );
4437 # Trim trailing whitespace
4438 $text = rtrim( $text );
4444 * Fetch the user's signature text, if any, and normalize to
4445 * validated, ready-to-insert wikitext.
4446 * If you have pre-fetched the nickname or the fancySig option, you can
4447 * specify them here to save a database query.
4448 * Do not reuse this parser instance after calling getUserSig(),
4449 * as it may have changed if it's the $wgParser.
4452 * @param $nickname String|bool nickname to use or false to use user's default nickname
4453 * @param $fancySig Boolean|null whether the nicknname is the complete signature
4454 * or null to use default value
4457 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4458 global $wgMaxSigChars;
4460 $username = $user->getName();
4462 # If not given, retrieve from the user object.
4463 if ( $nickname === false )
4464 $nickname = $user->getOption( 'nickname' );
4466 if ( is_null( $fancySig ) ) {
4467 $fancySig = $user->getBoolOption( 'fancysig' );
4470 $nickname = $nickname == null ?
$username : $nickname;
4472 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4473 $nickname = $username;
4474 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4475 } elseif ( $fancySig !== false ) {
4476 # Sig. might contain markup; validate this
4477 if ( $this->validateSig( $nickname ) !== false ) {
4478 # Validated; clean up (if needed) and return it
4479 return $this->cleanSig( $nickname, true );
4481 # Failed to validate; fall back to the default
4482 $nickname = $username;
4483 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4487 # Make sure nickname doesnt get a sig in a sig
4488 $nickname = self
::cleanSigInSig( $nickname );
4490 # If we're still here, make it a link to the user page
4491 $userText = wfEscapeWikiText( $username );
4492 $nickText = wfEscapeWikiText( $nickname );
4493 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4495 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4499 * Check that the user's signature contains no bad XML
4501 * @param $text String
4502 * @return mixed An expanded string, or false if invalid.
4504 function validateSig( $text ) {
4505 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4509 * Clean up signature text
4511 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4512 * 2) Substitute all transclusions
4514 * @param $text String
4515 * @param $parsing bool Whether we're cleaning (preferences save) or parsing
4516 * @return String: signature text
4518 public function cleanSig( $text, $parsing = false ) {
4521 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4524 # Option to disable this feature
4525 if ( !$this->mOptions
->getCleanSignatures() ) {
4529 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4530 # => Move this logic to braceSubstitution()
4531 $substWord = MagicWord
::get( 'subst' );
4532 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4533 $substText = '{{' . $substWord->getSynonym( 0 );
4535 $text = preg_replace( $substRegex, $substText, $text );
4536 $text = self
::cleanSigInSig( $text );
4537 $dom = $this->preprocessToDom( $text );
4538 $frame = $this->getPreprocessor()->newFrame();
4539 $text = $frame->expand( $dom );
4542 $text = $this->mStripState
->unstripBoth( $text );
4549 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4551 * @param $text String
4552 * @return String: signature text with /~{3,5}/ removed
4554 public static function cleanSigInSig( $text ) {
4555 $text = preg_replace( '/~{3,5}/', '', $text );
4560 * Set up some variables which are usually set up in parse()
4561 * so that an external function can call some class members with confidence
4563 * @param $title Title|null
4564 * @param $options ParserOptions
4565 * @param $outputType
4566 * @param $clearState bool
4568 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4569 $this->startParse( $title, $options, $outputType, $clearState );
4573 * @param $title Title|null
4574 * @param $options ParserOptions
4575 * @param $outputType
4576 * @param $clearState bool
4578 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4579 $this->setTitle( $title );
4580 $this->mOptions
= $options;
4581 $this->setOutputType( $outputType );
4582 if ( $clearState ) {
4583 $this->clearState();
4588 * Wrapper for preprocess()
4590 * @param $text String: the text to preprocess
4591 * @param $options ParserOptions: options
4592 * @param $title Title object or null to use $wgTitle
4595 public function transformMsg( $text, $options, $title = null ) {
4596 static $executing = false;
4598 # Guard against infinite recursion
4604 wfProfileIn( __METHOD__
);
4610 # It's not uncommon having a null $wgTitle in scripts. See r80898
4611 # Create a ghost title in such case
4612 $title = Title
::newFromText( 'Dwimmerlaik' );
4614 $text = $this->preprocess( $text, $title, $options );
4617 wfProfileOut( __METHOD__
);
4622 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4623 * The callback should have the following form:
4624 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4626 * Transform and return $text. Use $parser for any required context, e.g. use
4627 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4629 * Hooks may return extended information by returning an array, of which the
4630 * first numbered element (index 0) must be the return string, and all other
4631 * entries are extracted into local variables within an internal function
4632 * in the Parser class.
4634 * This interface (introduced r61913) appears to be undocumented, but
4635 * 'markerName' is used by some core tag hooks to override which strip
4636 * array their results are placed in. **Use great caution if attempting
4637 * this interface, as it is not documented and injudicious use could smash
4638 * private variables.**
4640 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4641 * @param $callback Mixed: the callback function (and object) to use for the tag
4642 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4644 public function setHook( $tag, $callback ) {
4645 $tag = strtolower( $tag );
4646 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4647 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4649 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4650 $this->mTagHooks
[$tag] = $callback;
4651 if ( !in_array( $tag, $this->mStripList
) ) {
4652 $this->mStripList
[] = $tag;
4659 * As setHook(), but letting the contents be parsed.
4661 * Transparent tag hooks are like regular XML-style tag hooks, except they
4662 * operate late in the transformation sequence, on HTML instead of wikitext.
4664 * This is probably obsoleted by things dealing with parser frames?
4665 * The only extension currently using it is geoserver.
4668 * @todo better document or deprecate this
4670 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4671 * @param $callback Mixed: the callback function (and object) to use for the tag
4672 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4674 function setTransparentTagHook( $tag, $callback ) {
4675 $tag = strtolower( $tag );
4676 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4677 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4679 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4680 $this->mTransparentTagHooks
[$tag] = $callback;
4686 * Remove all tag hooks
4688 function clearTagHooks() {
4689 $this->mTagHooks
= array();
4690 $this->mFunctionTagHooks
= array();
4691 $this->mStripList
= $this->mDefaultStripList
;
4695 * Create a function, e.g. {{sum:1|2|3}}
4696 * The callback function should have the form:
4697 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4699 * Or with SFH_OBJECT_ARGS:
4700 * function myParserFunction( $parser, $frame, $args ) { ... }
4702 * The callback may either return the text result of the function, or an array with the text
4703 * in element 0, and a number of flags in the other elements. The names of the flags are
4704 * specified in the keys. Valid flags are:
4705 * found The text returned is valid, stop processing the template. This
4707 * nowiki Wiki markup in the return value should be escaped
4708 * isHTML The returned text is HTML, armour it against wikitext transformation
4710 * @param $id String: The magic word ID
4711 * @param $callback Mixed: the callback function (and object) to use
4712 * @param $flags Integer: a combination of the following flags:
4713 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4715 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4716 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4717 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4718 * the arguments, and to control the way they are expanded.
4720 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4721 * arguments, for instance:
4722 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4724 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4725 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4726 * working if/when this is changed.
4728 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4731 * Please read the documentation in includes/parser/Preprocessor.php for more information
4732 * about the methods available in PPFrame and PPNode.
4734 * @return string|callback The old callback function for this name, if any
4736 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4739 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4740 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4742 # Add to function cache
4743 $mw = MagicWord
::get( $id );
4745 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4747 $synonyms = $mw->getSynonyms();
4748 $sensitive = intval( $mw->isCaseSensitive() );
4750 foreach ( $synonyms as $syn ) {
4752 if ( !$sensitive ) {
4753 $syn = $wgContLang->lc( $syn );
4756 if ( !( $flags & SFH_NO_HASH
) ) {
4759 # Remove trailing colon
4760 if ( substr( $syn, -1, 1 ) === ':' ) {
4761 $syn = substr( $syn, 0, -1 );
4763 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4769 * Get all registered function hook identifiers
4773 function getFunctionHooks() {
4774 return array_keys( $this->mFunctionHooks
);
4778 * Create a tag function, e.g. <test>some stuff</test>.
4779 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4780 * Unlike parser functions, their content is not preprocessed.
4783 function setFunctionTagHook( $tag, $callback, $flags ) {
4784 $tag = strtolower( $tag );
4785 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4786 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4787 $this->mFunctionTagHooks
[$tag] : null;
4788 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4790 if ( !in_array( $tag, $this->mStripList
) ) {
4791 $this->mStripList
[] = $tag;
4798 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
4799 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4800 * Placeholders created in Skin::makeLinkObj()
4802 * @param $text string
4803 * @param $options int
4805 * @return array of link CSS classes, indexed by PDBK.
4807 function replaceLinkHolders( &$text, $options = 0 ) {
4808 return $this->mLinkHolders
->replace( $text );
4812 * Replace <!--LINK--> link placeholders with plain text of links
4813 * (not HTML-formatted).
4815 * @param $text String
4818 function replaceLinkHoldersText( $text ) {
4819 return $this->mLinkHolders
->replaceText( $text );
4823 * Renders an image gallery from a text with one line per image.
4824 * text labels may be given by using |-style alternative text. E.g.
4825 * Image:one.jpg|The number "1"
4826 * Image:tree.jpg|A tree
4827 * given as text will return the HTML of a gallery with two images,
4828 * labeled 'The number "1"' and
4831 * @param string $text
4832 * @param array $params
4833 * @return string HTML
4835 function renderImageGallery( $text, $params ) {
4836 $ig = new ImageGallery();
4837 $ig->setContextTitle( $this->mTitle
);
4838 $ig->setShowBytes( false );
4839 $ig->setShowFilename( false );
4840 $ig->setParser( $this );
4841 $ig->setHideBadImages();
4842 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4844 if ( isset( $params['showfilename'] ) ) {
4845 $ig->setShowFilename( true );
4847 $ig->setShowFilename( false );
4849 if ( isset( $params['caption'] ) ) {
4850 $caption = $params['caption'];
4851 $caption = htmlspecialchars( $caption );
4852 $caption = $this->replaceInternalLinks( $caption );
4853 $ig->setCaptionHtml( $caption );
4855 if ( isset( $params['perrow'] ) ) {
4856 $ig->setPerRow( $params['perrow'] );
4858 if ( isset( $params['widths'] ) ) {
4859 $ig->setWidths( $params['widths'] );
4861 if ( isset( $params['heights'] ) ) {
4862 $ig->setHeights( $params['heights'] );
4865 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4867 $lines = StringUtils
::explode( "\n", $text );
4868 foreach ( $lines as $line ) {
4869 # match lines like these:
4870 # Image:someimage.jpg|This is some image
4872 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4874 if ( count( $matches ) == 0 ) {
4878 if ( strpos( $matches[0], '%' ) !== false ) {
4879 $matches[1] = rawurldecode( $matches[1] );
4881 $title = Title
::newFromText( $matches[1], NS_FILE
);
4882 if ( is_null( $title ) ) {
4883 # Bogus title. Ignore these so we don't bomb out later.
4890 if ( isset( $matches[3] ) ) {
4891 // look for an |alt= definition while trying not to break existing
4892 // captions with multiple pipes (|) in it, until a more sensible grammar
4893 // is defined for images in galleries
4895 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
4896 $parameterMatches = StringUtils
::explode('|', $matches[3]);
4897 $magicWordAlt = MagicWord
::get( 'img_alt' );
4898 $magicWordLink = MagicWord
::get( 'img_link' );
4900 foreach ( $parameterMatches as $parameterMatch ) {
4901 if ( $match = $magicWordAlt->matchVariableStartToEnd( $parameterMatch ) ) {
4902 $alt = $this->stripAltText( $match, false );
4904 elseif( $match = $magicWordLink->matchVariableStartToEnd( $parameterMatch ) ){
4905 $link = strip_tags($this->replaceLinkHoldersText($match));
4906 $chars = self
::EXT_LINK_URL_CLASS
;
4907 $prots = $this->mUrlProtocols
;
4908 //check to see if link matches an absolute url, if not then it must be a wiki link.
4909 if(!preg_match( "/^($prots)$chars+$/u", $link)){
4910 $localLinkTitle = Title
::newFromText($link);
4911 $link = $localLinkTitle->getLocalURL();
4915 // concatenate all other pipes
4916 $label .= '|' . $parameterMatch;
4919 // remove the first pipe
4920 $label = substr( $label, 1 );
4923 $ig->add( $title, $label, $alt ,$link);
4925 return $ig->toHTML();
4932 function getImageParams( $handler ) {
4934 $handlerClass = get_class( $handler );
4938 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4939 # Initialise static lists
4940 static $internalParamNames = array(
4941 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4942 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4943 'bottom', 'text-bottom' ),
4944 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4945 'upright', 'border', 'link', 'alt' ),
4947 static $internalParamMap;
4948 if ( !$internalParamMap ) {
4949 $internalParamMap = array();
4950 foreach ( $internalParamNames as $type => $names ) {
4951 foreach ( $names as $name ) {
4952 $magicName = str_replace( '-', '_', "img_$name" );
4953 $internalParamMap[$magicName] = array( $type, $name );
4958 # Add handler params
4959 $paramMap = $internalParamMap;
4961 $handlerParamMap = $handler->getParamMap();
4962 foreach ( $handlerParamMap as $magic => $paramName ) {
4963 $paramMap[$magic] = array( 'handler', $paramName );
4966 $this->mImageParams
[$handlerClass] = $paramMap;
4967 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4969 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4973 * Parse image options text and use it to make an image
4975 * @param $title Title
4976 * @param $options String
4977 * @param $holders LinkHolderArray|bool
4978 * @return string HTML
4980 function makeImage( $title, $options, $holders = false ) {
4981 # Check if the options text is of the form "options|alt text"
4983 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4984 # * left no resizing, just left align. label is used for alt= only
4985 # * right same, but right aligned
4986 # * none same, but not aligned
4987 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4988 # * center center the image
4989 # * frame Keep original image size, no magnify-button.
4990 # * framed Same as "frame"
4991 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4992 # * upright reduce width for upright images, rounded to full __0 px
4993 # * border draw a 1px border around the image
4994 # * alt Text for HTML alt attribute (defaults to empty)
4995 # * link Set the target of the image link. Can be external, interwiki, or local
4996 # vertical-align values (no % or length right now):
5006 $parts = StringUtils
::explode( "|", $options );
5008 # Give extensions a chance to select the file revision for us
5011 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5012 array( $this, $title, &$options, &$descQuery ) );
5013 # Fetch and register the file (file title may be different via hooks)
5014 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5017 $handler = $file ?
$file->getHandler() : false;
5019 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5022 $this->addTrackingCategory( 'broken-file-category' );
5025 # Process the input parameters
5027 $params = array( 'frame' => array(), 'handler' => array(),
5028 'horizAlign' => array(), 'vertAlign' => array() );
5029 foreach ( $parts as $part ) {
5030 $part = trim( $part );
5031 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5033 if ( isset( $paramMap[$magicName] ) ) {
5034 list( $type, $paramName ) = $paramMap[$magicName];
5036 # Special case; width and height come in one variable together
5037 if ( $type === 'handler' && $paramName === 'width' ) {
5039 # (bug 13500) In both cases (width/height and width only),
5040 # permit trailing "px" for backward compatibility.
5041 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
5042 $width = intval( $m[1] );
5043 $height = intval( $m[2] );
5044 if ( $handler->validateParam( 'width', $width ) ) {
5045 $params[$type]['width'] = $width;
5048 if ( $handler->validateParam( 'height', $height ) ) {
5049 $params[$type]['height'] = $height;
5052 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
5053 $width = intval( $value );
5054 if ( $handler->validateParam( 'width', $width ) ) {
5055 $params[$type]['width'] = $width;
5058 } # else no validation -- bug 13436
5060 if ( $type === 'handler' ) {
5061 # Validate handler parameter
5062 $validated = $handler->validateParam( $paramName, $value );
5064 # Validate internal parameters
5065 switch( $paramName ) {
5068 # @todo FIXME: Possibly check validity here for
5069 # manualthumb? downstream behavior seems odd with
5070 # missing manual thumbs.
5072 $value = $this->stripAltText( $value, $holders );
5075 $chars = self
::EXT_LINK_URL_CLASS
;
5076 $prots = $this->mUrlProtocols
;
5077 if ( $value === '' ) {
5078 $paramName = 'no-link';
5081 } elseif ( preg_match( "/^$prots/", $value ) ) {
5082 if ( preg_match( "/^($prots)$chars+$/u", $value, $m ) ) {
5083 $paramName = 'link-url';
5084 $this->mOutput
->addExternalLink( $value );
5085 if ( $this->mOptions
->getExternalLinkTarget() ) {
5086 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5091 $linkTitle = Title
::newFromText( $value );
5093 $paramName = 'link-title';
5094 $value = $linkTitle;
5095 $this->mOutput
->addLink( $linkTitle );
5101 # Most other things appear to be empty or numeric...
5102 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5107 $params[$type][$paramName] = $value;
5111 if ( !$validated ) {
5116 # Process alignment parameters
5117 if ( $params['horizAlign'] ) {
5118 $params['frame']['align'] = key( $params['horizAlign'] );
5120 if ( $params['vertAlign'] ) {
5121 $params['frame']['valign'] = key( $params['vertAlign'] );
5124 $params['frame']['caption'] = $caption;
5126 # Will the image be presented in a frame, with the caption below?
5127 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5128 isset( $params['frame']['framed'] ) ||
5129 isset( $params['frame']['thumbnail'] ) ||
5130 isset( $params['frame']['manualthumb'] );
5132 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5133 # came to also set the caption, ordinary text after the image -- which
5134 # makes no sense, because that just repeats the text multiple times in
5135 # screen readers. It *also* came to set the title attribute.
5137 # Now that we have an alt attribute, we should not set the alt text to
5138 # equal the caption: that's worse than useless, it just repeats the
5139 # text. This is the framed/thumbnail case. If there's no caption, we
5140 # use the unnamed parameter for alt text as well, just for the time be-
5141 # ing, if the unnamed param is set and the alt param is not.
5143 # For the future, we need to figure out if we want to tweak this more,
5144 # e.g., introducing a title= parameter for the title; ignoring the un-
5145 # named parameter entirely for images without a caption; adding an ex-
5146 # plicit caption= parameter and preserving the old magic unnamed para-
5148 if ( $imageIsFramed ) { # Framed image
5149 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5150 # No caption or alt text, add the filename as the alt text so
5151 # that screen readers at least get some description of the image
5152 $params['frame']['alt'] = $title->getText();
5154 # Do not set $params['frame']['title'] because tooltips don't make sense
5156 } else { # Inline image
5157 if ( !isset( $params['frame']['alt'] ) ) {
5158 # No alt text, use the "caption" for the alt text
5159 if ( $caption !== '') {
5160 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5162 # No caption, fall back to using the filename for the
5164 $params['frame']['alt'] = $title->getText();
5167 # Use the "caption" for the tooltip text
5168 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5171 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5173 # Linker does the rest
5174 $time = isset( $options['time'] ) ?
$options['time'] : false;
5175 $ret = Linker
::makeImageLink2( $title, $file, $params['frame'], $params['handler'],
5176 $time, $descQuery, $this->mOptions
->getThumbSize() );
5178 # Give the handler a chance to modify the parser object
5180 $handler->parserTransformHook( $this, $file );
5188 * @param $holders LinkHolderArray
5189 * @return mixed|String
5191 protected function stripAltText( $caption, $holders ) {
5192 # Strip bad stuff out of the title (tooltip). We can't just use
5193 # replaceLinkHoldersText() here, because if this function is called
5194 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5196 $tooltip = $holders->replaceText( $caption );
5198 $tooltip = $this->replaceLinkHoldersText( $caption );
5201 # make sure there are no placeholders in thumbnail attributes
5202 # that are later expanded to html- so expand them now and
5204 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5205 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5211 * Set a flag in the output object indicating that the content is dynamic and
5212 * shouldn't be cached.
5214 function disableCache() {
5215 wfDebug( "Parser output marked as uncacheable.\n" );
5216 if ( !$this->mOutput
) {
5217 throw new MWException( __METHOD__
.
5218 " can only be called when actually parsing something" );
5220 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5221 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5225 * Callback from the Sanitizer for expanding items found in HTML attribute
5226 * values, so they can be safely tested and escaped.
5228 * @param $text String
5229 * @param $frame PPFrame
5232 function attributeStripCallback( &$text, $frame = false ) {
5233 $text = $this->replaceVariables( $text, $frame );
5234 $text = $this->mStripState
->unstripBoth( $text );
5243 function getTags() {
5244 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
), array_keys( $this->mFunctionTagHooks
) );
5248 * Replace transparent tags in $text with the values given by the callbacks.
5250 * Transparent tag hooks are like regular XML-style tag hooks, except they
5251 * operate late in the transformation sequence, on HTML instead of wikitext.
5253 * @param $text string
5257 function replaceTransparentTags( $text ) {
5259 $elements = array_keys( $this->mTransparentTagHooks
);
5260 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5261 $replacements = array();
5263 foreach ( $matches as $marker => $data ) {
5264 list( $element, $content, $params, $tag ) = $data;
5265 $tagName = strtolower( $element );
5266 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5267 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
5271 $replacements[$marker] = $output;
5273 return strtr( $text, $replacements );
5277 * Break wikitext input into sections, and either pull or replace
5278 * some particular section's text.
5280 * External callers should use the getSection and replaceSection methods.
5282 * @param $text String: Page wikitext
5283 * @param $section String: a section identifier string of the form:
5284 * <flag1> - <flag2> - ... - <section number>
5286 * Currently the only recognised flag is "T", which means the target section number
5287 * was derived during a template inclusion parse, in other words this is a template
5288 * section edit link. If no flags are given, it was an ordinary section edit link.
5289 * This flag is required to avoid a section numbering mismatch when a section is
5290 * enclosed by <includeonly> (bug 6563).
5292 * The section number 0 pulls the text before the first heading; other numbers will
5293 * pull the given section along with its lower-level subsections. If the section is
5294 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5296 * Section 0 is always considered to exist, even if it only contains the empty
5297 * string. If $text is the empty string and section 0 is replaced, $newText is
5300 * @param $mode String: one of "get" or "replace"
5301 * @param $newText String: replacement text for section data.
5302 * @return String: for "get", the extracted section text.
5303 * for "replace", the whole page with the section replaced.
5305 private function extractSections( $text, $section, $mode, $newText='' ) {
5306 global $wgTitle; # not generally used but removes an ugly failure mode
5307 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5309 $frame = $this->getPreprocessor()->newFrame();
5311 # Process section extraction flags
5313 $sectionParts = explode( '-', $section );
5314 $sectionIndex = array_pop( $sectionParts );
5315 foreach ( $sectionParts as $part ) {
5316 if ( $part === 'T' ) {
5317 $flags |
= self
::PTD_FOR_INCLUSION
;
5321 # Check for empty input
5322 if ( strval( $text ) === '' ) {
5323 # Only sections 0 and T-0 exist in an empty document
5324 if ( $sectionIndex == 0 ) {
5325 if ( $mode === 'get' ) {
5331 if ( $mode === 'get' ) {
5339 # Preprocess the text
5340 $root = $this->preprocessToDom( $text, $flags );
5342 # <h> nodes indicate section breaks
5343 # They can only occur at the top level, so we can find them by iterating the root's children
5344 $node = $root->getFirstChild();
5346 # Find the target section
5347 if ( $sectionIndex == 0 ) {
5348 # Section zero doesn't nest, level=big
5349 $targetLevel = 1000;
5352 if ( $node->getName() === 'h' ) {
5353 $bits = $node->splitHeading();
5354 if ( $bits['i'] == $sectionIndex ) {
5355 $targetLevel = $bits['level'];
5359 if ( $mode === 'replace' ) {
5360 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5362 $node = $node->getNextSibling();
5368 if ( $mode === 'get' ) {
5375 # Find the end of the section, including nested sections
5377 if ( $node->getName() === 'h' ) {
5378 $bits = $node->splitHeading();
5379 $curLevel = $bits['level'];
5380 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5384 if ( $mode === 'get' ) {
5385 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5387 $node = $node->getNextSibling();
5390 # Write out the remainder (in replace mode only)
5391 if ( $mode === 'replace' ) {
5392 # Output the replacement text
5393 # Add two newlines on -- trailing whitespace in $newText is conventionally
5394 # stripped by the editor, so we need both newlines to restore the paragraph gap
5395 # Only add trailing whitespace if there is newText
5396 if ( $newText != "" ) {
5397 $outText .= $newText . "\n\n";
5401 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5402 $node = $node->getNextSibling();
5406 if ( is_string( $outText ) ) {
5407 # Re-insert stripped tags
5408 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5415 * This function returns the text of a section, specified by a number ($section).
5416 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5417 * the first section before any such heading (section 0).
5419 * If a section contains subsections, these are also returned.
5421 * @param $text String: text to look in
5422 * @param $section String: section identifier
5423 * @param $deftext String: default to return if section is not found
5424 * @return string text of the requested section
5426 public function getSection( $text, $section, $deftext='' ) {
5427 return $this->extractSections( $text, $section, "get", $deftext );
5431 * This function returns $oldtext after the content of the section
5432 * specified by $section has been replaced with $text. If the target
5433 * section does not exist, $oldtext is returned unchanged.
5435 * @param $oldtext String: former text of the article
5436 * @param $section int section identifier
5437 * @param $text String: replacing text
5438 * @return String: modified text
5440 public function replaceSection( $oldtext, $section, $text ) {
5441 return $this->extractSections( $oldtext, $section, "replace", $text );
5445 * Get the ID of the revision we are parsing
5447 * @return Mixed: integer or null
5449 function getRevisionId() {
5450 return $this->mRevisionId
;
5454 * Get the revision object for $this->mRevisionId
5456 * @return Revision|null either a Revision object or null
5458 protected function getRevisionObject() {
5459 if ( !is_null( $this->mRevisionObject
) ) {
5460 return $this->mRevisionObject
;
5462 if ( is_null( $this->mRevisionId
) ) {
5466 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5467 return $this->mRevisionObject
;
5471 * Get the timestamp associated with the current revision, adjusted for
5472 * the default server-local timestamp
5474 function getRevisionTimestamp() {
5475 if ( is_null( $this->mRevisionTimestamp
) ) {
5476 wfProfileIn( __METHOD__
);
5480 $revObject = $this->getRevisionObject();
5481 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5483 # The cryptic '' timezone parameter tells to use the site-default
5484 # timezone offset instead of the user settings.
5486 # Since this value will be saved into the parser cache, served
5487 # to other users, and potentially even used inside links and such,
5488 # it needs to be consistent for all visitors.
5489 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5491 wfProfileOut( __METHOD__
);
5493 return $this->mRevisionTimestamp
;
5497 * Get the name of the user that edited the last revision
5499 * @return String: user name
5501 function getRevisionUser() {
5502 if( is_null( $this->mRevisionUser
) ) {
5503 $revObject = $this->getRevisionObject();
5505 # if this template is subst: the revision id will be blank,
5506 # so just use the current user's name
5508 $this->mRevisionUser
= $revObject->getUserText();
5509 } elseif( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5510 $this->mRevisionUser
= $this->getUser()->getName();
5513 return $this->mRevisionUser
;
5517 * Mutator for $mDefaultSort
5519 * @param $sort string New value
5521 public function setDefaultSort( $sort ) {
5522 $this->mDefaultSort
= $sort;
5523 $this->mOutput
->setProperty( 'defaultsort', $sort );
5527 * Accessor for $mDefaultSort
5528 * Will use the empty string if none is set.
5530 * This value is treated as a prefix, so the
5531 * empty string is equivalent to sorting by
5536 public function getDefaultSort() {
5537 if ( $this->mDefaultSort
!== false ) {
5538 return $this->mDefaultSort
;
5545 * Accessor for $mDefaultSort
5546 * Unlike getDefaultSort(), will return false if none is set
5548 * @return string or false
5550 public function getCustomDefaultSort() {
5551 return $this->mDefaultSort
;
5555 * Try to guess the section anchor name based on a wikitext fragment
5556 * presumably extracted from a heading, for example "Header" from
5559 * @param $text string
5563 public function guessSectionNameFromWikiText( $text ) {
5564 # Strip out wikitext links(they break the anchor)
5565 $text = $this->stripSectionName( $text );
5566 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5567 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5571 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5572 * instead. For use in redirects, since IE6 interprets Redirect: headers
5573 * as something other than UTF-8 (apparently?), resulting in breakage.
5575 * @param $text String: The section name
5576 * @return string An anchor
5578 public function guessLegacySectionNameFromWikiText( $text ) {
5579 # Strip out wikitext links(they break the anchor)
5580 $text = $this->stripSectionName( $text );
5581 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5582 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5586 * Strips a text string of wikitext for use in a section anchor
5588 * Accepts a text string and then removes all wikitext from the
5589 * string and leaves only the resultant text (i.e. the result of
5590 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5591 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5592 * to create valid section anchors by mimicing the output of the
5593 * parser when headings are parsed.
5595 * @param $text String: text string to be stripped of wikitext
5596 * for use in a Section anchor
5597 * @return string Filtered text string
5599 public function stripSectionName( $text ) {
5600 # Strip internal link markup
5601 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5602 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5604 # Strip external link markup
5605 # @todo FIXME: Not tolerant to blank link text
5606 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5607 # on how many empty links there are on the page - need to figure that out.
5608 $text = preg_replace( '/\[(?:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5610 # Parse wikitext quotes (italics & bold)
5611 $text = $this->doQuotes( $text );
5614 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5619 * strip/replaceVariables/unstrip for preprocessor regression testing
5621 * @param $text string
5622 * @param $title Title
5623 * @param $options ParserOptions
5624 * @param $outputType int
5628 function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5629 $this->startParse( $title, $options, $outputType, true );
5631 $text = $this->replaceVariables( $text );
5632 $text = $this->mStripState
->unstripBoth( $text );
5633 $text = Sanitizer
::removeHTMLtags( $text );
5638 * @param $text string
5639 * @param $title Title
5640 * @param $options ParserOptions
5643 function testPst( $text, Title
$title, ParserOptions
$options ) {
5644 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5649 * @param $title Title
5650 * @param $options ParserOptions
5653 function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5654 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5658 * Call a callback function on all regions of the given text that are not
5659 * inside strip markers, and replace those regions with the return value
5660 * of the callback. For example, with input:
5664 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5665 * two strings will be replaced with the value returned by the callback in
5673 function markerSkipCallback( $s, $callback ) {
5676 while ( $i < strlen( $s ) ) {
5677 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5678 if ( $markerStart === false ) {
5679 $out .= call_user_func( $callback, substr( $s, $i ) );
5682 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5683 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5684 if ( $markerEnd === false ) {
5685 $out .= substr( $s, $markerStart );
5688 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5689 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5698 * Remove any strip markers found in the given text.
5700 * @param $text Input string
5703 function killMarkers( $text ) {
5704 return $this->mStripState
->killMarkers( $text );
5708 * Save the parser state required to convert the given half-parsed text to
5709 * HTML. "Half-parsed" in this context means the output of
5710 * recursiveTagParse() or internalParse(). This output has strip markers
5711 * from replaceVariables (extensionSubstitution() etc.), and link
5712 * placeholders from replaceLinkHolders().
5714 * Returns an array which can be serialized and stored persistently. This
5715 * array can later be loaded into another parser instance with
5716 * unserializeHalfParsedText(). The text can then be safely incorporated into
5717 * the return value of a parser hook.
5719 * @param $text string
5723 function serializeHalfParsedText( $text ) {
5724 wfProfileIn( __METHOD__
);
5727 'version' => self
::HALF_PARSED_VERSION
,
5728 'stripState' => $this->mStripState
->getSubState( $text ),
5729 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
5731 wfProfileOut( __METHOD__
);
5736 * Load the parser state given in the $data array, which is assumed to
5737 * have been generated by serializeHalfParsedText(). The text contents is
5738 * extracted from the array, and its markers are transformed into markers
5739 * appropriate for the current Parser instance. This transformed text is
5740 * returned, and can be safely included in the return value of a parser
5743 * If the $data array has been stored persistently, the caller should first
5744 * check whether it is still valid, by calling isValidHalfParsedText().
5746 * @param $data array Serialized data
5749 function unserializeHalfParsedText( $data ) {
5750 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
5751 throw new MWException( __METHOD__
.': invalid version' );
5754 # First, extract the strip state.
5755 $texts = array( $data['text'] );
5756 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
5758 # Now renumber links
5759 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
5761 # Should be good to go.
5766 * Returns true if the given array, presumed to be generated by
5767 * serializeHalfParsedText(), is compatible with the current version of the
5770 * @param $data Array
5774 function isValidHalfParsedText( $data ) {
5775 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;