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 );
368 $text = $this->mStripState
->unstripGeneral( $text );
370 # Clean up special characters, only run once, next-to-last before doBlockLevels
372 # french spaces, last one Guillemet-left
373 # only if there is something before the space
374 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 ',
375 # french spaces, Guillemet-right
376 '/(\\302\\253) /' => '\\1 ',
377 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
379 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
381 $text = $this->doBlockLevels( $text, $linestart );
383 $this->replaceLinkHolders( $text );
386 * The input doesn't get language converted if
388 * b) Content isn't converted
389 * c) It's a conversion table
390 * d) it is an interface message (which is in the user language)
392 if ( !( $wgDisableLangConversion
393 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
394 ||
$this->mTitle
->isConversionTable() ) )
396 # Run convert unconditionally in 1.18-compatible mode
397 global $wgBug34832TransitionalRollback;
398 if ( $wgBug34832TransitionalRollback ||
!$this->mOptions
->getInterfaceMessage() ) {
399 # The position of the convert() call should not be changed. it
400 # assumes that the links are all replaced and the only thing left
401 # is the <nowiki> mark.
402 $text = $this->getConverterLanguage()->convert( $text );
407 * A converted title will be provided in the output object if title and
408 * content conversion are enabled, the article text does not contain
409 * a conversion-suppressing double-underscore tag, and no
410 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
411 * automatic link conversion.
413 if ( !( $wgDisableLangConversion
414 ||
$wgDisableTitleConversion
415 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
416 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
417 ||
$this->mOutput
->getDisplayTitle() !== false ) )
419 $convruletitle = $this->getConverterLanguage()->getConvRuleTitle();
420 if ( $convruletitle ) {
421 $this->mOutput
->setTitleText( $convruletitle );
423 $titleText = $this->getConverterLanguage()->convertTitle( $title );
424 $this->mOutput
->setTitleText( $titleText );
428 $text = $this->mStripState
->unstripNoWiki( $text );
430 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
432 $text = $this->replaceTransparentTags( $text );
433 $text = $this->mStripState
->unstripGeneral( $text );
435 $text = Sanitizer
::normalizeCharReferences( $text );
437 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
438 $text = MWTidy
::tidy( $text );
440 # attempt to sanitize at least some nesting problems
441 # (bug #2702 and quite a few others)
443 # ''Something [http://www.cool.com cool''] -->
444 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
445 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
446 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
447 # fix up an anchor inside another anchor, only
448 # at least for a single single nested link (bug 3695)
449 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
450 '\\1\\2</a>\\3</a>\\1\\4</a>',
451 # fix div inside inline elements- doBlockLevels won't wrap a line which
452 # contains a div, so fix it up here; replace
453 # div with escaped text
454 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
455 '\\1\\3<div\\5>\\6</div>\\8\\9',
456 # remove empty italic or bold tag pairs, some
457 # introduced by rules above
458 '/<([bi])><\/\\1>/' => '',
461 $text = preg_replace(
462 array_keys( $tidyregs ),
463 array_values( $tidyregs ),
467 if ( $this->mExpensiveFunctionCount
> $this->mOptions
->getExpensiveParserFunctionLimit() ) {
468 $this->limitationWarn( 'expensive-parserfunction',
469 $this->mExpensiveFunctionCount
,
470 $this->mOptions
->getExpensiveParserFunctionLimit()
474 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
476 # Information on include size limits, for the benefit of users who try to skirt them
477 if ( $this->mOptions
->getEnableLimitReport() ) {
478 $max = $this->mOptions
->getMaxIncludeSize();
479 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/{$this->mOptions->getExpensiveParserFunctionLimit()}\n";
481 "NewPP limit report\n" .
482 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
483 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
484 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
485 "Highest expansion depth: {$this->mHighestExpansionDepth}/{$this->mOptions->getMaxPPExpandDepth()}\n".
487 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
488 $text .= "\n<!-- \n$limitReport-->\n";
490 $this->mOutput
->setText( $text );
492 $this->mRevisionId
= $oldRevisionId;
493 $this->mRevisionObject
= $oldRevisionObject;
494 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
495 $this->mRevisionUser
= $oldRevisionUser;
496 wfProfileOut( $fname );
497 wfProfileOut( __METHOD__
);
499 return $this->mOutput
;
503 * Recursive parser entry point that can be called from an extension tag
506 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
508 * @param $text String: text extension wants to have parsed
509 * @param $frame PPFrame: The frame to use for expanding any template variables
513 function recursiveTagParse( $text, $frame=false ) {
514 wfProfileIn( __METHOD__
);
515 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
516 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
517 $text = $this->internalParse( $text, false, $frame );
518 wfProfileOut( __METHOD__
);
523 * Expand templates and variables in the text, producing valid, static wikitext.
524 * Also removes comments.
525 * @return mixed|string
527 function preprocess( $text, Title
$title, ParserOptions
$options, $revid = null ) {
528 wfProfileIn( __METHOD__
);
529 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
530 if ( $revid !== null ) {
531 $this->mRevisionId
= $revid;
533 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
534 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
535 $text = $this->replaceVariables( $text );
536 $text = $this->mStripState
->unstripBoth( $text );
537 wfProfileOut( __METHOD__
);
542 * Recursive parser entry point that can be called from an extension tag
545 * @param $text String: text to be expanded
546 * @param $frame PPFrame: The frame to use for expanding any template variables
550 public function recursivePreprocess( $text, $frame = false ) {
551 wfProfileIn( __METHOD__
);
552 $text = $this->replaceVariables( $text, $frame );
553 $text = $this->mStripState
->unstripBoth( $text );
554 wfProfileOut( __METHOD__
);
559 * Process the wikitext for the ?preload= feature. (bug 5210)
561 * <noinclude>, <includeonly> etc. are parsed as for template transclusion,
562 * comments, templates, arguments, tags hooks and parser functions are untouched.
564 * @param $text String
565 * @param $title Title
566 * @param $options ParserOptions
569 public function getPreloadText( $text, Title
$title, ParserOptions
$options ) {
570 # Parser (re)initialisation
571 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
573 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
574 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
575 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
576 $text = $this->mStripState
->unstripBoth( $text );
581 * Get a random string
585 static public function getRandomString() {
586 return wfRandomString( 16 );
590 * Set the current user.
591 * Should only be used when doing pre-save transform.
593 * @param $user Mixed: User object or null (to reset)
595 function setUser( $user ) {
596 $this->mUser
= $user;
600 * Accessor for mUniqPrefix.
604 public function uniqPrefix() {
605 if ( !isset( $this->mUniqPrefix
) ) {
606 # @todo FIXME: This is probably *horribly wrong*
607 # LanguageConverter seems to want $wgParser's uniqPrefix, however
608 # if this is called for a parser cache hit, the parser may not
609 # have ever been initialized in the first place.
610 # Not really sure what the heck is supposed to be going on here.
612 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
614 return $this->mUniqPrefix
;
618 * Set the context title
622 function setTitle( $t ) {
623 if ( !$t ||
$t instanceof FakeTitle
) {
624 $t = Title
::newFromText( 'NO TITLE' );
627 if ( strval( $t->getFragment() ) !== '' ) {
628 # Strip the fragment to avoid various odd effects
629 $this->mTitle
= clone $t;
630 $this->mTitle
->setFragment( '' );
637 * Accessor for the Title object
639 * @return Title object
641 function getTitle() {
642 return $this->mTitle
;
646 * Accessor/mutator for the Title object
648 * @param $x Title object or null to just get the current one
649 * @return Title object
651 function Title( $x = null ) {
652 return wfSetVar( $this->mTitle
, $x );
656 * Set the output type
658 * @param $ot Integer: new value
660 function setOutputType( $ot ) {
661 $this->mOutputType
= $ot;
664 'html' => $ot == self
::OT_HTML
,
665 'wiki' => $ot == self
::OT_WIKI
,
666 'pre' => $ot == self
::OT_PREPROCESS
,
667 'plain' => $ot == self
::OT_PLAIN
,
672 * Accessor/mutator for the output type
674 * @param $x int|null New value or null to just get the current one
677 function OutputType( $x = null ) {
678 return wfSetVar( $this->mOutputType
, $x );
682 * Get the ParserOutput object
684 * @return ParserOutput object
686 function getOutput() {
687 return $this->mOutput
;
691 * Get the ParserOptions object
693 * @return ParserOptions object
695 function getOptions() {
696 return $this->mOptions
;
700 * Accessor/mutator for the ParserOptions object
702 * @param $x ParserOptions New value or null to just get the current one
703 * @return ParserOptions Current ParserOptions object
705 function Options( $x = null ) {
706 return wfSetVar( $this->mOptions
, $x );
712 function nextLinkID() {
713 return $this->mLinkID++
;
719 function setLinkID( $id ) {
720 $this->mLinkID
= $id;
724 * Get a language object for use in parser functions such as {{FORMATNUM:}}
727 function getFunctionLang() {
728 return $this->getTargetLanguage();
732 * Get the target language for the content being parsed. This is usually the
733 * language that the content is in.
735 function getTargetLanguage() {
736 $target = $this->mOptions
->getTargetLanguage();
737 if ( $target !== null ) {
739 } elseif( $this->mOptions
->getInterfaceMessage() ) {
740 return $this->mOptions
->getUserLangObj();
741 } elseif( is_null( $this->mTitle
) ) {
742 throw new MWException( __METHOD__
.': $this->mTitle is null' );
744 return $this->mTitle
->getPageLanguage();
748 * Get the language object for language conversion
750 function getConverterLanguage() {
751 global $wgBug34832TransitionalRollback, $wgContLang;
752 if ( $wgBug34832TransitionalRollback ) {
755 return $this->getTargetLanguage();
760 * Get a User object either from $this->mUser, if set, or from the
761 * ParserOptions object otherwise
763 * @return User object
766 if ( !is_null( $this->mUser
) ) {
769 return $this->mOptions
->getUser();
773 * Get a preprocessor object
775 * @return Preprocessor instance
777 function getPreprocessor() {
778 if ( !isset( $this->mPreprocessor
) ) {
779 $class = $this->mPreprocessorClass
;
780 $this->mPreprocessor
= new $class( $this );
782 return $this->mPreprocessor
;
786 * Replaces all occurrences of HTML-style comments and the given tags
787 * in the text with a random marker and returns the next text. The output
788 * parameter $matches will be an associative array filled with data in
790 * 'UNIQ-xxxxx' => array(
793 * array( 'param' => 'x' ),
794 * '<element param="x">tag content</element>' ) )
796 * @param $elements array list of element names. Comments are always extracted.
797 * @param $text string Source text string.
798 * @param $matches array Out parameter, Array: extracted tags
799 * @param $uniq_prefix string
800 * @return String: stripped text
802 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
807 $taglist = implode( '|', $elements );
808 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
810 while ( $text != '' ) {
811 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
813 if ( count( $p ) < 5 ) {
816 if ( count( $p ) > 5 ) {
830 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
831 $stripped .= $marker;
833 if ( $close === '/>' ) {
834 # Empty element tag, <tag />
839 if ( $element === '!--' ) {
842 $end = "/(<\\/$element\\s*>)/i";
844 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
846 if ( count( $q ) < 3 ) {
847 # No end tag -- let it run out to the end of the text.
856 $matches[$marker] = array( $element,
858 Sanitizer
::decodeTagAttributes( $attributes ),
859 "<$element$attributes$close$content$tail" );
865 * Get a list of strippable XML-like elements
869 function getStripList() {
870 return $this->mStripList
;
874 * Add an item to the strip state
875 * Returns the unique tag which must be inserted into the stripped text
876 * The tag will be replaced with the original text in unstrip()
878 * @param $text string
882 function insertStripItem( $text ) {
883 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
884 $this->mMarkerIndex++
;
885 $this->mStripState
->addGeneral( $rnd, $text );
890 * parse the wiki syntax used to render tables
895 function doTableStuff( $text ) {
896 wfProfileIn( __METHOD__
);
898 $lines = StringUtils
::explode( "\n", $text );
900 $td_history = array(); # Is currently a td tag open?
901 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
902 $tr_history = array(); # Is currently a tr tag open?
903 $tr_attributes = array(); # history of tr attributes
904 $has_opened_tr = array(); # Did this table open a <tr> element?
905 $indent_level = 0; # indent level of the table
907 foreach ( $lines as $outLine ) {
908 $line = trim( $outLine );
910 if ( $line === '' ) { # empty line, go to next line
911 $out .= $outLine."\n";
915 $first_character = $line[0];
918 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
919 # First check if we are starting a new table
920 $indent_level = strlen( $matches[1] );
922 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
923 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
925 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
926 array_push( $td_history , false );
927 array_push( $last_tag_history , '' );
928 array_push( $tr_history , false );
929 array_push( $tr_attributes , '' );
930 array_push( $has_opened_tr , false );
931 } elseif ( count( $td_history ) == 0 ) {
932 # Don't do any of the following
933 $out .= $outLine."\n";
935 } elseif ( substr( $line , 0 , 2 ) === '|}' ) {
936 # We are ending a table
937 $line = '</table>' . substr( $line , 2 );
938 $last_tag = array_pop( $last_tag_history );
940 if ( !array_pop( $has_opened_tr ) ) {
941 $line = "<tr><td></td></tr>{$line}";
944 if ( array_pop( $tr_history ) ) {
945 $line = "</tr>{$line}";
948 if ( array_pop( $td_history ) ) {
949 $line = "</{$last_tag}>{$line}";
951 array_pop( $tr_attributes );
952 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
953 } elseif ( substr( $line , 0 , 2 ) === '|-' ) {
954 # Now we have a table row
955 $line = preg_replace( '#^\|-+#', '', $line );
957 # Whats after the tag is now only attributes
958 $attributes = $this->mStripState
->unstripBoth( $line );
959 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
960 array_pop( $tr_attributes );
961 array_push( $tr_attributes, $attributes );
964 $last_tag = array_pop( $last_tag_history );
965 array_pop( $has_opened_tr );
966 array_push( $has_opened_tr , true );
968 if ( array_pop( $tr_history ) ) {
972 if ( array_pop( $td_history ) ) {
973 $line = "</{$last_tag}>{$line}";
977 array_push( $tr_history , false );
978 array_push( $td_history , false );
979 array_push( $last_tag_history , '' );
980 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line , 0 , 2 ) === '|+' ) {
981 # This might be cell elements, td, th or captions
982 if ( substr( $line , 0 , 2 ) === '|+' ) {
983 $first_character = '+';
984 $line = substr( $line , 1 );
987 $line = substr( $line , 1 );
989 if ( $first_character === '!' ) {
990 $line = str_replace( '!!' , '||' , $line );
993 # Split up multiple cells on the same line.
994 # FIXME : This can result in improper nesting of tags processed
995 # by earlier parser steps, but should avoid splitting up eg
996 # attribute values containing literal "||".
997 $cells = StringUtils
::explodeMarkup( '||' , $line );
1001 # Loop through each table cell
1002 foreach ( $cells as $cell ) {
1004 if ( $first_character !== '+' ) {
1005 $tr_after = array_pop( $tr_attributes );
1006 if ( !array_pop( $tr_history ) ) {
1007 $previous = "<tr{$tr_after}>\n";
1009 array_push( $tr_history , true );
1010 array_push( $tr_attributes , '' );
1011 array_pop( $has_opened_tr );
1012 array_push( $has_opened_tr , true );
1015 $last_tag = array_pop( $last_tag_history );
1017 if ( array_pop( $td_history ) ) {
1018 $previous = "</{$last_tag}>\n{$previous}";
1021 if ( $first_character === '|' ) {
1023 } elseif ( $first_character === '!' ) {
1025 } elseif ( $first_character === '+' ) {
1026 $last_tag = 'caption';
1031 array_push( $last_tag_history , $last_tag );
1033 # A cell could contain both parameters and data
1034 $cell_data = explode( '|' , $cell , 2 );
1036 # Bug 553: Note that a '|' inside an invalid link should not
1037 # be mistaken as delimiting cell parameters
1038 if ( strpos( $cell_data[0], '[[' ) !== false ) {
1039 $cell = "{$previous}<{$last_tag}>{$cell}";
1040 } elseif ( count( $cell_data ) == 1 ) {
1041 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
1043 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
1044 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
1045 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
1049 array_push( $td_history , true );
1052 $out .= $outLine . "\n";
1055 # Closing open td, tr && table
1056 while ( count( $td_history ) > 0 ) {
1057 if ( array_pop( $td_history ) ) {
1060 if ( array_pop( $tr_history ) ) {
1063 if ( !array_pop( $has_opened_tr ) ) {
1064 $out .= "<tr><td></td></tr>\n" ;
1067 $out .= "</table>\n";
1070 # Remove trailing line-ending (b/c)
1071 if ( substr( $out, -1 ) === "\n" ) {
1072 $out = substr( $out, 0, -1 );
1075 # special case: don't return empty table
1076 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
1080 wfProfileOut( __METHOD__
);
1086 * Helper function for parse() that transforms wiki markup into
1087 * HTML. Only called for $mOutputType == self::OT_HTML.
1091 * @param $text string
1092 * @param $isMain bool
1093 * @param $frame bool
1097 function internalParse( $text, $isMain = true, $frame = false ) {
1098 wfProfileIn( __METHOD__
);
1102 # Hook to suspend the parser in this state
1103 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1104 wfProfileOut( __METHOD__
);
1108 # if $frame is provided, then use $frame for replacing any variables
1110 # use frame depth to infer how include/noinclude tags should be handled
1111 # depth=0 means this is the top-level document; otherwise it's an included document
1112 if ( !$frame->depth
) {
1115 $flag = Parser
::PTD_FOR_INCLUSION
;
1117 $dom = $this->preprocessToDom( $text, $flag );
1118 $text = $frame->expand( $dom );
1120 # if $frame is not provided, then use old-style replaceVariables
1121 $text = $this->replaceVariables( $text );
1124 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1125 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1127 # Tables need to come after variable replacement for things to work
1128 # properly; putting them before other transformations should keep
1129 # exciting things like link expansions from showing up in surprising
1131 $text = $this->doTableStuff( $text );
1133 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1135 $text = $this->doDoubleUnderscore( $text );
1137 $text = $this->doHeadings( $text );
1138 if ( $this->mOptions
->getUseDynamicDates() ) {
1139 $df = DateFormatter
::getInstance();
1140 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1142 $text = $this->replaceInternalLinks( $text );
1143 $text = $this->doAllQuotes( $text );
1144 $text = $this->replaceExternalLinks( $text );
1146 # replaceInternalLinks may sometimes leave behind
1147 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1148 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
1150 $text = $this->doMagicLinks( $text );
1151 $text = $this->formatHeadings( $text, $origText, $isMain );
1153 wfProfileOut( __METHOD__
);
1158 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1159 * magic external links.
1164 * @param $text string
1168 function doMagicLinks( $text ) {
1169 wfProfileIn( __METHOD__
);
1170 $prots = wfUrlProtocolsWithoutProtRel();
1171 $urlChar = self
::EXT_LINK_URL_CLASS
;
1172 $text = preg_replace_callback(
1174 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1175 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1176 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1177 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1178 ISBN\s+(\b # m[5]: ISBN, capture number
1179 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1180 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1181 [0-9Xx] # check digit
1183 )!xu', array( &$this, 'magicLinkCallback' ), $text );
1184 wfProfileOut( __METHOD__
);
1189 * @throws MWException
1191 * @return HTML|string
1193 function magicLinkCallback( $m ) {
1194 if ( isset( $m[1] ) && $m[1] !== '' ) {
1197 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1200 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1201 # Free external link
1202 return $this->makeFreeExternalLink( $m[0] );
1203 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1205 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1208 $CssClass = 'mw-magiclink-rfc';
1210 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1212 $urlmsg = 'pubmedurl';
1213 $CssClass = 'mw-magiclink-pmid';
1216 throw new MWException( __METHOD__
.': unrecognised match type "' .
1217 substr( $m[0], 0, 20 ) . '"' );
1219 $url = wfMsgForContent( $urlmsg, $id );
1220 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1221 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1224 $num = strtr( $isbn, array(
1229 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1231 htmlspecialchars( $titleObj->getLocalUrl() ) .
1232 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1239 * Make a free external link, given a user-supplied URL
1241 * @param $url string
1243 * @return string HTML
1246 function makeFreeExternalLink( $url ) {
1247 wfProfileIn( __METHOD__
);
1251 # The characters '<' and '>' (which were escaped by
1252 # removeHTMLtags()) should not be included in
1253 # URLs, per RFC 2396.
1255 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1256 $trail = substr( $url, $m2[0][1] ) . $trail;
1257 $url = substr( $url, 0, $m2[0][1] );
1260 # Move trailing punctuation to $trail
1262 # If there is no left bracket, then consider right brackets fair game too
1263 if ( strpos( $url, '(' ) === false ) {
1267 $numSepChars = strspn( strrev( $url ), $sep );
1268 if ( $numSepChars ) {
1269 $trail = substr( $url, -$numSepChars ) . $trail;
1270 $url = substr( $url, 0, -$numSepChars );
1273 $url = Sanitizer
::cleanUrl( $url );
1275 # Is this an external image?
1276 $text = $this->maybeMakeExternalImage( $url );
1277 if ( $text === false ) {
1278 # Not an image, make a link
1279 $text = Linker
::makeExternalLink( $url,
1280 $this->getConverterLanguage()->markNoConversion($url), true, 'free',
1281 $this->getExternalLinkAttribs( $url ) );
1282 # Register it in the output object...
1283 # Replace unnecessary URL escape codes with their equivalent characters
1284 $pasteurized = self
::replaceUnusualEscapes( $url );
1285 $this->mOutput
->addExternalLink( $pasteurized );
1287 wfProfileOut( __METHOD__
);
1288 return $text . $trail;
1293 * Parse headers and return html
1297 * @param $text string
1301 function doHeadings( $text ) {
1302 wfProfileIn( __METHOD__
);
1303 for ( $i = 6; $i >= 1; --$i ) {
1304 $h = str_repeat( '=', $i );
1305 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1306 "<h$i>\\1</h$i>", $text );
1308 wfProfileOut( __METHOD__
);
1313 * Replace single quotes with HTML markup
1316 * @param $text string
1318 * @return string the altered text
1320 function doAllQuotes( $text ) {
1321 wfProfileIn( __METHOD__
);
1323 $lines = StringUtils
::explode( "\n", $text );
1324 foreach ( $lines as $line ) {
1325 $outtext .= $this->doQuotes( $line ) . "\n";
1327 $outtext = substr( $outtext, 0,-1 );
1328 wfProfileOut( __METHOD__
);
1333 * Helper function for doAllQuotes()
1335 * @param $text string
1339 public function doQuotes( $text ) {
1340 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1341 if ( count( $arr ) == 1 ) {
1344 # First, do some preliminary work. This may shift some apostrophes from
1345 # being mark-up to being text. It also counts the number of occurrences
1346 # of bold and italics mark-ups.
1349 for ( $i = 0; $i < count( $arr ); $i++
) {
1350 if ( ( $i %
2 ) == 1 ) {
1351 # If there are ever four apostrophes, assume the first is supposed to
1352 # be text, and the remaining three constitute mark-up for bold text.
1353 if ( strlen( $arr[$i] ) == 4 ) {
1356 } elseif ( strlen( $arr[$i] ) > 5 ) {
1357 # If there are more than 5 apostrophes in a row, assume they're all
1358 # text except for the last 5.
1359 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1362 # Count the number of occurrences of bold and italics mark-ups.
1363 # We are not counting sequences of five apostrophes.
1364 if ( strlen( $arr[$i] ) == 2 ) {
1366 } elseif ( strlen( $arr[$i] ) == 3 ) {
1368 } elseif ( strlen( $arr[$i] ) == 5 ) {
1375 # If there is an odd number of both bold and italics, it is likely
1376 # that one of the bold ones was meant to be an apostrophe followed
1377 # by italics. Which one we cannot know for certain, but it is more
1378 # likely to be one that has a single-letter word before it.
1379 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1381 $firstsingleletterword = -1;
1382 $firstmultiletterword = -1;
1384 foreach ( $arr as $r ) {
1385 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1386 $x1 = substr( $arr[$i-1], -1 );
1387 $x2 = substr( $arr[$i-1], -2, 1 );
1388 if ( $x1 === ' ' ) {
1389 if ( $firstspace == -1 ) {
1392 } elseif ( $x2 === ' ') {
1393 if ( $firstsingleletterword == -1 ) {
1394 $firstsingleletterword = $i;
1397 if ( $firstmultiletterword == -1 ) {
1398 $firstmultiletterword = $i;
1405 # If there is a single-letter word, use it!
1406 if ( $firstsingleletterword > -1 ) {
1407 $arr[$firstsingleletterword] = "''";
1408 $arr[$firstsingleletterword-1] .= "'";
1409 } elseif ( $firstmultiletterword > -1 ) {
1410 # If not, but there's a multi-letter word, use that one.
1411 $arr[$firstmultiletterword] = "''";
1412 $arr[$firstmultiletterword-1] .= "'";
1413 } elseif ( $firstspace > -1 ) {
1414 # ... otherwise use the first one that has neither.
1415 # (notice that it is possible for all three to be -1 if, for example,
1416 # there is only one pentuple-apostrophe in the line)
1417 $arr[$firstspace] = "''";
1418 $arr[$firstspace-1] .= "'";
1422 # Now let's actually convert our apostrophic mush to HTML!
1427 foreach ( $arr as $r ) {
1428 if ( ( $i %
2 ) == 0 ) {
1429 if ( $state === 'both' ) {
1435 if ( strlen( $r ) == 2 ) {
1436 if ( $state === 'i' ) {
1437 $output .= '</i>'; $state = '';
1438 } elseif ( $state === 'bi' ) {
1439 $output .= '</i>'; $state = 'b';
1440 } elseif ( $state === 'ib' ) {
1441 $output .= '</b></i><b>'; $state = 'b';
1442 } elseif ( $state === 'both' ) {
1443 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1444 } else { # $state can be 'b' or ''
1445 $output .= '<i>'; $state .= 'i';
1447 } elseif ( strlen( $r ) == 3 ) {
1448 if ( $state === 'b' ) {
1449 $output .= '</b>'; $state = '';
1450 } elseif ( $state === 'bi' ) {
1451 $output .= '</i></b><i>'; $state = 'i';
1452 } elseif ( $state === 'ib' ) {
1453 $output .= '</b>'; $state = 'i';
1454 } elseif ( $state === 'both' ) {
1455 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1456 } else { # $state can be 'i' or ''
1457 $output .= '<b>'; $state .= 'b';
1459 } elseif ( strlen( $r ) == 5 ) {
1460 if ( $state === 'b' ) {
1461 $output .= '</b><i>'; $state = 'i';
1462 } elseif ( $state === 'i' ) {
1463 $output .= '</i><b>'; $state = 'b';
1464 } elseif ( $state === 'bi' ) {
1465 $output .= '</i></b>'; $state = '';
1466 } elseif ( $state === 'ib' ) {
1467 $output .= '</b></i>'; $state = '';
1468 } elseif ( $state === 'both' ) {
1469 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1470 } else { # ($state == '')
1471 $buffer = ''; $state = 'both';
1477 # Now close all remaining tags. Notice that the order is important.
1478 if ( $state === 'b' ||
$state === 'ib' ) {
1481 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1484 if ( $state === 'bi' ) {
1487 # There might be lonely ''''', so make sure we have a buffer
1488 if ( $state === 'both' && $buffer ) {
1489 $output .= '<b><i>'.$buffer.'</i></b>';
1496 * Replace external links (REL)
1498 * Note: this is all very hackish and the order of execution matters a lot.
1499 * Make sure to run maintenance/parserTests.php if you change this code.
1503 * @param $text string
1507 function replaceExternalLinks( $text ) {
1508 wfProfileIn( __METHOD__
);
1510 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1511 $s = array_shift( $bits );
1514 while ( $i<count( $bits ) ) {
1516 $protocol = $bits[$i++
];
1517 $text = $bits[$i++
];
1518 $trail = $bits[$i++
];
1520 # The characters '<' and '>' (which were escaped by
1521 # removeHTMLtags()) should not be included in
1522 # URLs, per RFC 2396.
1524 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1525 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1526 $url = substr( $url, 0, $m2[0][1] );
1529 # If the link text is an image URL, replace it with an <img> tag
1530 # This happened by accident in the original parser, but some people used it extensively
1531 $img = $this->maybeMakeExternalImage( $text );
1532 if ( $img !== false ) {
1538 # Set linktype for CSS - if URL==text, link is essentially free
1539 $linktype = ( $text === $url ) ?
'free' : 'text';
1541 # No link text, e.g. [http://domain.tld/some.link]
1542 if ( $text == '' ) {
1544 $langObj = $this->getTargetLanguage();
1545 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1546 $linktype = 'autonumber';
1548 # Have link text, e.g. [http://domain.tld/some.link text]s
1550 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1553 $text = $this->getConverterLanguage()->markNoConversion( $text );
1555 $url = Sanitizer
::cleanUrl( $url );
1557 # Use the encoded URL
1558 # This means that users can paste URLs directly into the text
1559 # Funny characters like ö aren't valid in URLs anyway
1560 # This was changed in August 2004
1561 $s .= Linker
::makeExternalLink( $url, $text, false, $linktype,
1562 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1564 # Register link in the output object.
1565 # Replace unnecessary URL escape codes with the referenced character
1566 # This prevents spammers from hiding links from the filters
1567 $pasteurized = self
::replaceUnusualEscapes( $url );
1568 $this->mOutput
->addExternalLink( $pasteurized );
1571 wfProfileOut( __METHOD__
);
1576 * Get an associative array of additional HTML attributes appropriate for a
1577 * particular external link. This currently may include rel => nofollow
1578 * (depending on configuration, namespace, and the URL's domain) and/or a
1579 * target attribute (depending on configuration).
1581 * @param $url String|bool optional URL, to extract the domain from for rel =>
1582 * nofollow if appropriate
1583 * @return Array associative array of HTML attributes
1585 function getExternalLinkAttribs( $url = false ) {
1587 global $wgNoFollowLinks, $wgNoFollowNsExceptions, $wgNoFollowDomainExceptions;
1588 $ns = $this->mTitle
->getNamespace();
1589 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) &&
1590 !wfMatchesDomainList( $url, $wgNoFollowDomainExceptions ) )
1592 $attribs['rel'] = 'nofollow';
1594 if ( $this->mOptions
->getExternalLinkTarget() ) {
1595 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1601 * Replace unusual URL escape codes with their equivalent characters
1603 * @param $url String
1606 * @todo This can merge genuinely required bits in the path or query string,
1607 * breaking legit URLs. A proper fix would treat the various parts of
1608 * the URL differently; as a workaround, just use the output for
1609 * statistical records, not for actual linking/output.
1611 static function replaceUnusualEscapes( $url ) {
1612 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1613 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1617 * Callback function used in replaceUnusualEscapes().
1618 * Replaces unusual URL escape codes with their equivalent character
1620 * @param $matches array
1624 private static function replaceUnusualEscapesCallback( $matches ) {
1625 $char = urldecode( $matches[0] );
1626 $ord = ord( $char );
1627 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1628 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1629 # No, shouldn't be escaped
1632 # Yes, leave it escaped
1638 * make an image if it's allowed, either through the global
1639 * option, through the exception, or through the on-wiki whitelist
1642 * $param $url string
1646 function maybeMakeExternalImage( $url ) {
1647 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1648 $imagesexception = !empty( $imagesfrom );
1650 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1651 if ( $imagesexception && is_array( $imagesfrom ) ) {
1652 $imagematch = false;
1653 foreach ( $imagesfrom as $match ) {
1654 if ( strpos( $url, $match ) === 0 ) {
1659 } elseif ( $imagesexception ) {
1660 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1662 $imagematch = false;
1664 if ( $this->mOptions
->getAllowExternalImages()
1665 ||
( $imagesexception && $imagematch ) ) {
1666 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1668 $text = Linker
::makeExternalImage( $url );
1671 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1672 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1673 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1674 foreach ( $whitelist as $entry ) {
1675 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1676 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1679 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1680 # Image matches a whitelist entry
1681 $text = Linker
::makeExternalImage( $url );
1690 * Process [[ ]] wikilinks
1694 * @return String: processed text
1698 function replaceInternalLinks( $s ) {
1699 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1704 * Process [[ ]] wikilinks (RIL)
1705 * @return LinkHolderArray
1709 function replaceInternalLinks2( &$s ) {
1710 wfProfileIn( __METHOD__
);
1712 wfProfileIn( __METHOD__
.'-setup' );
1713 static $tc = FALSE, $e1, $e1_img;
1714 # the % is needed to support urlencoded titles as well
1716 $tc = Title
::legalChars() . '#%';
1717 # Match a link having the form [[namespace:link|alternate]]trail
1718 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1719 # Match cases where there is no "]]", which might still be images
1720 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1723 $holders = new LinkHolderArray( $this );
1725 # split the entire text string on occurrences of [[
1726 $a = StringUtils
::explode( '[[', ' ' . $s );
1727 # get the first element (all text up to first [[), and remove the space we added
1730 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1731 $s = substr( $s, 1 );
1733 $useLinkPrefixExtension = $this->getTargetLanguage()->linkPrefixExtension();
1735 if ( $useLinkPrefixExtension ) {
1736 # Match the end of a line for a word that's not followed by whitespace,
1737 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1738 $e2 = wfMsgForContent( 'linkprefix' );
1741 if ( is_null( $this->mTitle
) ) {
1742 wfProfileOut( __METHOD__
.'-setup' );
1743 wfProfileOut( __METHOD__
);
1744 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1746 $nottalk = !$this->mTitle
->isTalkPage();
1748 if ( $useLinkPrefixExtension ) {
1750 if ( preg_match( $e2, $s, $m ) ) {
1751 $first_prefix = $m[2];
1753 $first_prefix = false;
1759 if ( $this->getConverterLanguage()->hasVariants() ) {
1760 $selflink = $this->getConverterLanguage()->autoConvertToAllVariants(
1761 $this->mTitle
->getPrefixedText() );
1763 $selflink = array( $this->mTitle
->getPrefixedText() );
1765 $useSubpages = $this->areSubpagesAllowed();
1766 wfProfileOut( __METHOD__
.'-setup' );
1768 # Loop for each link
1769 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1770 # Check for excessive memory usage
1771 if ( $holders->isBig() ) {
1773 # Do the existence check, replace the link holders and clear the array
1774 $holders->replace( $s );
1778 if ( $useLinkPrefixExtension ) {
1779 wfProfileIn( __METHOD__
.'-prefixhandling' );
1780 if ( preg_match( $e2, $s, $m ) ) {
1787 if ( $first_prefix ) {
1788 $prefix = $first_prefix;
1789 $first_prefix = false;
1791 wfProfileOut( __METHOD__
.'-prefixhandling' );
1794 $might_be_img = false;
1796 wfProfileIn( __METHOD__
."-e1" );
1797 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1799 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1800 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1801 # the real problem is with the $e1 regex
1804 # Still some problems for cases where the ] is meant to be outside punctuation,
1805 # and no image is in sight. See bug 2095.
1807 if ( $text !== '' &&
1808 substr( $m[3], 0, 1 ) === ']' &&
1809 strpos( $text, '[' ) !== false
1812 $text .= ']'; # so that replaceExternalLinks($text) works later
1813 $m[3] = substr( $m[3], 1 );
1815 # fix up urlencoded title texts
1816 if ( strpos( $m[1], '%' ) !== false ) {
1817 # Should anchors '#' also be rejected?
1818 $m[1] = str_replace( array('<', '>'), array('<', '>'), rawurldecode( $m[1] ) );
1821 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1822 $might_be_img = true;
1824 if ( strpos( $m[1], '%' ) !== false ) {
1825 $m[1] = rawurldecode( $m[1] );
1828 } else { # Invalid form; output directly
1829 $s .= $prefix . '[[' . $line ;
1830 wfProfileOut( __METHOD__
."-e1" );
1833 wfProfileOut( __METHOD__
."-e1" );
1834 wfProfileIn( __METHOD__
."-misc" );
1836 # Don't allow internal links to pages containing
1837 # PROTO: where PROTO is a valid URL protocol; these
1838 # should be external links.
1839 if ( preg_match( '/^(?:' . $this->mUrlProtocols
. ')/', $m[1] ) ) {
1840 $s .= $prefix . '[[' . $line ;
1841 wfProfileOut( __METHOD__
."-misc" );
1845 # Make subpage if necessary
1846 if ( $useSubpages ) {
1847 $link = $this->maybeDoSubpageLink( $m[1], $text );
1852 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1854 # Strip off leading ':'
1855 $link = substr( $link, 1 );
1858 wfProfileOut( __METHOD__
."-misc" );
1859 wfProfileIn( __METHOD__
."-title" );
1860 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1861 if ( $nt === null ) {
1862 $s .= $prefix . '[[' . $line;
1863 wfProfileOut( __METHOD__
."-title" );
1867 $ns = $nt->getNamespace();
1868 $iw = $nt->getInterWiki();
1869 wfProfileOut( __METHOD__
."-title" );
1871 if ( $might_be_img ) { # if this is actually an invalid link
1872 wfProfileIn( __METHOD__
."-might_be_img" );
1873 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1876 # look at the next 'line' to see if we can close it there
1878 $next_line = $a->current();
1879 if ( $next_line === false ||
$next_line === null ) {
1882 $m = explode( ']]', $next_line, 3 );
1883 if ( count( $m ) == 3 ) {
1884 # the first ]] closes the inner link, the second the image
1886 $text .= "[[{$m[0]}]]{$m[1]}";
1889 } elseif ( count( $m ) == 2 ) {
1890 # if there's exactly one ]] that's fine, we'll keep looking
1891 $text .= "[[{$m[0]}]]{$m[1]}";
1893 # if $next_line is invalid too, we need look no further
1894 $text .= '[[' . $next_line;
1899 # we couldn't find the end of this imageLink, so output it raw
1900 # but don't ignore what might be perfectly normal links in the text we've examined
1901 $holders->merge( $this->replaceInternalLinks2( $text ) );
1902 $s .= "{$prefix}[[$link|$text";
1903 # note: no $trail, because without an end, there *is* no trail
1904 wfProfileOut( __METHOD__
."-might_be_img" );
1907 } else { # it's not an image, so output it raw
1908 $s .= "{$prefix}[[$link|$text";
1909 # note: no $trail, because without an end, there *is* no trail
1910 wfProfileOut( __METHOD__
."-might_be_img" );
1913 wfProfileOut( __METHOD__
."-might_be_img" );
1916 $wasblank = ( $text == '' );
1920 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1921 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1922 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1923 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1924 $text = $this->doQuotes( $text );
1927 # Link not escaped by : , create the various objects
1930 wfProfileIn( __METHOD__
."-interwiki" );
1931 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && Language
::fetchLanguageName( $iw, null, 'mw' ) ) {
1932 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1933 $s = rtrim( $s . $prefix );
1934 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1935 wfProfileOut( __METHOD__
."-interwiki" );
1938 wfProfileOut( __METHOD__
."-interwiki" );
1940 if ( $ns == NS_FILE
) {
1941 wfProfileIn( __METHOD__
."-image" );
1942 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1944 # if no parameters were passed, $text
1945 # becomes something like "File:Foo.png",
1946 # which we don't want to pass on to the
1950 # recursively parse links inside the image caption
1951 # actually, this will parse them in any other parameters, too,
1952 # but it might be hard to fix that, and it doesn't matter ATM
1953 $text = $this->replaceExternalLinks( $text );
1954 $holders->merge( $this->replaceInternalLinks2( $text ) );
1956 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1957 $s .= $prefix . $this->armorLinks(
1958 $this->makeImage( $nt, $text, $holders ) ) . $trail;
1960 $s .= $prefix . $trail;
1962 wfProfileOut( __METHOD__
."-image" );
1966 if ( $ns == NS_CATEGORY
) {
1967 wfProfileIn( __METHOD__
."-category" );
1968 $s = rtrim( $s . "\n" ); # bug 87
1971 $sortkey = $this->getDefaultSort();
1975 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1976 $sortkey = str_replace( "\n", '', $sortkey );
1977 $sortkey = $this->getConverterLanguage()->convertCategoryKey( $sortkey );
1978 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1981 * Strip the whitespace Category links produce, see bug 87
1982 * @todo We might want to use trim($tmp, "\n") here.
1984 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
1986 wfProfileOut( __METHOD__
."-category" );
1991 # Self-link checking
1992 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1993 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1994 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
1999 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2000 # @todo FIXME: Should do batch file existence checks, see comment below
2001 if ( $ns == NS_MEDIA
) {
2002 wfProfileIn( __METHOD__
."-media" );
2003 # Give extensions a chance to select the file revision for us
2006 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2007 array( $this, $nt, &$options, &$descQuery ) );
2008 # Fetch and register the file (file title may be different via hooks)
2009 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $options );
2010 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2011 $s .= $prefix . $this->armorLinks(
2012 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2013 wfProfileOut( __METHOD__
."-media" );
2017 wfProfileIn( __METHOD__
."-always_known" );
2018 # Some titles, such as valid special pages or files in foreign repos, should
2019 # be shown as bluelinks even though they're not included in the page table
2021 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2022 # batch file existence checks for NS_FILE and NS_MEDIA
2023 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2024 $this->mOutput
->addLink( $nt );
2025 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2027 # Links will be added to the output link list after checking
2028 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2030 wfProfileOut( __METHOD__
."-always_known" );
2032 wfProfileOut( __METHOD__
);
2037 * Render a forced-blue link inline; protect against double expansion of
2038 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2039 * Since this little disaster has to split off the trail text to avoid
2040 * breaking URLs in the following text without breaking trails on the
2041 * wiki links, it's been made into a horrible function.
2044 * @param $text String
2045 * @param $query Array or String
2046 * @param $trail String
2047 * @param $prefix String
2048 * @return String: HTML-wikitext mix oh yuck
2050 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2051 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2053 if ( is_string( $query ) ) {
2054 $query = wfCgiToArray( $query );
2056 if ( $text == '' ) {
2057 $text = htmlspecialchars( $nt->getPrefixedText() );
2060 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2062 return $this->armorLinks( $link ) . $trail;
2066 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2067 * going to go through further parsing steps before inline URL expansion.
2069 * Not needed quite as much as it used to be since free links are a bit
2070 * more sensible these days. But bracketed links are still an issue.
2072 * @param $text String: more-or-less HTML
2073 * @return String: less-or-more HTML with NOPARSE bits
2075 function armorLinks( $text ) {
2076 return preg_replace( '/\b(' . $this->mUrlProtocols
. ')/',
2077 "{$this->mUniqPrefix}NOPARSE$1", $text );
2081 * Return true if subpage links should be expanded on this page.
2084 function areSubpagesAllowed() {
2085 # Some namespaces don't allow subpages
2086 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2090 * Handle link to subpage if necessary
2092 * @param $target String: the source of the link
2093 * @param &$text String: the link text, modified as necessary
2094 * @return string the full name of the link
2097 function maybeDoSubpageLink( $target, &$text ) {
2098 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2102 * Used by doBlockLevels()
2107 function closeParagraph() {
2109 if ( $this->mLastSection
!= '' ) {
2110 $result = '</' . $this->mLastSection
. ">\n";
2112 $this->mInPre
= false;
2113 $this->mLastSection
= '';
2118 * getCommon() returns the length of the longest common substring
2119 * of both arguments, starting at the beginning of both.
2122 * @param $st1 string
2123 * @param $st2 string
2127 function getCommon( $st1, $st2 ) {
2128 $fl = strlen( $st1 );
2129 $shorter = strlen( $st2 );
2130 if ( $fl < $shorter ) {
2134 for ( $i = 0; $i < $shorter; ++
$i ) {
2135 if ( $st1[$i] != $st2[$i] ) {
2143 * These next three functions open, continue, and close the list
2144 * element appropriate to the prefix character passed into them.
2147 * @param $char string
2151 function openList( $char ) {
2152 $result = $this->closeParagraph();
2154 if ( '*' === $char ) {
2155 $result .= '<ul><li>';
2156 } elseif ( '#' === $char ) {
2157 $result .= '<ol><li>';
2158 } elseif ( ':' === $char ) {
2159 $result .= '<dl><dd>';
2160 } elseif ( ';' === $char ) {
2161 $result .= '<dl><dt>';
2162 $this->mDTopen
= true;
2164 $result = '<!-- ERR 1 -->';
2172 * @param $char String
2177 function nextItem( $char ) {
2178 if ( '*' === $char ||
'#' === $char ) {
2180 } elseif ( ':' === $char ||
';' === $char ) {
2182 if ( $this->mDTopen
) {
2185 if ( ';' === $char ) {
2186 $this->mDTopen
= true;
2187 return $close . '<dt>';
2189 $this->mDTopen
= false;
2190 return $close . '<dd>';
2193 return '<!-- ERR 2 -->';
2198 * @param $char String
2203 function closeList( $char ) {
2204 if ( '*' === $char ) {
2205 $text = '</li></ul>';
2206 } elseif ( '#' === $char ) {
2207 $text = '</li></ol>';
2208 } elseif ( ':' === $char ) {
2209 if ( $this->mDTopen
) {
2210 $this->mDTopen
= false;
2211 $text = '</dt></dl>';
2213 $text = '</dd></dl>';
2216 return '<!-- ERR 3 -->';
2223 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2225 * @param $text String
2226 * @param $linestart Boolean: whether or not this is at the start of a line.
2228 * @return string the lists rendered as HTML
2230 function doBlockLevels( $text, $linestart ) {
2231 wfProfileIn( __METHOD__
);
2233 # Parsing through the text line by line. The main thing
2234 # happening here is handling of block-level elements p, pre,
2235 # and making lists from lines starting with * # : etc.
2237 $textLines = StringUtils
::explode( "\n", $text );
2239 $lastPrefix = $output = '';
2240 $this->mDTopen
= $inBlockElem = false;
2242 $paragraphStack = false;
2244 foreach ( $textLines as $oLine ) {
2246 if ( !$linestart ) {
2256 $lastPrefixLength = strlen( $lastPrefix );
2257 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2258 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2259 # If not in a <pre> element, scan for and figure out what prefixes are there.
2260 if ( !$this->mInPre
) {
2261 # Multiple prefixes may abut each other for nested lists.
2262 $prefixLength = strspn( $oLine, '*#:;' );
2263 $prefix = substr( $oLine, 0, $prefixLength );
2266 # ; and : are both from definition-lists, so they're equivalent
2267 # for the purposes of determining whether or not we need to open/close
2269 $prefix2 = str_replace( ';', ':', $prefix );
2270 $t = substr( $oLine, $prefixLength );
2271 $this->mInPre
= (bool)$preOpenMatch;
2273 # Don't interpret any other prefixes in preformatted text
2275 $prefix = $prefix2 = '';
2280 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2281 # Same as the last item, so no need to deal with nesting or opening stuff
2282 $output .= $this->nextItem( substr( $prefix, -1 ) );
2283 $paragraphStack = false;
2285 if ( substr( $prefix, -1 ) === ';') {
2286 # The one nasty exception: definition lists work like this:
2287 # ; title : definition text
2288 # So we check for : in the remainder text to split up the
2289 # title and definition, without b0rking links.
2291 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2293 $output .= $term . $this->nextItem( ':' );
2296 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2297 # We need to open or close prefixes, or both.
2299 # Either open or close a level...
2300 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2301 $paragraphStack = false;
2303 # Close all the prefixes which aren't shared.
2304 while ( $commonPrefixLength < $lastPrefixLength ) {
2305 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2306 --$lastPrefixLength;
2309 # Continue the current prefix if appropriate.
2310 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2311 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2314 # Open prefixes where appropriate.
2315 while ( $prefixLength > $commonPrefixLength ) {
2316 $char = substr( $prefix, $commonPrefixLength, 1 );
2317 $output .= $this->openList( $char );
2319 if ( ';' === $char ) {
2320 # @todo FIXME: This is dupe of code above
2321 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2323 $output .= $term . $this->nextItem( ':' );
2326 ++
$commonPrefixLength;
2328 $lastPrefix = $prefix2;
2331 # If we have no prefixes, go to paragraph mode.
2332 if ( 0 == $prefixLength ) {
2333 wfProfileIn( __METHOD__
."-paragraph" );
2334 # No prefix (not in list)--go to paragraph mode
2335 # XXX: use a stack for nestable elements like span, table and div
2336 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2337 $closematch = preg_match(
2338 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2339 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2340 if ( $openmatch or $closematch ) {
2341 $paragraphStack = false;
2342 # TODO bug 5718: paragraph closed
2343 $output .= $this->closeParagraph();
2344 if ( $preOpenMatch and !$preCloseMatch ) {
2345 $this->mInPre
= true;
2347 $inBlockElem = !$closematch;
2348 } elseif ( !$inBlockElem && !$this->mInPre
) {
2349 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2351 if ( $this->mLastSection
!== 'pre' ) {
2352 $paragraphStack = false;
2353 $output .= $this->closeParagraph().'<pre>';
2354 $this->mLastSection
= 'pre';
2356 $t = substr( $t, 1 );
2359 if ( trim( $t ) === '' ) {
2360 if ( $paragraphStack ) {
2361 $output .= $paragraphStack.'<br />';
2362 $paragraphStack = false;
2363 $this->mLastSection
= 'p';
2365 if ( $this->mLastSection
!== 'p' ) {
2366 $output .= $this->closeParagraph();
2367 $this->mLastSection
= '';
2368 $paragraphStack = '<p>';
2370 $paragraphStack = '</p><p>';
2374 if ( $paragraphStack ) {
2375 $output .= $paragraphStack;
2376 $paragraphStack = false;
2377 $this->mLastSection
= 'p';
2378 } elseif ( $this->mLastSection
!== 'p' ) {
2379 $output .= $this->closeParagraph().'<p>';
2380 $this->mLastSection
= 'p';
2385 wfProfileOut( __METHOD__
."-paragraph" );
2387 # somewhere above we forget to get out of pre block (bug 785)
2388 if ( $preCloseMatch && $this->mInPre
) {
2389 $this->mInPre
= false;
2391 if ( $paragraphStack === false ) {
2395 while ( $prefixLength ) {
2396 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2399 if ( $this->mLastSection
!= '' ) {
2400 $output .= '</' . $this->mLastSection
. '>';
2401 $this->mLastSection
= '';
2404 wfProfileOut( __METHOD__
);
2409 * Split up a string on ':', ignoring any occurrences inside tags
2410 * to prevent illegal overlapping.
2412 * @param $str String the string to split
2413 * @param &$before String set to everything before the ':'
2414 * @param &$after String set to everything after the ':'
2415 * @return String the position of the ':', or false if none found
2417 function findColonNoLinks( $str, &$before, &$after ) {
2418 wfProfileIn( __METHOD__
);
2420 $pos = strpos( $str, ':' );
2421 if ( $pos === false ) {
2423 wfProfileOut( __METHOD__
);
2427 $lt = strpos( $str, '<' );
2428 if ( $lt === false ||
$lt > $pos ) {
2429 # Easy; no tag nesting to worry about
2430 $before = substr( $str, 0, $pos );
2431 $after = substr( $str, $pos+
1 );
2432 wfProfileOut( __METHOD__
);
2436 # Ugly state machine to walk through avoiding tags.
2437 $state = self
::COLON_STATE_TEXT
;
2439 $len = strlen( $str );
2440 for( $i = 0; $i < $len; $i++
) {
2444 # (Using the number is a performance hack for common cases)
2445 case 0: # self::COLON_STATE_TEXT:
2448 # Could be either a <start> tag or an </end> tag
2449 $state = self
::COLON_STATE_TAGSTART
;
2452 if ( $stack == 0 ) {
2454 $before = substr( $str, 0, $i );
2455 $after = substr( $str, $i +
1 );
2456 wfProfileOut( __METHOD__
);
2459 # Embedded in a tag; don't break it.
2462 # Skip ahead looking for something interesting
2463 $colon = strpos( $str, ':', $i );
2464 if ( $colon === false ) {
2465 # Nothing else interesting
2466 wfProfileOut( __METHOD__
);
2469 $lt = strpos( $str, '<', $i );
2470 if ( $stack === 0 ) {
2471 if ( $lt === false ||
$colon < $lt ) {
2473 $before = substr( $str, 0, $colon );
2474 $after = substr( $str, $colon +
1 );
2475 wfProfileOut( __METHOD__
);
2479 if ( $lt === false ) {
2480 # Nothing else interesting to find; abort!
2481 # We're nested, but there's no close tags left. Abort!
2484 # Skip ahead to next tag start
2486 $state = self
::COLON_STATE_TAGSTART
;
2489 case 1: # self::COLON_STATE_TAG:
2494 $state = self
::COLON_STATE_TEXT
;
2497 # Slash may be followed by >?
2498 $state = self
::COLON_STATE_TAGSLASH
;
2504 case 2: # self::COLON_STATE_TAGSTART:
2507 $state = self
::COLON_STATE_CLOSETAG
;
2510 $state = self
::COLON_STATE_COMMENT
;
2513 # Illegal early close? This shouldn't happen D:
2514 $state = self
::COLON_STATE_TEXT
;
2517 $state = self
::COLON_STATE_TAG
;
2520 case 3: # self::COLON_STATE_CLOSETAG:
2525 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2526 wfProfileOut( __METHOD__
);
2529 $state = self
::COLON_STATE_TEXT
;
2532 case self
::COLON_STATE_TAGSLASH
:
2534 # Yes, a self-closed tag <blah/>
2535 $state = self
::COLON_STATE_TEXT
;
2537 # Probably we're jumping the gun, and this is an attribute
2538 $state = self
::COLON_STATE_TAG
;
2541 case 5: # self::COLON_STATE_COMMENT:
2543 $state = self
::COLON_STATE_COMMENTDASH
;
2546 case self
::COLON_STATE_COMMENTDASH
:
2548 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2550 $state = self
::COLON_STATE_COMMENT
;
2553 case self
::COLON_STATE_COMMENTDASHDASH
:
2555 $state = self
::COLON_STATE_TEXT
;
2557 $state = self
::COLON_STATE_COMMENT
;
2561 throw new MWException( "State machine error in " . __METHOD__
);
2565 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2566 wfProfileOut( __METHOD__
);
2569 wfProfileOut( __METHOD__
);
2574 * Return value of a magic variable (like PAGENAME)
2578 * @param $index integer
2579 * @param $frame PPFrame
2583 function getVariableValue( $index, $frame = false ) {
2584 global $wgContLang, $wgSitename, $wgServer;
2585 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2587 if ( is_null( $this->mTitle
) ) {
2588 // If no title set, bad things are going to happen
2589 // later. Title should always be set since this
2590 // should only be called in the middle of a parse
2591 // operation (but the unit-tests do funky stuff)
2592 throw new MWException( __METHOD__
. ' Should only be '
2593 . ' called while parsing (no title set)' );
2597 * Some of these require message or data lookups and can be
2598 * expensive to check many times.
2600 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2601 if ( isset( $this->mVarCache
[$index] ) ) {
2602 return $this->mVarCache
[$index];
2606 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2607 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2610 global $wgLocaltimezone;
2611 if ( isset( $wgLocaltimezone ) ) {
2612 $oldtz = date_default_timezone_get();
2613 date_default_timezone_set( $wgLocaltimezone );
2616 $localTimestamp = date( 'YmdHis', $ts );
2617 $localMonth = date( 'm', $ts );
2618 $localMonth1 = date( 'n', $ts );
2619 $localMonthName = date( 'n', $ts );
2620 $localDay = date( 'j', $ts );
2621 $localDay2 = date( 'd', $ts );
2622 $localDayOfWeek = date( 'w', $ts );
2623 $localWeek = date( 'W', $ts );
2624 $localYear = date( 'Y', $ts );
2625 $localHour = date( 'H', $ts );
2626 if ( isset( $wgLocaltimezone ) ) {
2627 date_default_timezone_set( $oldtz );
2630 $pageLang = $this->getFunctionLang();
2633 case 'currentmonth':
2634 $value = $pageLang->formatNum( gmdate( 'm', $ts ) );
2636 case 'currentmonth1':
2637 $value = $pageLang->formatNum( gmdate( 'n', $ts ) );
2639 case 'currentmonthname':
2640 $value = $pageLang->getMonthName( gmdate( 'n', $ts ) );
2642 case 'currentmonthnamegen':
2643 $value = $pageLang->getMonthNameGen( gmdate( 'n', $ts ) );
2645 case 'currentmonthabbrev':
2646 $value = $pageLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2649 $value = $pageLang->formatNum( gmdate( 'j', $ts ) );
2652 $value = $pageLang->formatNum( gmdate( 'd', $ts ) );
2655 $value = $pageLang->formatNum( $localMonth );
2658 $value = $pageLang->formatNum( $localMonth1 );
2660 case 'localmonthname':
2661 $value = $pageLang->getMonthName( $localMonthName );
2663 case 'localmonthnamegen':
2664 $value = $pageLang->getMonthNameGen( $localMonthName );
2666 case 'localmonthabbrev':
2667 $value = $pageLang->getMonthAbbreviation( $localMonthName );
2670 $value = $pageLang->formatNum( $localDay );
2673 $value = $pageLang->formatNum( $localDay2 );
2676 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2679 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2681 case 'fullpagename':
2682 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2684 case 'fullpagenamee':
2685 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2688 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2690 case 'subpagenamee':
2691 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2693 case 'basepagename':
2694 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2696 case 'basepagenamee':
2697 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2699 case 'talkpagename':
2700 if ( $this->mTitle
->canTalk() ) {
2701 $talkPage = $this->mTitle
->getTalkPage();
2702 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2707 case 'talkpagenamee':
2708 if ( $this->mTitle
->canTalk() ) {
2709 $talkPage = $this->mTitle
->getTalkPage();
2710 $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() );
2715 case 'subjectpagename':
2716 $subjPage = $this->mTitle
->getSubjectPage();
2717 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2719 case 'subjectpagenamee':
2720 $subjPage = $this->mTitle
->getSubjectPage();
2721 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() );
2723 case 'pageid': // requested in bug 23427
2724 $pageid = $this->getTitle()->getArticleId();
2725 if( $pageid == 0 ) {
2726 # 0 means the page doesn't exist in the database,
2727 # which means the user is previewing a new page.
2728 # The vary-revision flag must be set, because the magic word
2729 # will have a different value once the page is saved.
2730 $this->mOutput
->setFlag( 'vary-revision' );
2731 wfDebug( __METHOD__
. ": {{PAGEID}} used in a new page, setting vary-revision...\n" );
2733 $value = $pageid ?
$pageid : null;
2736 # Let the edit saving system know we should parse the page
2737 # *after* a revision ID has been assigned.
2738 $this->mOutput
->setFlag( 'vary-revision' );
2739 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2740 $value = $this->mRevisionId
;
2743 # Let the edit saving system know we should parse the page
2744 # *after* a revision ID has been assigned. This is for null edits.
2745 $this->mOutput
->setFlag( 'vary-revision' );
2746 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2747 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2749 case 'revisionday2':
2750 # Let the edit saving system know we should parse the page
2751 # *after* a revision ID has been assigned. This is for null edits.
2752 $this->mOutput
->setFlag( 'vary-revision' );
2753 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2754 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2756 case 'revisionmonth':
2757 # Let the edit saving system know we should parse the page
2758 # *after* a revision ID has been assigned. This is for null edits.
2759 $this->mOutput
->setFlag( 'vary-revision' );
2760 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2761 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2763 case 'revisionmonth1':
2764 # Let the edit saving system know we should parse the page
2765 # *after* a revision ID has been assigned. This is for null edits.
2766 $this->mOutput
->setFlag( 'vary-revision' );
2767 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2768 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2770 case 'revisionyear':
2771 # Let the edit saving system know we should parse the page
2772 # *after* a revision ID has been assigned. This is for null edits.
2773 $this->mOutput
->setFlag( 'vary-revision' );
2774 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2775 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2777 case 'revisiontimestamp':
2778 # Let the edit saving system know we should parse the page
2779 # *after* a revision ID has been assigned. This is for null edits.
2780 $this->mOutput
->setFlag( 'vary-revision' );
2781 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2782 $value = $this->getRevisionTimestamp();
2784 case 'revisionuser':
2785 # Let the edit saving system know we should parse the page
2786 # *after* a revision ID has been assigned. This is for null edits.
2787 $this->mOutput
->setFlag( 'vary-revision' );
2788 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2789 $value = $this->getRevisionUser();
2792 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2795 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2797 case 'namespacenumber':
2798 $value = $this->mTitle
->getNamespace();
2801 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2804 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2806 case 'subjectspace':
2807 $value = $this->mTitle
->getSubjectNsText();
2809 case 'subjectspacee':
2810 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2812 case 'currentdayname':
2813 $value = $pageLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2816 $value = $pageLang->formatNum( gmdate( 'Y', $ts ), true );
2819 $value = $pageLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2822 $value = $pageLang->formatNum( gmdate( 'H', $ts ), true );
2825 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2826 # int to remove the padding
2827 $value = $pageLang->formatNum( (int)gmdate( 'W', $ts ) );
2830 $value = $pageLang->formatNum( gmdate( 'w', $ts ) );
2832 case 'localdayname':
2833 $value = $pageLang->getWeekdayName( $localDayOfWeek +
1 );
2836 $value = $pageLang->formatNum( $localYear, true );
2839 $value = $pageLang->time( $localTimestamp, false, false );
2842 $value = $pageLang->formatNum( $localHour, true );
2845 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2846 # int to remove the padding
2847 $value = $pageLang->formatNum( (int)$localWeek );
2850 $value = $pageLang->formatNum( $localDayOfWeek );
2852 case 'numberofarticles':
2853 $value = $pageLang->formatNum( SiteStats
::articles() );
2855 case 'numberoffiles':
2856 $value = $pageLang->formatNum( SiteStats
::images() );
2858 case 'numberofusers':
2859 $value = $pageLang->formatNum( SiteStats
::users() );
2861 case 'numberofactiveusers':
2862 $value = $pageLang->formatNum( SiteStats
::activeUsers() );
2864 case 'numberofpages':
2865 $value = $pageLang->formatNum( SiteStats
::pages() );
2867 case 'numberofadmins':
2868 $value = $pageLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2870 case 'numberofedits':
2871 $value = $pageLang->formatNum( SiteStats
::edits() );
2873 case 'numberofviews':
2874 global $wgDisableCounters;
2875 $value = !$wgDisableCounters ?
$pageLang->formatNum( SiteStats
::views() ) : '';
2877 case 'currenttimestamp':
2878 $value = wfTimestamp( TS_MW
, $ts );
2880 case 'localtimestamp':
2881 $value = $localTimestamp;
2883 case 'currentversion':
2884 $value = SpecialVersion
::getVersion();
2887 return $wgArticlePath;
2893 $serverParts = wfParseUrl( $wgServer );
2894 return $serverParts && isset( $serverParts['host'] ) ?
$serverParts['host'] : $wgServer;
2896 return $wgScriptPath;
2898 return $wgStylePath;
2899 case 'directionmark':
2900 return $pageLang->getDirMark();
2901 case 'contentlanguage':
2902 global $wgLanguageCode;
2903 return $wgLanguageCode;
2906 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2914 $this->mVarCache
[$index] = $value;
2921 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2925 function initialiseVariables() {
2926 wfProfileIn( __METHOD__
);
2927 $variableIDs = MagicWord
::getVariableIDs();
2928 $substIDs = MagicWord
::getSubstIDs();
2930 $this->mVariables
= new MagicWordArray( $variableIDs );
2931 $this->mSubstWords
= new MagicWordArray( $substIDs );
2932 wfProfileOut( __METHOD__
);
2936 * Preprocess some wikitext and return the document tree.
2937 * This is the ghost of replace_variables().
2939 * @param $text String: The text to parse
2940 * @param $flags Integer: bitwise combination of:
2941 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2942 * included. Default is to assume a direct page view.
2944 * The generated DOM tree must depend only on the input text and the flags.
2945 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2947 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2948 * change in the DOM tree for a given text, must be passed through the section identifier
2949 * in the section edit link and thus back to extractSections().
2951 * The output of this function is currently only cached in process memory, but a persistent
2952 * cache may be implemented at a later date which takes further advantage of these strict
2953 * dependency requirements.
2959 function preprocessToDom( $text, $flags = 0 ) {
2960 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2965 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2971 public static function splitWhitespace( $s ) {
2972 $ltrimmed = ltrim( $s );
2973 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2974 $trimmed = rtrim( $ltrimmed );
2975 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2977 $w2 = substr( $ltrimmed, -$diff );
2981 return array( $w1, $trimmed, $w2 );
2985 * Replace magic variables, templates, and template arguments
2986 * with the appropriate text. Templates are substituted recursively,
2987 * taking care to avoid infinite loops.
2989 * Note that the substitution depends on value of $mOutputType:
2990 * self::OT_WIKI: only {{subst:}} templates
2991 * self::OT_PREPROCESS: templates but not extension tags
2992 * self::OT_HTML: all templates and extension tags
2994 * @param $text String the text to transform
2995 * @param $frame PPFrame Object describing the arguments passed to the template.
2996 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2997 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2998 * @param $argsOnly Boolean only do argument (triple-brace) expansion, not double-brace expansion
3003 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
3004 # Is there any text? Also, Prevent too big inclusions!
3005 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
3008 wfProfileIn( __METHOD__
);
3010 if ( $frame === false ) {
3011 $frame = $this->getPreprocessor()->newFrame();
3012 } elseif ( !( $frame instanceof PPFrame
) ) {
3013 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
3014 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
3017 $dom = $this->preprocessToDom( $text );
3018 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
3019 $text = $frame->expand( $dom, $flags );
3021 wfProfileOut( __METHOD__
);
3026 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
3028 * @param $args array
3032 static function createAssocArgs( $args ) {
3033 $assocArgs = array();
3035 foreach ( $args as $arg ) {
3036 $eqpos = strpos( $arg, '=' );
3037 if ( $eqpos === false ) {
3038 $assocArgs[$index++
] = $arg;
3040 $name = trim( substr( $arg, 0, $eqpos ) );
3041 $value = trim( substr( $arg, $eqpos+
1 ) );
3042 if ( $value === false ) {
3045 if ( $name !== false ) {
3046 $assocArgs[$name] = $value;
3055 * Warn the user when a parser limitation is reached
3056 * Will warn at most once the user per limitation type
3058 * @param $limitationType String: should be one of:
3059 * 'expensive-parserfunction' (corresponding messages:
3060 * 'expensive-parserfunction-warning',
3061 * 'expensive-parserfunction-category')
3062 * 'post-expand-template-argument' (corresponding messages:
3063 * 'post-expand-template-argument-warning',
3064 * 'post-expand-template-argument-category')
3065 * 'post-expand-template-inclusion' (corresponding messages:
3066 * 'post-expand-template-inclusion-warning',
3067 * 'post-expand-template-inclusion-category')
3068 * @param $current int|null Current value
3069 * @param $max int|null Maximum allowed, when an explicit limit has been
3070 * exceeded, provide the values (optional)
3072 function limitationWarn( $limitationType, $current = null, $max = null) {
3073 # does no harm if $current and $max are present but are unnecessary for the message
3074 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
3075 $this->mOutput
->addWarning( $warning );
3076 $this->addTrackingCategory( "$limitationType-category" );
3080 * Return the text of a template, after recursively
3081 * replacing any variables or templates within the template.
3083 * @param $piece Array: the parts of the template
3084 * $piece['title']: the title, i.e. the part before the |
3085 * $piece['parts']: the parameter array
3086 * $piece['lineStart']: whether the brace was at the start of a line
3087 * @param $frame PPFrame The current frame, contains template arguments
3088 * @return String: the text of the template
3091 function braceSubstitution( $piece, $frame ) {
3093 wfProfileIn( __METHOD__
);
3094 wfProfileIn( __METHOD__
.'-setup' );
3097 $found = false; # $text has been filled
3098 $nowiki = false; # wiki markup in $text should be escaped
3099 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3100 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3101 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3102 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3104 # Title object, where $text came from
3107 # $part1 is the bit before the first |, and must contain only title characters.
3108 # Various prefixes will be stripped from it later.
3109 $titleWithSpaces = $frame->expand( $piece['title'] );
3110 $part1 = trim( $titleWithSpaces );
3113 # Original title text preserved for various purposes
3114 $originalTitle = $part1;
3116 # $args is a list of argument nodes, starting from index 0, not including $part1
3117 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3118 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3119 wfProfileOut( __METHOD__
.'-setup' );
3121 $titleProfileIn = null; // profile templates
3124 wfProfileIn( __METHOD__
.'-modifiers' );
3127 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3129 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3130 # Decide whether to expand template or keep wikitext as-is.
3131 if ( $this->ot
['wiki'] ) {
3132 if ( $substMatch === false ) {
3133 $literal = true; # literal when in PST with no prefix
3135 $literal = false; # expand when in PST with subst: or safesubst:
3138 if ( $substMatch == 'subst' ) {
3139 $literal = true; # literal when not in PST with plain subst:
3141 $literal = false; # expand when not in PST with safesubst: or no prefix
3145 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3152 if ( !$found && $args->getLength() == 0 ) {
3153 $id = $this->mVariables
->matchStartToEnd( $part1 );
3154 if ( $id !== false ) {
3155 $text = $this->getVariableValue( $id, $frame );
3156 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3157 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3163 # MSG, MSGNW and RAW
3166 $mwMsgnw = MagicWord
::get( 'msgnw' );
3167 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3170 # Remove obsolete MSG:
3171 $mwMsg = MagicWord
::get( 'msg' );
3172 $mwMsg->matchStartAndRemove( $part1 );
3176 $mwRaw = MagicWord
::get( 'raw' );
3177 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3178 $forceRawInterwiki = true;
3181 wfProfileOut( __METHOD__
.'-modifiers' );
3185 wfProfileIn( __METHOD__
. '-pfunc' );
3187 $colonPos = strpos( $part1, ':' );
3188 if ( $colonPos !== false ) {
3189 # Case sensitive functions
3190 $function = substr( $part1, 0, $colonPos );
3191 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3192 $function = $this->mFunctionSynonyms
[1][$function];
3194 # Case insensitive functions
3195 $function = $wgContLang->lc( $function );
3196 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3197 $function = $this->mFunctionSynonyms
[0][$function];
3203 wfProfileIn( __METHOD__
. '-pfunc-' . $function );
3204 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3205 $initialArgs = array( &$this );
3206 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3207 if ( $flags & SFH_OBJECT_ARGS
) {
3208 # Add a frame parameter, and pass the arguments as an array
3209 $allArgs = $initialArgs;
3210 $allArgs[] = $frame;
3211 for ( $i = 0; $i < $args->getLength(); $i++
) {
3212 $funcArgs[] = $args->item( $i );
3214 $allArgs[] = $funcArgs;
3216 # Convert arguments to plain text
3217 for ( $i = 0; $i < $args->getLength(); $i++
) {
3218 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3220 $allArgs = array_merge( $initialArgs, $funcArgs );
3223 # Workaround for PHP bug 35229 and similar
3224 if ( !is_callable( $callback ) ) {
3225 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3226 wfProfileOut( __METHOD__
. '-pfunc' );
3227 wfProfileOut( __METHOD__
);
3228 throw new MWException( "Tag hook for $function is not callable\n" );
3230 $result = call_user_func_array( $callback, $allArgs );
3233 $preprocessFlags = 0;
3235 if ( is_array( $result ) ) {
3236 if ( isset( $result[0] ) ) {
3238 unset( $result[0] );
3241 # Extract flags into the local scope
3242 # This allows callers to set flags such as nowiki, found, etc.
3248 $text = $this->preprocessToDom( $text, $preprocessFlags );
3251 wfProfileOut( __METHOD__
. '-pfunc-' . $function );
3254 wfProfileOut( __METHOD__
. '-pfunc' );
3257 # Finish mangling title and then check for loops.
3258 # Set $title to a Title object and $titleText to the PDBK
3261 # Split the title into page and subpage
3263 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3264 if ( $subpage !== '' ) {
3265 $ns = $this->mTitle
->getNamespace();
3267 $title = Title
::newFromText( $part1, $ns );
3269 $titleText = $title->getPrefixedText();
3270 # Check for language variants if the template is not found
3271 if ( $this->getConverterLanguage()->hasVariants() && $title->getArticleID() == 0 ) {
3272 $this->getConverterLanguage()->findVariantLink( $part1, $title, true );
3274 # Do recursion depth check
3275 $limit = $this->mOptions
->getMaxTemplateDepth();
3276 if ( $frame->depth
>= $limit ) {
3278 $text = '<span class="error">'
3279 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
3285 # Load from database
3286 if ( !$found && $title ) {
3287 if ( !Profiler
::instance()->isPersistent() ) {
3288 # Too many unique items can kill profiling DBs/collectors
3289 $titleProfileIn = __METHOD__
. "-title-" . $title->getDBKey();
3290 wfProfileIn( $titleProfileIn ); // template in
3292 wfProfileIn( __METHOD__
. '-loadtpl' );
3293 if ( !$title->isExternal() ) {
3294 if ( $title->isSpecialPage()
3295 && $this->mOptions
->getAllowSpecialInclusion()
3296 && $this->ot
['html'] )
3298 // Pass the template arguments as URL parameters.
3299 // "uselang" will have no effect since the Language object
3300 // is forced to the one defined in ParserOptions.
3301 $pageArgs = array();
3302 for ( $i = 0; $i < $args->getLength(); $i++
) {
3303 $bits = $args->item( $i )->splitArg();
3304 if ( strval( $bits['index'] ) === '' ) {
3305 $name = trim( $frame->expand( $bits['name'], PPFrame
::STRIP_COMMENTS
) );
3306 $value = trim( $frame->expand( $bits['value'] ) );
3307 $pageArgs[$name] = $value;
3311 // Create a new context to execute the special page
3312 $context = new RequestContext
;
3313 $context->setTitle( $title );
3314 $context->setRequest( new FauxRequest( $pageArgs ) );
3315 $context->setUser( $this->getUser() );
3316 $context->setLanguage( $this->mOptions
->getUserLangObj() );
3317 $ret = SpecialPageFactory
::capturePath( $title, $context );
3319 $text = $context->getOutput()->getHTML();
3320 $this->mOutput
->addOutputPageMetadata( $context->getOutput() );
3323 $this->disableCache();
3325 } elseif ( MWNamespace
::isNonincludable( $title->getNamespace() ) ) {
3326 $found = false; # access denied
3327 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3329 list( $text, $title ) = $this->getTemplateDom( $title );
3330 if ( $text !== false ) {
3336 # If the title is valid but undisplayable, make a link to it
3337 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3338 $text = "[[:$titleText]]";
3341 } elseif ( $title->isTrans() ) {
3342 # Interwiki transclusion
3343 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3344 $text = $this->interwikiTransclude( $title, 'render' );
3347 $text = $this->interwikiTransclude( $title, 'raw' );
3348 # Preprocess it like a template
3349 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3355 # Do infinite loop check
3356 # This has to be done after redirect resolution to avoid infinite loops via redirects
3357 if ( !$frame->loopCheck( $title ) ) {
3359 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3360 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3362 wfProfileOut( __METHOD__
. '-loadtpl' );
3365 # If we haven't found text to substitute by now, we're done
3366 # Recover the source wikitext and return it
3368 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3369 if ( $titleProfileIn ) {
3370 wfProfileOut( $titleProfileIn ); // template out
3372 wfProfileOut( __METHOD__
);
3373 return array( 'object' => $text );
3376 # Expand DOM-style return values in a child frame
3377 if ( $isChildObj ) {
3378 # Clean up argument array
3379 $newFrame = $frame->newChild( $args, $title );
3382 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3383 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3384 # Expansion is eligible for the empty-frame cache
3385 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3386 $text = $this->mTplExpandCache
[$titleText];
3388 $text = $newFrame->expand( $text );
3389 $this->mTplExpandCache
[$titleText] = $text;
3392 # Uncached expansion
3393 $text = $newFrame->expand( $text );
3396 if ( $isLocalObj && $nowiki ) {
3397 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3398 $isLocalObj = false;
3401 if ( $titleProfileIn ) {
3402 wfProfileOut( $titleProfileIn ); // template out
3405 # Replace raw HTML by a placeholder
3407 $text = $this->insertStripItem( $text );
3408 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3409 # Escape nowiki-style return values
3410 $text = wfEscapeWikiText( $text );
3411 } elseif ( is_string( $text )
3412 && !$piece['lineStart']
3413 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3415 # Bug 529: if the template begins with a table or block-level
3416 # element, it should be treated as beginning a new line.
3417 # This behaviour is somewhat controversial.
3418 $text = "\n" . $text;
3421 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3422 # Error, oversize inclusion
3423 if ( $titleText !== false ) {
3424 # Make a working, properly escaped link if possible (bug 23588)
3425 $text = "[[:$titleText]]";
3427 # This will probably not be a working link, but at least it may
3428 # provide some hint of where the problem is
3429 preg_replace( '/^:/', '', $originalTitle );
3430 $text = "[[:$originalTitle]]";
3432 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3433 $this->limitationWarn( 'post-expand-template-inclusion' );
3436 if ( $isLocalObj ) {
3437 $ret = array( 'object' => $text );
3439 $ret = array( 'text' => $text );
3442 wfProfileOut( __METHOD__
);
3447 * Get the semi-parsed DOM representation of a template with a given title,
3448 * and its redirect destination title. Cached.
3450 * @param $title Title
3454 function getTemplateDom( $title ) {
3455 $cacheTitle = $title;
3456 $titleText = $title->getPrefixedDBkey();
3458 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3459 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3460 $title = Title
::makeTitle( $ns, $dbk );
3461 $titleText = $title->getPrefixedDBkey();
3463 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3464 return array( $this->mTplDomCache
[$titleText], $title );
3467 # Cache miss, go to the database
3468 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3470 if ( $text === false ) {
3471 $this->mTplDomCache
[$titleText] = false;
3472 return array( false, $title );
3475 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3476 $this->mTplDomCache
[ $titleText ] = $dom;
3478 if ( !$title->equals( $cacheTitle ) ) {
3479 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3480 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3483 return array( $dom, $title );
3487 * Fetch the unparsed text of a template and register a reference to it.
3488 * @param Title $title
3489 * @return Array ( string or false, Title )
3491 function fetchTemplateAndTitle( $title ) {
3492 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3493 $stuff = call_user_func( $templateCb, $title, $this );
3494 $text = $stuff['text'];
3495 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3496 if ( isset( $stuff['deps'] ) ) {
3497 foreach ( $stuff['deps'] as $dep ) {
3498 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3501 return array( $text, $finalTitle );
3505 * Fetch the unparsed text of a template and register a reference to it.
3506 * @param Title $title
3507 * @return mixed string or false
3509 function fetchTemplate( $title ) {
3510 $rv = $this->fetchTemplateAndTitle( $title );
3515 * Static function to get a template
3516 * Can be overridden via ParserOptions::setTemplateCallback().
3518 * @parma $title Title
3519 * @param $parser Parser
3523 static function statelessFetchTemplate( $title, $parser = false ) {
3524 $text = $skip = false;
3525 $finalTitle = $title;
3528 # Loop to fetch the article, with up to 1 redirect
3529 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3530 # Give extensions a chance to select the revision instead
3531 $id = false; # Assume current
3532 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3533 array( $parser, $title, &$skip, &$id ) );
3539 'page_id' => $title->getArticleID(),
3546 ? Revision
::newFromId( $id )
3547 : Revision
::newFromTitle( $title );
3548 $rev_id = $rev ?
$rev->getId() : 0;
3549 # If there is no current revision, there is no page
3550 if ( $id === false && !$rev ) {
3551 $linkCache = LinkCache
::singleton();
3552 $linkCache->addBadLinkObj( $title );
3557 'page_id' => $title->getArticleID(),
3558 'rev_id' => $rev_id );
3559 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3560 # We fetched a rev from a different title; register it too...
3562 'title' => $rev->getTitle(),
3563 'page_id' => $rev->getPage(),
3564 'rev_id' => $rev_id );
3568 $text = $rev->getText();
3569 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3571 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3572 if ( !$message->exists() ) {
3576 $text = $message->plain();
3580 if ( $text === false ) {
3584 $finalTitle = $title;
3585 $title = Title
::newFromRedirect( $text );
3589 'finalTitle' => $finalTitle,
3594 * Fetch a file and its title and register a reference to it.
3595 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3596 * @param Title $title
3597 * @param Array $options Array of options to RepoGroup::findFile
3600 function fetchFile( $title, $options = array() ) {
3601 $res = $this->fetchFileAndTitle( $title, $options );
3606 * Fetch a file and its title and register a reference to it.
3607 * If 'broken' is a key in $options then the file will appear as a broken thumbnail.
3608 * @param Title $title
3609 * @param Array $options Array of options to RepoGroup::findFile
3610 * @return Array ( File or false, Title of file )
3612 function fetchFileAndTitle( $title, $options = array() ) {
3613 if ( isset( $options['broken'] ) ) {
3614 $file = false; // broken thumbnail forced by hook
3615 } elseif ( isset( $options['sha1'] ) ) { // get by (sha1,timestamp)
3616 $file = RepoGroup
::singleton()->findFileFromKey( $options['sha1'], $options );
3617 } else { // get by (name,timestamp)
3618 $file = wfFindFile( $title, $options );
3620 $time = $file ?
$file->getTimestamp() : false;
3621 $sha1 = $file ?
$file->getSha1() : false;
3622 # Register the file as a dependency...
3623 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3624 if ( $file && !$title->equals( $file->getTitle() ) ) {
3625 # Update fetched file title
3626 $title = $file->getTitle();
3627 if ( is_null( $file->getRedirectedTitle() ) ) {
3628 # This file was not a redirect, but the title does not match.
3629 # Register under the new name because otherwise the link will
3631 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3634 return array( $file, $title );
3638 * Transclude an interwiki link.
3640 * @param $title Title
3645 function interwikiTransclude( $title, $action ) {
3646 global $wgEnableScaryTranscluding;
3648 if ( !$wgEnableScaryTranscluding ) {
3649 return wfMsgForContent('scarytranscludedisabled');
3652 $url = $title->getFullUrl( "action=$action" );
3654 if ( strlen( $url ) > 255 ) {
3655 return wfMsgForContent( 'scarytranscludetoolong' );
3657 return $this->fetchScaryTemplateMaybeFromCache( $url );
3661 * @param $url string
3662 * @return Mixed|String
3664 function fetchScaryTemplateMaybeFromCache( $url ) {
3665 global $wgTranscludeCacheExpiry;
3666 $dbr = wfGetDB( DB_SLAVE
);
3667 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3668 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3669 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3671 return $obj->tc_contents
;
3674 $text = Http
::get( $url );
3676 return wfMsgForContent( 'scarytranscludefailed', $url );
3679 $dbw = wfGetDB( DB_MASTER
);
3680 $dbw->replace( 'transcache', array('tc_url'), array(
3682 'tc_time' => $dbw->timestamp( time() ),
3683 'tc_contents' => $text)
3689 * Triple brace replacement -- used for template arguments
3692 * @param $peice array
3693 * @param $frame PPFrame
3697 function argSubstitution( $piece, $frame ) {
3698 wfProfileIn( __METHOD__
);
3701 $parts = $piece['parts'];
3702 $nameWithSpaces = $frame->expand( $piece['title'] );
3703 $argName = trim( $nameWithSpaces );
3705 $text = $frame->getArgument( $argName );
3706 if ( $text === false && $parts->getLength() > 0
3710 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3713 # No match in frame, use the supplied default
3714 $object = $parts->item( 0 )->getChildren();
3716 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3717 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3718 $this->limitationWarn( 'post-expand-template-argument' );
3721 if ( $text === false && $object === false ) {
3723 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3725 if ( $error !== false ) {
3728 if ( $object !== false ) {
3729 $ret = array( 'object' => $object );
3731 $ret = array( 'text' => $text );
3734 wfProfileOut( __METHOD__
);
3739 * Return the text to be used for a given extension tag.
3740 * This is the ghost of strip().
3742 * @param $params array Associative array of parameters:
3743 * name PPNode for the tag name
3744 * attr PPNode for unparsed text where tag attributes are thought to be
3745 * attributes Optional associative array of parsed attributes
3746 * inner Contents of extension element
3747 * noClose Original text did not have a close tag
3748 * @param $frame PPFrame
3752 function extensionSubstitution( $params, $frame ) {
3753 $name = $frame->expand( $params['name'] );
3754 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3755 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3756 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3758 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3759 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3760 if ( $isFunctionTag ) {
3761 $markerType = 'none';
3763 $markerType = 'general';
3765 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3766 $name = strtolower( $name );
3767 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3768 if ( isset( $params['attributes'] ) ) {
3769 $attributes = $attributes +
$params['attributes'];
3772 if ( isset( $this->mTagHooks
[$name] ) ) {
3773 # Workaround for PHP bug 35229 and similar
3774 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3775 throw new MWException( "Tag hook for $name is not callable\n" );
3777 $output = call_user_func_array( $this->mTagHooks
[$name],
3778 array( $content, $attributes, $this, $frame ) );
3779 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3780 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3781 if ( !is_callable( $callback ) ) {
3782 throw new MWException( "Tag hook for $name is not callable\n" );
3785 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3787 $output = '<span class="error">Invalid tag extension name: ' .
3788 htmlspecialchars( $name ) . '</span>';
3791 if ( is_array( $output ) ) {
3792 # Extract flags to local scope (to override $markerType)
3794 $output = $flags[0];
3799 if ( is_null( $attrText ) ) {
3802 if ( isset( $params['attributes'] ) ) {
3803 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3804 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3805 htmlspecialchars( $attrValue ) . '"';
3808 if ( $content === null ) {
3809 $output = "<$name$attrText/>";
3811 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3812 $output = "<$name$attrText>$content$close";
3816 if ( $markerType === 'none' ) {
3818 } elseif ( $markerType === 'nowiki' ) {
3819 $this->mStripState
->addNoWiki( $marker, $output );
3820 } elseif ( $markerType === 'general' ) {
3821 $this->mStripState
->addGeneral( $marker, $output );
3823 throw new MWException( __METHOD__
.': invalid marker type' );
3829 * Increment an include size counter
3831 * @param $type String: the type of expansion
3832 * @param $size Integer: the size of the text
3833 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3835 function incrementIncludeSize( $type, $size ) {
3836 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3839 $this->mIncludeSizes
[$type] +
= $size;
3845 * Increment the expensive function count
3847 * @return Boolean: false if the limit has been exceeded
3849 function incrementExpensiveFunctionCount() {
3850 $this->mExpensiveFunctionCount++
;
3851 return $this->mExpensiveFunctionCount
<= $this->mOptions
->getExpensiveParserFunctionLimit();
3855 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3856 * Fills $this->mDoubleUnderscores, returns the modified text
3858 * @param $text string
3862 function doDoubleUnderscore( $text ) {
3863 wfProfileIn( __METHOD__
);
3865 # The position of __TOC__ needs to be recorded
3866 $mw = MagicWord
::get( 'toc' );
3867 if ( $mw->match( $text ) ) {
3868 $this->mShowToc
= true;
3869 $this->mForceTocPosition
= true;
3871 # Set a placeholder. At the end we'll fill it in with the TOC.
3872 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3874 # Only keep the first one.
3875 $text = $mw->replace( '', $text );
3878 # Now match and remove the rest of them
3879 $mwa = MagicWord
::getDoubleUnderscoreArray();
3880 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3882 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3883 $this->mOutput
->mNoGallery
= true;
3885 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3886 $this->mShowToc
= false;
3888 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3889 $this->addTrackingCategory( 'hidden-category-category' );
3891 # (bug 8068) Allow control over whether robots index a page.
3893 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
3894 # is not desirable, the last one on the page should win.
3895 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3896 $this->mOutput
->setIndexPolicy( 'noindex' );
3897 $this->addTrackingCategory( 'noindex-category' );
3899 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3900 $this->mOutput
->setIndexPolicy( 'index' );
3901 $this->addTrackingCategory( 'index-category' );
3904 # Cache all double underscores in the database
3905 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
3906 $this->mOutput
->setProperty( $key, '' );
3909 wfProfileOut( __METHOD__
);
3914 * Add a tracking category, getting the title from a system message,
3915 * or print a debug message if the title is invalid.
3917 * @param $msg String: message key
3918 * @return Boolean: whether the addition was successful
3920 public function addTrackingCategory( $msg ) {
3921 if ( $this->mTitle
->getNamespace() === NS_SPECIAL
) {
3922 wfDebug( __METHOD__
.": Not adding tracking category $msg to special page!\n" );
3925 // Important to parse with correct title (bug 31469)
3926 $cat = wfMessage( $msg )
3927 ->title( $this->getTitle() )
3928 ->inContentLanguage()
3931 # Allow tracking categories to be disabled by setting them to "-"
3932 if ( $cat === '-' ) {
3936 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3937 if ( $containerCategory ) {
3938 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3941 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3947 * This function accomplishes several tasks:
3948 * 1) Auto-number headings if that option is enabled
3949 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3950 * 3) Add a Table of contents on the top for users who have enabled the option
3951 * 4) Auto-anchor headings
3953 * It loops through all headlines, collects the necessary data, then splits up the
3954 * string and re-inserts the newly formatted headlines.
3956 * @param $text String
3957 * @param $origText String: original, untouched wikitext
3958 * @param $isMain Boolean
3959 * @return mixed|string
3962 function formatHeadings( $text, $origText, $isMain=true ) {
3963 global $wgMaxTocLevel, $wgHtml5, $wgExperimentalHtmlIds;
3965 # Inhibit editsection links if requested in the page
3966 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3967 $maybeShowEditLink = $showEditLink = false;
3969 $maybeShowEditLink = true; /* Actual presence will depend on ParserOptions option */
3970 $showEditLink = $this->mOptions
->getEditSection();
3972 if ( $showEditLink ) {
3973 $this->mOutput
->setEditSectionTokens( true );
3976 # Get all headlines for numbering them and adding funky stuff like [edit]
3977 # links - this is for later, but we need the number of headlines right now
3979 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3981 # if there are fewer than 4 headlines in the article, do not show TOC
3982 # unless it's been explicitly enabled.
3983 $enoughToc = $this->mShowToc
&&
3984 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
3986 # Allow user to stipulate that a page should have a "new section"
3987 # link added via __NEWSECTIONLINK__
3988 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3989 $this->mOutput
->setNewSection( true );
3992 # Allow user to remove the "new section"
3993 # link via __NONEWSECTIONLINK__
3994 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3995 $this->mOutput
->hideNewSection( true );
3998 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3999 # override above conditions and always show TOC above first header
4000 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
4001 $this->mShowToc
= true;
4009 # Ugh .. the TOC should have neat indentation levels which can be
4010 # passed to the skin functions. These are determined here
4014 $sublevelCount = array();
4015 $levelCount = array();
4020 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
4021 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
4022 $oldType = $this->mOutputType
;
4023 $this->setOutputType( self
::OT_WIKI
);
4024 $frame = $this->getPreprocessor()->newFrame();
4025 $root = $this->preprocessToDom( $origText );
4026 $node = $root->getFirstChild();
4031 foreach ( $matches[3] as $headline ) {
4032 $isTemplate = false;
4034 $sectionIndex = false;
4036 $markerMatches = array();
4037 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
4038 $serial = $markerMatches[1];
4039 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
4040 $isTemplate = ( $titleText != $baseTitleText );
4041 $headline = preg_replace( "/^$markerRegex/", "", $headline );
4045 $prevlevel = $level;
4047 $level = $matches[1][$headlineCount];
4049 if ( $level > $prevlevel ) {
4050 # Increase TOC level
4052 $sublevelCount[$toclevel] = 0;
4053 if ( $toclevel<$wgMaxTocLevel ) {
4054 $prevtoclevel = $toclevel;
4055 $toc .= Linker
::tocIndent();
4058 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
4059 # Decrease TOC level, find level to jump to
4061 for ( $i = $toclevel; $i > 0; $i-- ) {
4062 if ( $levelCount[$i] == $level ) {
4063 # Found last matching level
4066 } elseif ( $levelCount[$i] < $level ) {
4067 # Found first matching level below current level
4075 if ( $toclevel<$wgMaxTocLevel ) {
4076 if ( $prevtoclevel < $wgMaxTocLevel ) {
4077 # Unindent only if the previous toc level was shown :p
4078 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
4079 $prevtoclevel = $toclevel;
4081 $toc .= Linker
::tocLineEnd();
4085 # No change in level, end TOC line
4086 if ( $toclevel<$wgMaxTocLevel ) {
4087 $toc .= Linker
::tocLineEnd();
4091 $levelCount[$toclevel] = $level;
4093 # count number of headlines for each level
4094 @$sublevelCount[$toclevel]++
;
4096 for( $i = 1; $i <= $toclevel; $i++
) {
4097 if ( !empty( $sublevelCount[$i] ) ) {
4101 $numbering .= $this->getTargetLanguage()->formatNum( $sublevelCount[$i] );
4106 # The safe header is a version of the header text safe to use for links
4108 # Remove link placeholders by the link text.
4109 # <!--LINK number-->
4111 # link text with suffix
4112 # Do this before unstrip since link text can contain strip markers
4113 $safeHeadline = $this->replaceLinkHoldersText( $headline );
4115 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4116 $safeHeadline = $this->mStripState
->unstripBoth( $safeHeadline );
4118 # Strip out HTML (first regex removes any tag not allowed)
4119 # Allowed tags are <sup> and <sub> (bug 8393), <i> (bug 26375) and <b> (r105284)
4120 # We strip any parameter from accepted tags (second regex)
4121 $tocline = preg_replace(
4122 array( '#<(?!/?(sup|sub|i|b)(?: [^>]*)?>).*?'.'>#', '#<(/?(sup|sub|i|b))(?: .*?)?'.'>#' ),
4123 array( '', '<$1>' ),
4126 $tocline = trim( $tocline );
4128 # For the anchor, strip out HTML-y stuff period
4129 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
4130 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4132 # Save headline for section edit hint before it's escaped
4133 $headlineHint = $safeHeadline;
4135 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
4136 # For reverse compatibility, provide an id that's
4137 # HTML4-compatible, like we used to.
4139 # It may be worth noting, academically, that it's possible for
4140 # the legacy anchor to conflict with a non-legacy headline
4141 # anchor on the page. In this case likely the "correct" thing
4142 # would be to either drop the legacy anchors or make sure
4143 # they're numbered first. However, this would require people
4144 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4145 # manually, so let's not bother worrying about it.
4146 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4147 array( 'noninitial', 'legacy' ) );
4148 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4150 if ( $legacyHeadline == $safeHeadline ) {
4151 # No reason to have both (in fact, we can't)
4152 $legacyHeadline = false;
4155 $legacyHeadline = false;
4156 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4160 # HTML names must be case-insensitively unique (bug 10721).
4161 # This does not apply to Unicode characters per
4162 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4163 # @todo FIXME: We may be changing them depending on the current locale.
4164 $arrayKey = strtolower( $safeHeadline );
4165 if ( $legacyHeadline === false ) {
4166 $legacyArrayKey = false;
4168 $legacyArrayKey = strtolower( $legacyHeadline );
4171 # count how many in assoc. array so we can track dupes in anchors
4172 if ( isset( $refers[$arrayKey] ) ) {
4173 $refers[$arrayKey]++
;
4175 $refers[$arrayKey] = 1;
4177 if ( isset( $refers[$legacyArrayKey] ) ) {
4178 $refers[$legacyArrayKey]++
;
4180 $refers[$legacyArrayKey] = 1;
4183 # Don't number the heading if it is the only one (looks silly)
4184 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4185 # the two are different if the line contains a link
4186 $headline = Html
::element( 'span', array( 'class' => 'mw-headline-number' ), $numbering ) . ' ' . $headline;
4189 # Create the anchor for linking from the TOC to the section
4190 $anchor = $safeHeadline;
4191 $legacyAnchor = $legacyHeadline;
4192 if ( $refers[$arrayKey] > 1 ) {
4193 $anchor .= '_' . $refers[$arrayKey];
4195 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4196 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4198 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4199 $toc .= Linker
::tocLine( $anchor, $tocline,
4200 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4203 # Add the section to the section tree
4204 # Find the DOM node for this header
4205 while ( $node && !$isTemplate ) {
4206 if ( $node->getName() === 'h' ) {
4207 $bits = $node->splitHeading();
4208 if ( $bits['i'] == $sectionIndex ) {
4212 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4213 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4214 $node = $node->getNextSibling();
4217 'toclevel' => $toclevel,
4220 'number' => $numbering,
4221 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4222 'fromtitle' => $titleText,
4223 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
4224 'anchor' => $anchor,
4227 # give headline the correct <h#> tag
4228 if ( $maybeShowEditLink && $sectionIndex !== false ) {
4229 // Output edit section links as markers with styles that can be customized by skins
4230 if ( $isTemplate ) {
4231 # Put a T flag in the section identifier, to indicate to extractSections()
4232 # that sections inside <includeonly> should be counted.
4233 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4235 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
4237 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4238 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4239 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4240 // so we don't have to worry about a user trying to input one of these markers directly.
4241 // We use a page and section attribute to stop the language converter from converting these important bits
4242 // of data, but put the headline hint inside a content block because the language converter is supposed to
4243 // be able to convert that piece of data.
4244 $editlink = '<mw:editsection page="' . htmlspecialchars($editlinkArgs[0]);
4245 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"';
4246 if ( isset($editlinkArgs[2]) ) {
4247 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4254 $head[$headlineCount] = Linker
::makeHeadline( $level,
4255 $matches['attrib'][$headlineCount], $anchor, $headline,
4256 $editlink, $legacyAnchor );
4261 $this->setOutputType( $oldType );
4263 # Never ever show TOC if no headers
4264 if ( $numVisible < 1 ) {
4269 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4270 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4272 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLangObj() );
4273 $this->mOutput
->setTOCHTML( $toc );
4277 $this->mOutput
->setSections( $tocraw );
4280 # split up and insert constructed headlines
4281 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4284 // build an array of document sections
4285 $sections = array();
4286 foreach ( $blocks as $block ) {
4287 // $head is zero-based, sections aren't.
4288 if ( empty( $head[$i - 1] ) ) {
4289 $sections[$i] = $block;
4291 $sections[$i] = $head[$i - 1] . $block;
4295 * Send a hook, one per section.
4296 * The idea here is to be able to make section-level DIVs, but to do so in a
4297 * lower-impact, more correct way than r50769
4300 * $section : the section number
4301 * &$sectionContent : ref to the content of the section
4302 * $showEditLinks : boolean describing whether this section has an edit link
4304 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4309 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4310 // append the TOC at the beginning
4311 // Top anchor now in skin
4312 $sections[0] = $sections[0] . $toc . "\n";
4315 $full .= join( '', $sections );
4317 if ( $this->mForceTocPosition
) {
4318 return str_replace( '<!--MWTOC-->', $toc, $full );
4325 * Transform wiki markup when saving a page by doing \r\n -> \n
4326 * conversion, substitting signatures, {{subst:}} templates, etc.
4328 * @param $text String: the text to transform
4329 * @param $title Title: the Title object for the current article
4330 * @param $user User: the User object describing the current user
4331 * @param $options ParserOptions: parsing options
4332 * @param $clearState Boolean: whether to clear the parser state first
4333 * @return String: the altered wiki markup
4335 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4336 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4337 $this->setUser( $user );
4342 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4343 if( $options->getPreSaveTransform() ) {
4344 $text = $this->pstPass2( $text, $user );
4346 $text = $this->mStripState
->unstripBoth( $text );
4348 $this->setUser( null ); #Reset
4354 * Pre-save transform helper function
4357 * @param $text string
4362 function pstPass2( $text, $user ) {
4363 global $wgContLang, $wgLocaltimezone;
4365 # Note: This is the timestamp saved as hardcoded wikitext to
4366 # the database, we use $wgContLang here in order to give
4367 # everyone the same signature and use the default one rather
4368 # than the one selected in each user's preferences.
4369 # (see also bug 12815)
4370 $ts = $this->mOptions
->getTimestamp();
4371 if ( isset( $wgLocaltimezone ) ) {
4372 $tz = $wgLocaltimezone;
4374 $tz = date_default_timezone_get();
4377 $unixts = wfTimestamp( TS_UNIX
, $ts );
4378 $oldtz = date_default_timezone_get();
4379 date_default_timezone_set( $tz );
4380 $ts = date( 'YmdHis', $unixts );
4381 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4383 # Allow translation of timezones through wiki. date() can return
4384 # whatever crap the system uses, localised or not, so we cannot
4385 # ship premade translations.
4386 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4387 $msg = wfMessage( $key )->inContentLanguage();
4388 if ( $msg->exists() ) {
4389 $tzMsg = $msg->text();
4392 date_default_timezone_set( $oldtz );
4394 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4396 # Variable replacement
4397 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4398 $text = $this->replaceVariables( $text );
4400 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4401 # which may corrupt this parser instance via its wfMsgExt( parsemag ) call-
4404 $sigText = $this->getUserSig( $user );
4405 $text = strtr( $text, array(
4407 '~~~~' => "$sigText $d",
4411 # Context links: [[|name]] and [[name (context)|]]
4412 $tc = '[' . Title
::legalChars() . ']';
4413 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4415 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4416 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)( ?($tc+))\\|]]/"; # [[ns:page(context)|]]
4417 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( ?\\($tc+\\)|)((?:, |,)$tc+|)\\|]]/"; # [[ns:page (context), context|]]
4418 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4420 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4421 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4422 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4423 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4425 $t = $this->mTitle
->getText();
4427 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4428 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4429 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4430 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4432 # if there's no context, don't bother duplicating the title
4433 $text = preg_replace( $p2, '[[\\1]]', $text );
4436 # Trim trailing whitespace
4437 $text = rtrim( $text );
4443 * Fetch the user's signature text, if any, and normalize to
4444 * validated, ready-to-insert wikitext.
4445 * If you have pre-fetched the nickname or the fancySig option, you can
4446 * specify them here to save a database query.
4447 * Do not reuse this parser instance after calling getUserSig(),
4448 * as it may have changed if it's the $wgParser.
4451 * @param $nickname String|bool nickname to use or false to use user's default nickname
4452 * @param $fancySig Boolean|null whether the nicknname is the complete signature
4453 * or null to use default value
4456 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4457 global $wgMaxSigChars;
4459 $username = $user->getName();
4461 # If not given, retrieve from the user object.
4462 if ( $nickname === false )
4463 $nickname = $user->getOption( 'nickname' );
4465 if ( is_null( $fancySig ) ) {
4466 $fancySig = $user->getBoolOption( 'fancysig' );
4469 $nickname = $nickname == null ?
$username : $nickname;
4471 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4472 $nickname = $username;
4473 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4474 } elseif ( $fancySig !== false ) {
4475 # Sig. might contain markup; validate this
4476 if ( $this->validateSig( $nickname ) !== false ) {
4477 # Validated; clean up (if needed) and return it
4478 return $this->cleanSig( $nickname, true );
4480 # Failed to validate; fall back to the default
4481 $nickname = $username;
4482 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4486 # Make sure nickname doesnt get a sig in a sig
4487 $nickname = self
::cleanSigInSig( $nickname );
4489 # If we're still here, make it a link to the user page
4490 $userText = wfEscapeWikiText( $username );
4491 $nickText = wfEscapeWikiText( $nickname );
4492 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4494 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4498 * Check that the user's signature contains no bad XML
4500 * @param $text String
4501 * @return mixed An expanded string, or false if invalid.
4503 function validateSig( $text ) {
4504 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4508 * Clean up signature text
4510 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4511 * 2) Substitute all transclusions
4513 * @param $text String
4514 * @param $parsing bool Whether we're cleaning (preferences save) or parsing
4515 * @return String: signature text
4517 public function cleanSig( $text, $parsing = false ) {
4520 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PREPROCESS
, true );
4523 # Option to disable this feature
4524 if ( !$this->mOptions
->getCleanSignatures() ) {
4528 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4529 # => Move this logic to braceSubstitution()
4530 $substWord = MagicWord
::get( 'subst' );
4531 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4532 $substText = '{{' . $substWord->getSynonym( 0 );
4534 $text = preg_replace( $substRegex, $substText, $text );
4535 $text = self
::cleanSigInSig( $text );
4536 $dom = $this->preprocessToDom( $text );
4537 $frame = $this->getPreprocessor()->newFrame();
4538 $text = $frame->expand( $dom );
4541 $text = $this->mStripState
->unstripBoth( $text );
4548 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4550 * @param $text String
4551 * @return String: signature text with /~{3,5}/ removed
4553 public static function cleanSigInSig( $text ) {
4554 $text = preg_replace( '/~{3,5}/', '', $text );
4559 * Set up some variables which are usually set up in parse()
4560 * so that an external function can call some class members with confidence
4562 * @param $title Title|null
4563 * @param $options ParserOptions
4564 * @param $outputType
4565 * @param $clearState bool
4567 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4568 $this->startParse( $title, $options, $outputType, $clearState );
4572 * @param $title Title|null
4573 * @param $options ParserOptions
4574 * @param $outputType
4575 * @param $clearState bool
4577 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4578 $this->setTitle( $title );
4579 $this->mOptions
= $options;
4580 $this->setOutputType( $outputType );
4581 if ( $clearState ) {
4582 $this->clearState();
4587 * Wrapper for preprocess()
4589 * @param $text String: the text to preprocess
4590 * @param $options ParserOptions: options
4591 * @param $title Title object or null to use $wgTitle
4594 public function transformMsg( $text, $options, $title = null ) {
4595 static $executing = false;
4597 # Guard against infinite recursion
4603 wfProfileIn( __METHOD__
);
4609 # It's not uncommon having a null $wgTitle in scripts. See r80898
4610 # Create a ghost title in such case
4611 $title = Title
::newFromText( 'Dwimmerlaik' );
4613 $text = $this->preprocess( $text, $title, $options );
4616 wfProfileOut( __METHOD__
);
4621 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4622 * The callback should have the following form:
4623 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4625 * Transform and return $text. Use $parser for any required context, e.g. use
4626 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4628 * Hooks may return extended information by returning an array, of which the
4629 * first numbered element (index 0) must be the return string, and all other
4630 * entries are extracted into local variables within an internal function
4631 * in the Parser class.
4633 * This interface (introduced r61913) appears to be undocumented, but
4634 * 'markerName' is used by some core tag hooks to override which strip
4635 * array their results are placed in. **Use great caution if attempting
4636 * this interface, as it is not documented and injudicious use could smash
4637 * private variables.**
4639 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4640 * @param $callback Mixed: the callback function (and object) to use for the tag
4641 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4643 public function setHook( $tag, $callback ) {
4644 $tag = strtolower( $tag );
4645 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4646 throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4648 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4649 $this->mTagHooks
[$tag] = $callback;
4650 if ( !in_array( $tag, $this->mStripList
) ) {
4651 $this->mStripList
[] = $tag;
4658 * As setHook(), but letting the contents be parsed.
4660 * Transparent tag hooks are like regular XML-style tag hooks, except they
4661 * operate late in the transformation sequence, on HTML instead of wikitext.
4663 * This is probably obsoleted by things dealing with parser frames?
4664 * The only extension currently using it is geoserver.
4667 * @todo better document or deprecate this
4669 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4670 * @param $callback Mixed: the callback function (and object) to use for the tag
4671 * @return Mixed|null The old value of the mTagHooks array associated with the hook
4673 function setTransparentTagHook( $tag, $callback ) {
4674 $tag = strtolower( $tag );
4675 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) {
4676 throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4678 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4679 $this->mTransparentTagHooks
[$tag] = $callback;
4685 * Remove all tag hooks
4687 function clearTagHooks() {
4688 $this->mTagHooks
= array();
4689 $this->mFunctionTagHooks
= array();
4690 $this->mStripList
= $this->mDefaultStripList
;
4694 * Create a function, e.g. {{sum:1|2|3}}
4695 * The callback function should have the form:
4696 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4698 * Or with SFH_OBJECT_ARGS:
4699 * function myParserFunction( $parser, $frame, $args ) { ... }
4701 * The callback may either return the text result of the function, or an array with the text
4702 * in element 0, and a number of flags in the other elements. The names of the flags are
4703 * specified in the keys. Valid flags are:
4704 * found The text returned is valid, stop processing the template. This
4706 * nowiki Wiki markup in the return value should be escaped
4707 * isHTML The returned text is HTML, armour it against wikitext transformation
4709 * @param $id String: The magic word ID
4710 * @param $callback Mixed: the callback function (and object) to use
4711 * @param $flags Integer: a combination of the following flags:
4712 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4714 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4715 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4716 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4717 * the arguments, and to control the way they are expanded.
4719 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4720 * arguments, for instance:
4721 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4723 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4724 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4725 * working if/when this is changed.
4727 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4730 * Please read the documentation in includes/parser/Preprocessor.php for more information
4731 * about the methods available in PPFrame and PPNode.
4733 * @return string|callback The old callback function for this name, if any
4735 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4738 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4739 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4741 # Add to function cache
4742 $mw = MagicWord
::get( $id );
4744 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4746 $synonyms = $mw->getSynonyms();
4747 $sensitive = intval( $mw->isCaseSensitive() );
4749 foreach ( $synonyms as $syn ) {
4751 if ( !$sensitive ) {
4752 $syn = $wgContLang->lc( $syn );
4755 if ( !( $flags & SFH_NO_HASH
) ) {
4758 # Remove trailing colon
4759 if ( substr( $syn, -1, 1 ) === ':' ) {
4760 $syn = substr( $syn, 0, -1 );
4762 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4768 * Get all registered function hook identifiers
4772 function getFunctionHooks() {
4773 return array_keys( $this->mFunctionHooks
);
4777 * Create a tag function, e.g. <test>some stuff</test>.
4778 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4779 * Unlike parser functions, their content is not preprocessed.
4782 function setFunctionTagHook( $tag, $callback, $flags ) {
4783 $tag = strtolower( $tag );
4784 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4785 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4786 $this->mFunctionTagHooks
[$tag] : null;
4787 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4789 if ( !in_array( $tag, $this->mStripList
) ) {
4790 $this->mStripList
[] = $tag;
4797 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
4798 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4799 * Placeholders created in Skin::makeLinkObj()
4801 * @param $text string
4802 * @param $options int
4804 * @return array of link CSS classes, indexed by PDBK.
4806 function replaceLinkHolders( &$text, $options = 0 ) {
4807 return $this->mLinkHolders
->replace( $text );
4811 * Replace <!--LINK--> link placeholders with plain text of links
4812 * (not HTML-formatted).
4814 * @param $text String
4817 function replaceLinkHoldersText( $text ) {
4818 return $this->mLinkHolders
->replaceText( $text );
4822 * Renders an image gallery from a text with one line per image.
4823 * text labels may be given by using |-style alternative text. E.g.
4824 * Image:one.jpg|The number "1"
4825 * Image:tree.jpg|A tree
4826 * given as text will return the HTML of a gallery with two images,
4827 * labeled 'The number "1"' and
4830 * @param string $text
4831 * @param array $params
4832 * @return string HTML
4834 function renderImageGallery( $text, $params ) {
4835 $ig = new ImageGallery();
4836 $ig->setContextTitle( $this->mTitle
);
4837 $ig->setShowBytes( false );
4838 $ig->setShowFilename( false );
4839 $ig->setParser( $this );
4840 $ig->setHideBadImages();
4841 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4843 if ( isset( $params['showfilename'] ) ) {
4844 $ig->setShowFilename( true );
4846 $ig->setShowFilename( false );
4848 if ( isset( $params['caption'] ) ) {
4849 $caption = $params['caption'];
4850 $caption = htmlspecialchars( $caption );
4851 $caption = $this->replaceInternalLinks( $caption );
4852 $ig->setCaptionHtml( $caption );
4854 if ( isset( $params['perrow'] ) ) {
4855 $ig->setPerRow( $params['perrow'] );
4857 if ( isset( $params['widths'] ) ) {
4858 $ig->setWidths( $params['widths'] );
4860 if ( isset( $params['heights'] ) ) {
4861 $ig->setHeights( $params['heights'] );
4864 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4866 $lines = StringUtils
::explode( "\n", $text );
4867 foreach ( $lines as $line ) {
4868 # match lines like these:
4869 # Image:someimage.jpg|This is some image
4871 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4873 if ( count( $matches ) == 0 ) {
4877 if ( strpos( $matches[0], '%' ) !== false ) {
4878 $matches[1] = rawurldecode( $matches[1] );
4880 $title = Title
::newFromText( $matches[1], NS_FILE
);
4881 if ( is_null( $title ) ) {
4882 # Bogus title. Ignore these so we don't bomb out later.
4889 if ( isset( $matches[3] ) ) {
4890 // look for an |alt= definition while trying not to break existing
4891 // captions with multiple pipes (|) in it, until a more sensible grammar
4892 // is defined for images in galleries
4894 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
4895 $parameterMatches = StringUtils
::explode('|', $matches[3]);
4896 $magicWordAlt = MagicWord
::get( 'img_alt' );
4897 $magicWordLink = MagicWord
::get( 'img_link' );
4899 foreach ( $parameterMatches as $parameterMatch ) {
4900 if ( $match = $magicWordAlt->matchVariableStartToEnd( $parameterMatch ) ) {
4901 $alt = $this->stripAltText( $match, false );
4903 elseif( $match = $magicWordLink->matchVariableStartToEnd( $parameterMatch ) ){
4904 $link = strip_tags($this->replaceLinkHoldersText($match));
4905 $chars = self
::EXT_LINK_URL_CLASS
;
4906 $prots = $this->mUrlProtocols
;
4907 //check to see if link matches an absolute url, if not then it must be a wiki link.
4908 if(!preg_match( "/^($prots)$chars+$/u", $link)){
4909 $localLinkTitle = Title
::newFromText($link);
4910 $link = $localLinkTitle->getLocalURL();
4914 // concatenate all other pipes
4915 $label .= '|' . $parameterMatch;
4918 // remove the first pipe
4919 $label = substr( $label, 1 );
4922 $ig->add( $title, $label, $alt ,$link);
4924 return $ig->toHTML();
4931 function getImageParams( $handler ) {
4933 $handlerClass = get_class( $handler );
4937 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4938 # Initialise static lists
4939 static $internalParamNames = array(
4940 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4941 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4942 'bottom', 'text-bottom' ),
4943 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4944 'upright', 'border', 'link', 'alt' ),
4946 static $internalParamMap;
4947 if ( !$internalParamMap ) {
4948 $internalParamMap = array();
4949 foreach ( $internalParamNames as $type => $names ) {
4950 foreach ( $names as $name ) {
4951 $magicName = str_replace( '-', '_', "img_$name" );
4952 $internalParamMap[$magicName] = array( $type, $name );
4957 # Add handler params
4958 $paramMap = $internalParamMap;
4960 $handlerParamMap = $handler->getParamMap();
4961 foreach ( $handlerParamMap as $magic => $paramName ) {
4962 $paramMap[$magic] = array( 'handler', $paramName );
4965 $this->mImageParams
[$handlerClass] = $paramMap;
4966 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4968 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4972 * Parse image options text and use it to make an image
4974 * @param $title Title
4975 * @param $options String
4976 * @param $holders LinkHolderArray|bool
4977 * @return string HTML
4979 function makeImage( $title, $options, $holders = false ) {
4980 # Check if the options text is of the form "options|alt text"
4982 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4983 # * left no resizing, just left align. label is used for alt= only
4984 # * right same, but right aligned
4985 # * none same, but not aligned
4986 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4987 # * center center the image
4988 # * frame Keep original image size, no magnify-button.
4989 # * framed Same as "frame"
4990 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4991 # * upright reduce width for upright images, rounded to full __0 px
4992 # * border draw a 1px border around the image
4993 # * alt Text for HTML alt attribute (defaults to empty)
4994 # * link Set the target of the image link. Can be external, interwiki, or local
4995 # vertical-align values (no % or length right now):
5005 $parts = StringUtils
::explode( "|", $options );
5007 # Give extensions a chance to select the file revision for us
5010 wfRunHooks( 'BeforeParserFetchFileAndTitle',
5011 array( $this, $title, &$options, &$descQuery ) );
5012 # Fetch and register the file (file title may be different via hooks)
5013 list( $file, $title ) = $this->fetchFileAndTitle( $title, $options );
5016 $handler = $file ?
$file->getHandler() : false;
5018 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
5021 $this->addTrackingCategory( 'broken-file-category' );
5024 # Process the input parameters
5026 $params = array( 'frame' => array(), 'handler' => array(),
5027 'horizAlign' => array(), 'vertAlign' => array() );
5028 foreach ( $parts as $part ) {
5029 $part = trim( $part );
5030 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
5032 if ( isset( $paramMap[$magicName] ) ) {
5033 list( $type, $paramName ) = $paramMap[$magicName];
5035 # Special case; width and height come in one variable together
5036 if ( $type === 'handler' && $paramName === 'width' ) {
5038 # (bug 13500) In both cases (width/height and width only),
5039 # permit trailing "px" for backward compatibility.
5040 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
5041 $width = intval( $m[1] );
5042 $height = intval( $m[2] );
5043 if ( $handler->validateParam( 'width', $width ) ) {
5044 $params[$type]['width'] = $width;
5047 if ( $handler->validateParam( 'height', $height ) ) {
5048 $params[$type]['height'] = $height;
5051 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
5052 $width = intval( $value );
5053 if ( $handler->validateParam( 'width', $width ) ) {
5054 $params[$type]['width'] = $width;
5057 } # else no validation -- bug 13436
5059 if ( $type === 'handler' ) {
5060 # Validate handler parameter
5061 $validated = $handler->validateParam( $paramName, $value );
5063 # Validate internal parameters
5064 switch( $paramName ) {
5067 # @todo FIXME: Possibly check validity here for
5068 # manualthumb? downstream behavior seems odd with
5069 # missing manual thumbs.
5071 $value = $this->stripAltText( $value, $holders );
5074 $chars = self
::EXT_LINK_URL_CLASS
;
5075 $prots = $this->mUrlProtocols
;
5076 if ( $value === '' ) {
5077 $paramName = 'no-link';
5080 } elseif ( preg_match( "/^$prots/", $value ) ) {
5081 if ( preg_match( "/^($prots)$chars+$/u", $value, $m ) ) {
5082 $paramName = 'link-url';
5083 $this->mOutput
->addExternalLink( $value );
5084 if ( $this->mOptions
->getExternalLinkTarget() ) {
5085 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
5090 $linkTitle = Title
::newFromText( $value );
5092 $paramName = 'link-title';
5093 $value = $linkTitle;
5094 $this->mOutput
->addLink( $linkTitle );
5100 # Most other things appear to be empty or numeric...
5101 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
5106 $params[$type][$paramName] = $value;
5110 if ( !$validated ) {
5115 # Process alignment parameters
5116 if ( $params['horizAlign'] ) {
5117 $params['frame']['align'] = key( $params['horizAlign'] );
5119 if ( $params['vertAlign'] ) {
5120 $params['frame']['valign'] = key( $params['vertAlign'] );
5123 $params['frame']['caption'] = $caption;
5125 # Will the image be presented in a frame, with the caption below?
5126 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5127 isset( $params['frame']['framed'] ) ||
5128 isset( $params['frame']['thumbnail'] ) ||
5129 isset( $params['frame']['manualthumb'] );
5131 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5132 # came to also set the caption, ordinary text after the image -- which
5133 # makes no sense, because that just repeats the text multiple times in
5134 # screen readers. It *also* came to set the title attribute.
5136 # Now that we have an alt attribute, we should not set the alt text to
5137 # equal the caption: that's worse than useless, it just repeats the
5138 # text. This is the framed/thumbnail case. If there's no caption, we
5139 # use the unnamed parameter for alt text as well, just for the time be-
5140 # ing, if the unnamed param is set and the alt param is not.
5142 # For the future, we need to figure out if we want to tweak this more,
5143 # e.g., introducing a title= parameter for the title; ignoring the un-
5144 # named parameter entirely for images without a caption; adding an ex-
5145 # plicit caption= parameter and preserving the old magic unnamed para-
5147 if ( $imageIsFramed ) { # Framed image
5148 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5149 # No caption or alt text, add the filename as the alt text so
5150 # that screen readers at least get some description of the image
5151 $params['frame']['alt'] = $title->getText();
5153 # Do not set $params['frame']['title'] because tooltips don't make sense
5155 } else { # Inline image
5156 if ( !isset( $params['frame']['alt'] ) ) {
5157 # No alt text, use the "caption" for the alt text
5158 if ( $caption !== '') {
5159 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5161 # No caption, fall back to using the filename for the
5163 $params['frame']['alt'] = $title->getText();
5166 # Use the "caption" for the tooltip text
5167 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5170 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params, $this ) );
5172 # Linker does the rest
5173 $time = isset( $options['time'] ) ?
$options['time'] : false;
5174 $ret = Linker
::makeImageLink2( $title, $file, $params['frame'], $params['handler'],
5175 $time, $descQuery, $this->mOptions
->getThumbSize() );
5177 # Give the handler a chance to modify the parser object
5179 $handler->parserTransformHook( $this, $file );
5187 * @param $holders LinkHolderArray
5188 * @return mixed|String
5190 protected function stripAltText( $caption, $holders ) {
5191 # Strip bad stuff out of the title (tooltip). We can't just use
5192 # replaceLinkHoldersText() here, because if this function is called
5193 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5195 $tooltip = $holders->replaceText( $caption );
5197 $tooltip = $this->replaceLinkHoldersText( $caption );
5200 # make sure there are no placeholders in thumbnail attributes
5201 # that are later expanded to html- so expand them now and
5203 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5204 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5210 * Set a flag in the output object indicating that the content is dynamic and
5211 * shouldn't be cached.
5213 function disableCache() {
5214 wfDebug( "Parser output marked as uncacheable.\n" );
5215 if ( !$this->mOutput
) {
5216 throw new MWException( __METHOD__
.
5217 " can only be called when actually parsing something" );
5219 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5220 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5224 * Callback from the Sanitizer for expanding items found in HTML attribute
5225 * values, so they can be safely tested and escaped.
5227 * @param $text String
5228 * @param $frame PPFrame
5231 function attributeStripCallback( &$text, $frame = false ) {
5232 $text = $this->replaceVariables( $text, $frame );
5233 $text = $this->mStripState
->unstripBoth( $text );
5242 function getTags() {
5243 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
), array_keys( $this->mFunctionTagHooks
) );
5247 * Replace transparent tags in $text with the values given by the callbacks.
5249 * Transparent tag hooks are like regular XML-style tag hooks, except they
5250 * operate late in the transformation sequence, on HTML instead of wikitext.
5252 * @param $text string
5256 function replaceTransparentTags( $text ) {
5258 $elements = array_keys( $this->mTransparentTagHooks
);
5259 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5260 $replacements = array();
5262 foreach ( $matches as $marker => $data ) {
5263 list( $element, $content, $params, $tag ) = $data;
5264 $tagName = strtolower( $element );
5265 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5266 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
5270 $replacements[$marker] = $output;
5272 return strtr( $text, $replacements );
5276 * Break wikitext input into sections, and either pull or replace
5277 * some particular section's text.
5279 * External callers should use the getSection and replaceSection methods.
5281 * @param $text String: Page wikitext
5282 * @param $section String: a section identifier string of the form:
5283 * <flag1> - <flag2> - ... - <section number>
5285 * Currently the only recognised flag is "T", which means the target section number
5286 * was derived during a template inclusion parse, in other words this is a template
5287 * section edit link. If no flags are given, it was an ordinary section edit link.
5288 * This flag is required to avoid a section numbering mismatch when a section is
5289 * enclosed by <includeonly> (bug 6563).
5291 * The section number 0 pulls the text before the first heading; other numbers will
5292 * pull the given section along with its lower-level subsections. If the section is
5293 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5295 * Section 0 is always considered to exist, even if it only contains the empty
5296 * string. If $text is the empty string and section 0 is replaced, $newText is
5299 * @param $mode String: one of "get" or "replace"
5300 * @param $newText String: replacement text for section data.
5301 * @return String: for "get", the extracted section text.
5302 * for "replace", the whole page with the section replaced.
5304 private function extractSections( $text, $section, $mode, $newText='' ) {
5305 global $wgTitle; # not generally used but removes an ugly failure mode
5306 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5308 $frame = $this->getPreprocessor()->newFrame();
5310 # Process section extraction flags
5312 $sectionParts = explode( '-', $section );
5313 $sectionIndex = array_pop( $sectionParts );
5314 foreach ( $sectionParts as $part ) {
5315 if ( $part === 'T' ) {
5316 $flags |
= self
::PTD_FOR_INCLUSION
;
5320 # Check for empty input
5321 if ( strval( $text ) === '' ) {
5322 # Only sections 0 and T-0 exist in an empty document
5323 if ( $sectionIndex == 0 ) {
5324 if ( $mode === 'get' ) {
5330 if ( $mode === 'get' ) {
5338 # Preprocess the text
5339 $root = $this->preprocessToDom( $text, $flags );
5341 # <h> nodes indicate section breaks
5342 # They can only occur at the top level, so we can find them by iterating the root's children
5343 $node = $root->getFirstChild();
5345 # Find the target section
5346 if ( $sectionIndex == 0 ) {
5347 # Section zero doesn't nest, level=big
5348 $targetLevel = 1000;
5351 if ( $node->getName() === 'h' ) {
5352 $bits = $node->splitHeading();
5353 if ( $bits['i'] == $sectionIndex ) {
5354 $targetLevel = $bits['level'];
5358 if ( $mode === 'replace' ) {
5359 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5361 $node = $node->getNextSibling();
5367 if ( $mode === 'get' ) {
5374 # Find the end of the section, including nested sections
5376 if ( $node->getName() === 'h' ) {
5377 $bits = $node->splitHeading();
5378 $curLevel = $bits['level'];
5379 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5383 if ( $mode === 'get' ) {
5384 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5386 $node = $node->getNextSibling();
5389 # Write out the remainder (in replace mode only)
5390 if ( $mode === 'replace' ) {
5391 # Output the replacement text
5392 # Add two newlines on -- trailing whitespace in $newText is conventionally
5393 # stripped by the editor, so we need both newlines to restore the paragraph gap
5394 # Only add trailing whitespace if there is newText
5395 if ( $newText != "" ) {
5396 $outText .= $newText . "\n\n";
5400 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5401 $node = $node->getNextSibling();
5405 if ( is_string( $outText ) ) {
5406 # Re-insert stripped tags
5407 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5414 * This function returns the text of a section, specified by a number ($section).
5415 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5416 * the first section before any such heading (section 0).
5418 * If a section contains subsections, these are also returned.
5420 * @param $text String: text to look in
5421 * @param $section String: section identifier
5422 * @param $deftext String: default to return if section is not found
5423 * @return string text of the requested section
5425 public function getSection( $text, $section, $deftext='' ) {
5426 return $this->extractSections( $text, $section, "get", $deftext );
5430 * This function returns $oldtext after the content of the section
5431 * specified by $section has been replaced with $text. If the target
5432 * section does not exist, $oldtext is returned unchanged.
5434 * @param $oldtext String: former text of the article
5435 * @param $section int section identifier
5436 * @param $text String: replacing text
5437 * @return String: modified text
5439 public function replaceSection( $oldtext, $section, $text ) {
5440 return $this->extractSections( $oldtext, $section, "replace", $text );
5444 * Get the ID of the revision we are parsing
5446 * @return Mixed: integer or null
5448 function getRevisionId() {
5449 return $this->mRevisionId
;
5453 * Get the revision object for $this->mRevisionId
5455 * @return Revision|null either a Revision object or null
5457 protected function getRevisionObject() {
5458 if ( !is_null( $this->mRevisionObject
) ) {
5459 return $this->mRevisionObject
;
5461 if ( is_null( $this->mRevisionId
) ) {
5465 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5466 return $this->mRevisionObject
;
5470 * Get the timestamp associated with the current revision, adjusted for
5471 * the default server-local timestamp
5473 function getRevisionTimestamp() {
5474 if ( is_null( $this->mRevisionTimestamp
) ) {
5475 wfProfileIn( __METHOD__
);
5479 $revObject = $this->getRevisionObject();
5480 $timestamp = $revObject ?
$revObject->getTimestamp() : wfTimestampNow();
5482 # The cryptic '' timezone parameter tells to use the site-default
5483 # timezone offset instead of the user settings.
5485 # Since this value will be saved into the parser cache, served
5486 # to other users, and potentially even used inside links and such,
5487 # it needs to be consistent for all visitors.
5488 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5490 wfProfileOut( __METHOD__
);
5492 return $this->mRevisionTimestamp
;
5496 * Get the name of the user that edited the last revision
5498 * @return String: user name
5500 function getRevisionUser() {
5501 if( is_null( $this->mRevisionUser
) ) {
5502 $revObject = $this->getRevisionObject();
5504 # if this template is subst: the revision id will be blank,
5505 # so just use the current user's name
5507 $this->mRevisionUser
= $revObject->getUserText();
5508 } elseif( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5509 $this->mRevisionUser
= $this->getUser()->getName();
5512 return $this->mRevisionUser
;
5516 * Mutator for $mDefaultSort
5518 * @param $sort string New value
5520 public function setDefaultSort( $sort ) {
5521 $this->mDefaultSort
= $sort;
5522 $this->mOutput
->setProperty( 'defaultsort', $sort );
5526 * Accessor for $mDefaultSort
5527 * Will use the empty string if none is set.
5529 * This value is treated as a prefix, so the
5530 * empty string is equivalent to sorting by
5535 public function getDefaultSort() {
5536 if ( $this->mDefaultSort
!== false ) {
5537 return $this->mDefaultSort
;
5544 * Accessor for $mDefaultSort
5545 * Unlike getDefaultSort(), will return false if none is set
5547 * @return string or false
5549 public function getCustomDefaultSort() {
5550 return $this->mDefaultSort
;
5554 * Try to guess the section anchor name based on a wikitext fragment
5555 * presumably extracted from a heading, for example "Header" from
5558 * @param $text string
5562 public function guessSectionNameFromWikiText( $text ) {
5563 # Strip out wikitext links(they break the anchor)
5564 $text = $this->stripSectionName( $text );
5565 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5566 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5570 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5571 * instead. For use in redirects, since IE6 interprets Redirect: headers
5572 * as something other than UTF-8 (apparently?), resulting in breakage.
5574 * @param $text String: The section name
5575 * @return string An anchor
5577 public function guessLegacySectionNameFromWikiText( $text ) {
5578 # Strip out wikitext links(they break the anchor)
5579 $text = $this->stripSectionName( $text );
5580 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5581 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5585 * Strips a text string of wikitext for use in a section anchor
5587 * Accepts a text string and then removes all wikitext from the
5588 * string and leaves only the resultant text (i.e. the result of
5589 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5590 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5591 * to create valid section anchors by mimicing the output of the
5592 * parser when headings are parsed.
5594 * @param $text String: text string to be stripped of wikitext
5595 * for use in a Section anchor
5596 * @return string Filtered text string
5598 public function stripSectionName( $text ) {
5599 # Strip internal link markup
5600 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5601 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5603 # Strip external link markup
5604 # @todo FIXME: Not tolerant to blank link text
5605 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5606 # on how many empty links there are on the page - need to figure that out.
5607 $text = preg_replace( '/\[(?:' . $this->mUrlProtocols
. ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5609 # Parse wikitext quotes (italics & bold)
5610 $text = $this->doQuotes( $text );
5613 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5618 * strip/replaceVariables/unstrip for preprocessor regression testing
5620 * @param $text string
5621 * @param $title Title
5622 * @param $options ParserOptions
5623 * @param $outputType int
5627 function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5628 $this->startParse( $title, $options, $outputType, true );
5630 $text = $this->replaceVariables( $text );
5631 $text = $this->mStripState
->unstripBoth( $text );
5632 $text = Sanitizer
::removeHTMLtags( $text );
5637 * @param $text string
5638 * @param $title Title
5639 * @param $options ParserOptions
5642 function testPst( $text, Title
$title, ParserOptions
$options ) {
5643 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5648 * @param $title Title
5649 * @param $options ParserOptions
5652 function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5653 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5657 * Call a callback function on all regions of the given text that are not
5658 * inside strip markers, and replace those regions with the return value
5659 * of the callback. For example, with input:
5663 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5664 * two strings will be replaced with the value returned by the callback in
5672 function markerSkipCallback( $s, $callback ) {
5675 while ( $i < strlen( $s ) ) {
5676 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5677 if ( $markerStart === false ) {
5678 $out .= call_user_func( $callback, substr( $s, $i ) );
5681 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5682 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5683 if ( $markerEnd === false ) {
5684 $out .= substr( $s, $markerStart );
5687 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5688 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5697 * Remove any strip markers found in the given text.
5699 * @param $text Input string
5702 function killMarkers( $text ) {
5703 return $this->mStripState
->killMarkers( $text );
5707 * Save the parser state required to convert the given half-parsed text to
5708 * HTML. "Half-parsed" in this context means the output of
5709 * recursiveTagParse() or internalParse(). This output has strip markers
5710 * from replaceVariables (extensionSubstitution() etc.), and link
5711 * placeholders from replaceLinkHolders().
5713 * Returns an array which can be serialized and stored persistently. This
5714 * array can later be loaded into another parser instance with
5715 * unserializeHalfParsedText(). The text can then be safely incorporated into
5716 * the return value of a parser hook.
5718 * @param $text string
5722 function serializeHalfParsedText( $text ) {
5723 wfProfileIn( __METHOD__
);
5726 'version' => self
::HALF_PARSED_VERSION
,
5727 'stripState' => $this->mStripState
->getSubState( $text ),
5728 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
5730 wfProfileOut( __METHOD__
);
5735 * Load the parser state given in the $data array, which is assumed to
5736 * have been generated by serializeHalfParsedText(). The text contents is
5737 * extracted from the array, and its markers are transformed into markers
5738 * appropriate for the current Parser instance. This transformed text is
5739 * returned, and can be safely included in the return value of a parser
5742 * If the $data array has been stored persistently, the caller should first
5743 * check whether it is still valid, by calling isValidHalfParsedText().
5745 * @param $data array Serialized data
5748 function unserializeHalfParsedText( $data ) {
5749 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
5750 throw new MWException( __METHOD__
.': invalid version' );
5753 # First, extract the strip state.
5754 $texts = array( $data['text'] );
5755 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
5757 # Now renumber links
5758 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
5760 # Should be good to go.
5765 * Returns true if the given array, presumed to be generated by
5766 * serializeHalfParsedText(), is compatible with the current version of the
5769 * @param $data Array
5773 function isValidHalfParsedText( $data ) {
5774 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;