3 * @defgroup Parser Parser
7 * File for Parser and related classes
12 * PHP Parser - Processes wiki markup (which uses a more user-friendly
13 * syntax, such as "[[link]]" for making links), and provides a one-way
14 * transformation of that wiki markup it into XHTML output / markup
15 * (which in turn the browser understands, and can display).
18 * There are five main entry points into the Parser class:
20 * produces HTML output
22 * produces altered wiki markup.
24 * removes HTML comments and expands templates
25 * cleanSig() / cleanSigInSig()
26 * Cleans a signature before saving it to preferences
28 * Return the content of a section from an article for section editing
30 * Replaces a section by number inside an article
32 * Removes <noinclude> sections, and <includeonly> tags.
35 * objects: $wgLang, $wgContLang
37 * NOT $wgUser or $wgTitle. Keep them away!
40 * $wgUseDynamicDates*, $wgInterwikiMagic*,
41 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
42 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
45 * * only within ParserOptions
52 * Update this version number when the ParserOutput format
53 * changes in an incompatible way, so the parser cache
54 * can automatically discard old data.
56 const VERSION
= '1.6.5';
59 * Update this version number when the output of serialiseHalfParsedText()
60 * changes in an incompatible way
62 const HALF_PARSED_VERSION
= 2;
64 # Flags for Parser::setFunctionHook
65 # Also available as global constants from Defines.php
66 const SFH_NO_HASH
= 1;
67 const SFH_OBJECT_ARGS
= 2;
69 # Constants needed for external link processing
70 # Everything except bracket, space, or control characters
71 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F]';
72 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
73 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
75 # State constants for the definition list colon extraction
76 const COLON_STATE_TEXT
= 0;
77 const COLON_STATE_TAG
= 1;
78 const COLON_STATE_TAGSTART
= 2;
79 const COLON_STATE_CLOSETAG
= 3;
80 const COLON_STATE_TAGSLASH
= 4;
81 const COLON_STATE_COMMENT
= 5;
82 const COLON_STATE_COMMENTDASH
= 6;
83 const COLON_STATE_COMMENTDASHDASH
= 7;
85 # Flags for preprocessToDom
86 const PTD_FOR_INCLUSION
= 1;
88 # Allowed values for $this->mOutputType
89 # Parameter to startExternalParse().
90 const OT_HTML
= 1; # like parse()
91 const OT_WIKI
= 2; # like preSaveTransform()
92 const OT_PREPROCESS
= 3; # like preprocess()
94 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
96 # Marker Suffix needs to be accessible staticly.
97 const MARKER_SUFFIX
= "-QINU\x7f";
100 var $mTagHooks = array();
101 var $mTransparentTagHooks = array();
102 var $mFunctionHooks = array();
103 var $mFunctionSynonyms = array( 0 => array(), 1 => array() );
104 var $mFunctionTagHooks = array();
105 var $mStripList = array();
106 var $mDefaultStripList = array();
107 var $mVarCache = array();
108 var $mImageParams = array();
109 var $mImageParamsMagicArray = array();
110 var $mMarkerIndex = 0;
111 var $mFirstCall = true;
113 # Initialised by initialiseVariables()
116 * @var MagicWordArray
121 * @var MagicWordArray
124 var $mConf, $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols; # Initialised in constructor
126 # Cleared with clearState():
131 var $mAutonumber, $mDTopen;
138 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
140 * @var LinkHolderArray
145 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
146 var $mTplExpandCache; # empty-frame expansion cache
147 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
148 var $mExpensiveFunctionCount; # number of expensive parser function calls
153 var $mUser; # User object; only used when doing pre-save transform
156 # These are variables reset at least once per parse regardless of $clearState
166 var $mTitle; # Title context, used for self-link rendering and similar things
167 var $mOutputType; # Output type, one of the OT_xxx constants
168 var $ot; # Shortcut alias, see setOutputType()
169 var $mRevisionObject; # The revision object of the specified revision ID
170 var $mRevisionId; # ID to display in {{REVISIONID}} tags
171 var $mRevisionTimestamp; # The timestamp of the specified revision ID
172 var $mRevisionUser; # User to display in {{REVISIONUSER}} tag
173 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp
183 public function __construct( $conf = array() ) {
184 $this->mConf
= $conf;
185 $this->mUrlProtocols
= wfUrlProtocols();
186 $this->mExtLinkBracketedRegex
= '/\[((' . wfUrlProtocols() . ')'.
187 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/S';
188 if ( isset( $conf['preprocessorClass'] ) ) {
189 $this->mPreprocessorClass
= $conf['preprocessorClass'];
190 } elseif ( defined( 'MW_COMPILED' ) ) {
191 # Preprocessor_Hash is much faster than Preprocessor_DOM in compiled mode
192 $this->mPreprocessorClass
= 'Preprocessor_Hash';
193 } elseif ( extension_loaded( 'domxml' ) ) {
194 # PECL extension that conflicts with the core DOM extension (bug 13770)
195 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
196 $this->mPreprocessorClass
= 'Preprocessor_Hash';
197 } elseif ( extension_loaded( 'dom' ) ) {
198 $this->mPreprocessorClass
= 'Preprocessor_DOM';
200 $this->mPreprocessorClass
= 'Preprocessor_Hash';
202 wfDebug( __CLASS__
. ": using preprocessor: {$this->mPreprocessorClass}\n" );
206 * Reduce memory usage to reduce the impact of circular references
208 function __destruct() {
209 if ( isset( $this->mLinkHolders
) ) {
210 unset( $this->mLinkHolders
);
212 foreach ( $this as $name => $value ) {
213 unset( $this->$name );
218 * Do various kinds of initialisation on the first call of the parser
220 function firstCallInit() {
221 if ( !$this->mFirstCall
) {
224 $this->mFirstCall
= false;
226 wfProfileIn( __METHOD__
);
228 CoreParserFunctions
::register( $this );
229 CoreTagHooks
::register( $this );
230 $this->initialiseVariables();
232 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
233 wfProfileOut( __METHOD__
);
241 function clearState() {
242 wfProfileIn( __METHOD__
);
243 if ( $this->mFirstCall
) {
244 $this->firstCallInit();
246 $this->mOutput
= new ParserOutput
;
247 $this->mOptions
->registerWatcher( array( $this->mOutput
, 'recordOption' ) );
248 $this->mAutonumber
= 0;
249 $this->mLastSection
= '';
250 $this->mDTopen
= false;
251 $this->mIncludeCount
= array();
252 $this->mArgStack
= false;
253 $this->mInPre
= false;
254 $this->mLinkHolders
= new LinkHolderArray( $this );
256 $this->mRevisionObject
= $this->mRevisionTimestamp
=
257 $this->mRevisionId
= $this->mRevisionUser
= null;
258 $this->mVarCache
= array();
262 * Prefix for temporary replacement strings for the multipass parser.
263 * \x07 should never appear in input as it's disallowed in XML.
264 * Using it at the front also gives us a little extra robustness
265 * since it shouldn't match when butted up against identifier-like
268 * Must not consist of all title characters, or else it will change
269 * the behaviour of <nowiki> in a link.
271 # $this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
272 # Changed to \x7f to allow XML double-parsing -- TS
273 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
274 $this->mStripState
= new StripState( $this->mUniqPrefix
);
277 # Clear these on every parse, bug 4549
278 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
280 $this->mShowToc
= true;
281 $this->mForceTocPosition
= false;
282 $this->mIncludeSizes
= array(
286 $this->mPPNodeCount
= 0;
287 $this->mDefaultSort
= false;
288 $this->mHeadings
= array();
289 $this->mDoubleUnderscores
= array();
290 $this->mExpensiveFunctionCount
= 0;
293 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
294 $this->mPreprocessor
= null;
297 wfRunHooks( 'ParserClearState', array( &$this ) );
298 wfProfileOut( __METHOD__
);
302 * Convert wikitext to HTML
303 * Do not call this function recursively.
305 * @param $text String: text we want to parse
306 * @param $title Title object
307 * @param $options ParserOptions
308 * @param $linestart boolean
309 * @param $clearState boolean
310 * @param $revid Int: number to pass in {{REVISIONID}}
311 * @return ParserOutput a ParserOutput
313 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
315 * First pass--just handle <nowiki> sections, pass the rest off
316 * to internalParse() which does all the real work.
319 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang, $wgDisableLangConversion, $wgDisableTitleConversion;
320 $fname = __METHOD__
.'-' . wfGetCaller();
321 wfProfileIn( __METHOD__
);
322 wfProfileIn( $fname );
324 $this->startParse( $title, $options, self
::OT_HTML
, $clearState );
326 $oldRevisionId = $this->mRevisionId
;
327 $oldRevisionObject = $this->mRevisionObject
;
328 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
329 $oldRevisionUser = $this->mRevisionUser
;
330 if ( $revid !== null ) {
331 $this->mRevisionId
= $revid;
332 $this->mRevisionObject
= null;
333 $this->mRevisionTimestamp
= null;
334 $this->mRevisionUser
= null;
337 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
339 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
340 $text = $this->internalParse( $text );
342 $text = $this->mStripState
->unstripGeneral( $text );
344 # Clean up special characters, only run once, next-to-last before doBlockLevels
346 # french spaces, last one Guillemet-left
347 # only if there is something before the space
348 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
349 # french spaces, Guillemet-right
350 '/(\\302\\253) /' => '\\1 ',
351 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
353 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
355 $text = $this->doBlockLevels( $text, $linestart );
357 $this->replaceLinkHolders( $text );
360 * The page doesn't get language converted if
362 * b) Content isn't converted
363 * c) It's a conversion table
365 if ( !( $wgDisableLangConversion
366 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
367 ||
$this->mTitle
->isConversionTable() ) ) {
369 # The position of the convert() call should not be changed. it
370 # assumes that the links are all replaced and the only thing left
371 # is the <nowiki> mark.
373 $text = $wgContLang->convert( $text );
377 * A converted title will be provided in the output object if title and
378 * content conversion are enabled, the article text does not contain
379 * a conversion-suppressing double-underscore tag, and no
380 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
381 * automatic link conversion.
383 if ( !( $wgDisableLangConversion
384 ||
$wgDisableTitleConversion
385 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
386 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
387 ||
$this->mOutput
->getDisplayTitle() !== false ) )
389 $convruletitle = $wgContLang->getConvRuleTitle();
390 if ( $convruletitle ) {
391 $this->mOutput
->setTitleText( $convruletitle );
393 $titleText = $wgContLang->convertTitle( $title );
394 $this->mOutput
->setTitleText( $titleText );
398 $text = $this->mStripState
->unstripNoWiki( $text );
400 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
402 $text = $this->replaceTransparentTags( $text );
403 $text = $this->mStripState
->unstripGeneral( $text );
405 $text = Sanitizer
::normalizeCharReferences( $text );
407 if ( ( $wgUseTidy && $this->mOptions
->getTidy() ) ||
$wgAlwaysUseTidy ) {
408 $text = MWTidy
::tidy( $text );
410 # attempt to sanitize at least some nesting problems
411 # (bug #2702 and quite a few others)
413 # ''Something [http://www.cool.com cool''] -->
414 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
415 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
416 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
417 # fix up an anchor inside another anchor, only
418 # at least for a single single nested link (bug 3695)
419 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
420 '\\1\\2</a>\\3</a>\\1\\4</a>',
421 # fix div inside inline elements- doBlockLevels won't wrap a line which
422 # contains a div, so fix it up here; replace
423 # div with escaped text
424 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
425 '\\1\\3<div\\5>\\6</div>\\8\\9',
426 # remove empty italic or bold tag pairs, some
427 # introduced by rules above
428 '/<([bi])><\/\\1>/' => '',
431 $text = preg_replace(
432 array_keys( $tidyregs ),
433 array_values( $tidyregs ),
436 global $wgExpensiveParserFunctionLimit;
437 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
438 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
441 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
443 # Information on include size limits, for the benefit of users who try to skirt them
444 if ( $this->mOptions
->getEnableLimitReport() ) {
445 $max = $this->mOptions
->getMaxIncludeSize();
446 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
448 "NewPP limit report\n" .
449 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
450 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
451 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
453 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
454 $text .= "\n<!-- \n$limitReport-->\n";
456 $this->mOutput
->setText( $text );
458 $this->mRevisionId
= $oldRevisionId;
459 $this->mRevisionObject
= $oldRevisionObject;
460 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
461 $this->mRevisionUser
= $oldRevisionUser;
462 wfProfileOut( $fname );
463 wfProfileOut( __METHOD__
);
465 return $this->mOutput
;
469 * Recursive parser entry point that can be called from an extension tag
472 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
474 * @param $text String: text extension wants to have parsed
475 * @param $frame PPFrame: The frame to use for expanding any template variables
479 function recursiveTagParse( $text, $frame=false ) {
480 wfProfileIn( __METHOD__
);
481 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
482 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
483 $text = $this->internalParse( $text, false, $frame );
484 wfProfileOut( __METHOD__
);
489 * Expand templates and variables in the text, producing valid, static wikitext.
490 * Also removes comments.
492 function preprocess( $text, Title
$title, ParserOptions
$options, $revid = null ) {
493 wfProfileIn( __METHOD__
);
494 $this->startParse( $title, $options, self
::OT_PREPROCESS
, true );
495 if ( $revid !== null ) {
496 $this->mRevisionId
= $revid;
498 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
499 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
500 $text = $this->replaceVariables( $text );
501 $text = $this->mStripState
->unstripBoth( $text );
502 wfProfileOut( __METHOD__
);
507 * Process the wikitext for the ?preload= feature. (bug 5210)
509 * <noinclude>, <includeonly> etc. are parsed as for template transclusion,
510 * comments, templates, arguments, tags hooks and parser functions are untouched.
512 public function getPreloadText( $text, Title
$title, ParserOptions
$options ) {
513 # Parser (re)initialisation
514 $this->startParse( $title, $options, self
::OT_PLAIN
, true );
516 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
517 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
518 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
519 $text = $this->mStripState
->unstripBoth( $text );
524 * Get a random string
528 static public function getRandomString() {
529 return dechex( mt_rand( 0, 0x7fffffff ) ) . dechex( mt_rand( 0, 0x7fffffff ) );
533 * Set the current user.
534 * Should only be used when doing pre-save transform.
536 * @param $user Mixed: User object or null (to reset)
538 function setUser( $user ) {
539 $this->mUser
= $user;
543 * Accessor for mUniqPrefix.
547 public function uniqPrefix() {
548 if ( !isset( $this->mUniqPrefix
) ) {
549 # @todo FIXME: This is probably *horribly wrong*
550 # LanguageConverter seems to want $wgParser's uniqPrefix, however
551 # if this is called for a parser cache hit, the parser may not
552 # have ever been initialized in the first place.
553 # Not really sure what the heck is supposed to be going on here.
555 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
557 return $this->mUniqPrefix
;
561 * Set the context title
565 function setTitle( $t ) {
566 if ( !$t ||
$t instanceof FakeTitle
) {
567 $t = Title
::newFromText( 'NO TITLE' );
570 if ( strval( $t->getFragment() ) !== '' ) {
571 # Strip the fragment to avoid various odd effects
572 $this->mTitle
= clone $t;
573 $this->mTitle
->setFragment( '' );
580 * Accessor for the Title object
582 * @return Title object
584 function getTitle() {
585 return $this->mTitle
;
589 * Accessor/mutator for the Title object
591 * @param $x New Title object or null to just get the current one
592 * @return Title object
594 function Title( $x = null ) {
595 return wfSetVar( $this->mTitle
, $x );
599 * Set the output type
601 * @param $ot Integer: new value
603 function setOutputType( $ot ) {
604 $this->mOutputType
= $ot;
607 'html' => $ot == self
::OT_HTML
,
608 'wiki' => $ot == self
::OT_WIKI
,
609 'pre' => $ot == self
::OT_PREPROCESS
,
610 'plain' => $ot == self
::OT_PLAIN
,
615 * Accessor/mutator for the output type
617 * @param $x New value or null to just get the current one
620 function OutputType( $x = null ) {
621 return wfSetVar( $this->mOutputType
, $x );
625 * Get the ParserOutput object
627 * @return ParserOutput object
629 function getOutput() {
630 return $this->mOutput
;
634 * Get the ParserOptions object
636 * @return ParserOptions object
638 function getOptions() {
639 return $this->mOptions
;
643 * Accessor/mutator for the ParserOptions object
645 * @param $x New value or null to just get the current one
646 * @return Current ParserOptions object
648 function Options( $x = null ) {
649 return wfSetVar( $this->mOptions
, $x );
655 function nextLinkID() {
656 return $this->mLinkID++
;
662 function setLinkID( $id ) {
663 $this->mLinkID
= $id;
669 function getFunctionLang() {
672 $target = $this->mOptions
->getTargetLanguage();
673 if ( $target !== null ) {
676 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $this->mTitle
->getPageLanguage();
681 * Get a User object either from $this->mUser, if set, or from the
682 * ParserOptions object otherwise
684 * @return User object
687 if ( !is_null( $this->mUser
) ) {
690 return $this->mOptions
->getUser();
694 * Get a preprocessor object
696 * @return Preprocessor instance
698 function getPreprocessor() {
699 if ( !isset( $this->mPreprocessor
) ) {
700 $class = $this->mPreprocessorClass
;
701 $this->mPreprocessor
= new $class( $this );
703 return $this->mPreprocessor
;
707 * Replaces all occurrences of HTML-style comments and the given tags
708 * in the text with a random marker and returns the next text. The output
709 * parameter $matches will be an associative array filled with data in
711 * 'UNIQ-xxxxx' => array(
714 * array( 'param' => 'x' ),
715 * '<element param="x">tag content</element>' ) )
717 * @param $elements array list of element names. Comments are always extracted.
718 * @param $text string Source text string.
719 * @param $matches array Out parameter, Array: extracted tags
720 * @param $uniq_prefix string
721 * @return String: stripped text
723 public static function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
728 $taglist = implode( '|', $elements );
729 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
731 while ( $text != '' ) {
732 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
734 if ( count( $p ) < 5 ) {
737 if ( count( $p ) > 5 ) {
751 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
752 $stripped .= $marker;
754 if ( $close === '/>' ) {
755 # Empty element tag, <tag />
760 if ( $element === '!--' ) {
763 $end = "/(<\\/$element\\s*>)/i";
765 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
767 if ( count( $q ) < 3 ) {
768 # No end tag -- let it run out to the end of the text.
777 $matches[$marker] = array( $element,
779 Sanitizer
::decodeTagAttributes( $attributes ),
780 "<$element$attributes$close$content$tail" );
786 * Get a list of strippable XML-like elements
790 function getStripList() {
791 return $this->mStripList
;
795 * Add an item to the strip state
796 * Returns the unique tag which must be inserted into the stripped text
797 * The tag will be replaced with the original text in unstrip()
799 function insertStripItem( $text ) {
800 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
801 $this->mMarkerIndex++
;
802 $this->mStripState
->addGeneral( $rnd, $text );
807 * parse the wiki syntax used to render tables
811 function doTableStuff( $text ) {
812 wfProfileIn( __METHOD__
);
814 $lines = StringUtils
::explode( "\n", $text );
818 foreach ( $lines as $outLine ) {
819 $line = trim( $outLine );
821 # empty line, go to next line,
822 # but only append \n if outside of table
824 $output .= $outLine . "\n";
827 $firstChars = $line[0];
828 if ( strlen( $line ) > 1 ) {
829 $firstChars .= in_array( $line[1], array( '}', '+', '-' ) ) ?
$line[1] : '';
833 if ( preg_match( '/^(:*)\s*\{\|(.*)$/', $line , $matches ) ) {
835 $table =& $this->last( $tables );
836 $table[0] = array(); // first row
837 $currentRow =& $table[0];
838 $table['indent'] = strlen( $matches[1] );
840 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
841 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
843 if ( $attributes !== '' ) {
844 $table['attributes'] = $attributes;
846 } elseif ( !isset( $tables[0] ) ) {
847 // we're outside the table
849 $out .= $outLine . "\n";
850 } elseif ( $firstChars === '|}' ) {
851 // trim the |} code from the line
852 $line = substr ( $line , 2 );
854 // Shorthand for last row
855 $lastRow =& $this->last( $table );
857 // a thead at the end becomes a tfoot, unless there is only one row
858 // Do this before deleting empty last lines to allow headers at the bottom of tables
859 if ( isset( $lastRow['type'] ) && $lastRow['type'] == 'thead' && isset( $table[1] ) ) {
860 $lastRow['type'] = 'tfoot';
861 for ( $i = 0; isset( $lastRow[$i] ); $i++
) {
862 $lastRow[$i]['type'] = 'th';
866 // Delete empty last lines
867 if ( empty( $lastRow ) ) {
871 $curtable = array_pop( $tables );
873 #Add a line-ending before the table, but only if there isn't one already
874 if ( substr( $out, -1 ) !== "\n" ) {
877 $o .= $this->generateTableHTML( $curtable ) . $line . "\n";
879 if ( count( $tables ) > 0 ) {
880 $table =& $this->last( $tables );
881 $currentRow =& $this->last( $table );
882 $currentElement =& $this->last( $currentRow );
884 $output =& $currentElement['content'];
891 } elseif ( $firstChars === '|-' ) {
892 // start a new row element
893 // but only when we haven't started one already
894 if ( count( $currentRow ) != 0 ) {
896 $currentRow =& $this->last( $table );
898 // Get the attributes, there's nothing else useful in $line now
899 $line = substr ( $line , 2 );
900 $attributes = $this->mStripState
->unstripBoth( $line );
901 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
902 if ( $attributes !== '' ) {
903 $currentRow['attributes'] = $attributes;
906 } elseif ( $firstChars === '|+' ) {
907 // a table caption, but only proceed if there isn't one already
908 if ( !isset ( $table['caption'] ) ) {
909 $line = substr ( $line , 2 );
911 $c = $this->getCellAttr( $line , 'caption' );
912 $table['caption'] = array();
913 $table['caption']['content'] = $c[0];
914 if ( isset( $c[1] ) ) $table['caption']['attributes'] = $c[1];
916 $output =& $table['caption']['content'];
918 } elseif ( $firstChars === '|' ||
$firstChars === '!' ||
$firstChars === '!+' ) {
919 // Which kind of cells are we dealing with
921 $line = substr ( $line , 1 );
923 if ( $firstChars === '!' ||
$firstChars === '!+' ) {
924 $line = str_replace ( '!!' , '||' , $line );
928 // Split up multiple cells on the same line.
929 $cells = StringUtils
::explodeMarkup( '||' , $line );
930 $line = ''; // save memory
932 // decide whether thead to tbody
933 if ( !array_key_exists( 'type', $currentRow ) ) {
934 $currentRow['type'] = ( $firstChars === '!' ) ?
'thead' : 'tbody' ;
935 } elseif ( $firstChars === '|' ) {
936 $currentRow['type'] = 'tbody';
939 // Loop through each table cell
940 foreach ( $cells as $cell ) {
942 $currentRow[] = array();
943 $currentElement =& $this->last( $currentRow );
945 $currentElement['type'] = $currentTag;
947 $c = $this->getCellAttr( $cell , $currentTag );
948 $currentElement['content'] = $c[0];
949 if ( isset( $c[1] ) ) $currentElement['attributes'] = $c[1];
952 $output =& $currentElement['content'];
955 $output .= "\n$outLine";
959 # Remove trailing line-ending (b/c)
960 if ( substr( $out, -1 ) === "\n" ) {
961 $out = substr( $out, 0, -1 );
964 # Close any unclosed tables
965 if ( isset( $tables ) && count( $tables ) > 0 ) {
966 for ( $i = 0; $i < count( $tables ); $i++
) {
967 $curtable = array_pop( $tables );
968 $curtable = $this->generateTableHTML( $curtable );
969 #Add a line-ending before the table, but only if there isn't one already
970 if ( substr( $out, -1 ) !== "\n" && $curtable !== "" ) {
977 wfProfileOut( __METHOD__
);
983 * Helper function for doTableStuff() separating the contents of cells from
984 * attributes. Particularly useful as there's a possible bug and this action
992 function getCellAttr ( $cell, $tagName ) {
995 $cell = trim ( $cell );
997 // A cell could contain both parameters and data
998 $cellData = explode ( '|' , $cell , 2 );
1000 // Bug 553: Note that a '|' inside an invalid link should not
1001 // be mistaken as delimiting cell parameters
1002 if ( strpos( $cellData[0], '[[' ) !== false ) {
1003 $content = trim ( $cell );
1005 elseif ( count ( $cellData ) == 1 ) {
1006 $content = trim ( $cellData[0] );
1008 $attributes = $this->mStripState
->unstripBoth( $cellData[0] );
1009 $attributes = Sanitizer
::fixTagAttributes( $attributes , $tagName );
1011 $content = trim ( $cellData[1] );
1013 return array( $content, $attributes );
1018 * Helper function for doTableStuff(). This converts the structured array into html.
1022 function generateTableHTML( &$table ) {
1024 $return .= str_repeat( '<dl><dd>' , $table['indent'] );
1025 $return .= '<table';
1026 $return .= isset( $table['attributes'] ) ?
$table['attributes'] : '';
1028 unset( $table['attributes'] );
1030 if ( isset( $table['caption'] ) ) {
1031 $return .= "\n<caption";
1032 $return .= isset( $table['caption']['attributes'] ) ?
$table['caption']['attributes'] : '';
1034 $return .= $table['caption']['content'];
1035 $return .= "\n</caption>";
1041 // If we only have tbodies, mark table as simple
1042 for ( $i = 0; isset( $table[$i] ); $i++
) {
1043 if ( !count( $table[$i] ) ) continue;
1044 if ( !isset( $table[$i]['type'] ) ) {
1045 $table[$i]['type'] = 'tbody';
1047 if ( !$lastSection ) {
1048 $lastSection = $table[$i]['type'];
1049 } elseif ( $lastSection != $table[$i]['type'] ) {
1054 for ( $i = 0; isset( $table[$i] ); $i++
) {
1055 if ( !count( $table[$i] ) ) continue;
1056 $empty = false; // check for empty tables
1058 if ( $table[$i]['type'] != $lastSection && !$simple ) {
1059 $return .= "\n<" . $table[$i]['type'] . '>';
1063 $return .= isset( $table[$i]['attributes'] ) ?
$table[$i]['attributes'] : '';
1065 for ( $j = 0; isset( $table[$i][$j] ); $j++
) {
1066 if ( !isset( $table[$i][$j]['type'] ) ) $table[$i][$j]['type'] = 'td';
1067 $return .= "\n<" . $table[$i][$j]['type'];
1068 $return .= isset( $table[$i][$j]['attributes'] ) ?
$table[$i][$j]['attributes'] : '';
1071 $return .= $table[$i][$j]['content'];
1072 if ( $table[$i][$j]['content'] != '' )
1075 $return .= '</' . $table[$i][$j]['type'] . '>';
1076 unset( $table[$i][$j] );
1078 $return .= "\n</tr>";
1080 if ( ( !isset( $table[$i +
1] ) && !$simple ) ||
( isset( $table[$i +
1] ) && isset( $table[$i +
1]['type'] ) && $table[$i]['type'] != $table[$i +
1]['type'] ) ) {
1081 $return .= '</' . $table[$i]['type'] . '>';
1083 $lastSection = $table[$i]['type'];
1084 unset( $table[$i] );
1087 if ( isset( $table['caption'] ) ) {
1088 $return .= "\n<tr><td></td></tr>";
1093 $return .= "\n</table>";
1094 $return .= str_repeat( '</dd></dl>' , $table['indent'] );
1100 * like end() but only works on the numeric array index and php's internal pointers
1101 * returns a reference to the last element of an array much like "\$arr[-1]" in perl
1102 * ignores associative elements and will create a 0 key will a NULL value if there were
1103 * no numric elements and an array itself if not previously defined.
1107 function &last ( &$arr ) {
1108 for ( $i = count( $arr ); ( !isset( $arr[$i] ) && $i > 0 ); $i-- ) { }
1113 * Helper function for parse() that transforms wiki markup into
1114 * HTML. Only called for $mOutputType == self::OT_HTML.
1118 function internalParse( $text, $isMain = true, $frame=false ) {
1119 wfProfileIn( __METHOD__
);
1123 # Hook to suspend the parser in this state
1124 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1125 wfProfileOut( __METHOD__
);
1129 # if $frame is provided, then use $frame for replacing any variables
1131 # use frame depth to infer how include/noinclude tags should be handled
1132 # depth=0 means this is the top-level document; otherwise it's an included document
1133 if ( !$frame->depth
) {
1136 $flag = Parser
::PTD_FOR_INCLUSION
;
1138 $dom = $this->preprocessToDom( $text, $flag );
1139 $text = $frame->expand( $dom );
1141 # if $frame is not provided, then use old-style replaceVariables
1142 $text = $this->replaceVariables( $text );
1145 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1146 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1148 # Tables need to come after variable replacement for things to work
1149 # properly; putting them before other transformations should keep
1150 # exciting things like link expansions from showing up in surprising
1152 $text = $this->doTableStuff( $text );
1154 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1156 $text = $this->doDoubleUnderscore( $text );
1158 $text = $this->doHeadings( $text );
1159 if ( $this->mOptions
->getUseDynamicDates() ) {
1160 $df = DateFormatter
::getInstance();
1161 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1163 $text = $this->replaceInternalLinks( $text );
1164 $text = $this->doAllQuotes( $text );
1165 $text = $this->replaceExternalLinks( $text );
1167 # replaceInternalLinks may sometimes leave behind
1168 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1169 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
1171 $text = $this->doMagicLinks( $text );
1172 $text = $this->formatHeadings( $text, $origText, $isMain );
1174 wfProfileOut( __METHOD__
);
1179 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1180 * magic external links.
1185 function doMagicLinks( $text ) {
1186 wfProfileIn( __METHOD__
);
1187 $prots = $this->mUrlProtocols
;
1188 $urlChar = self
::EXT_LINK_URL_CLASS
;
1189 $text = preg_replace_callback(
1191 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1192 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1193 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1194 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1195 ISBN\s+(\b # m[5]: ISBN, capture number
1196 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1197 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1198 [0-9Xx] # check digit
1200 )!x', array( &$this, 'magicLinkCallback' ), $text );
1201 wfProfileOut( __METHOD__
);
1206 * @throws MWException
1208 * @return HTML|string
1210 function magicLinkCallback( $m ) {
1211 if ( isset( $m[1] ) && $m[1] !== '' ) {
1214 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1217 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1218 # Free external link
1219 return $this->makeFreeExternalLink( $m[0] );
1220 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1222 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1225 $CssClass = 'mw-magiclink-rfc';
1227 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1229 $urlmsg = 'pubmedurl';
1230 $CssClass = 'mw-magiclink-pmid';
1233 throw new MWException( __METHOD__
.': unrecognised match type "' .
1234 substr( $m[0], 0, 20 ) . '"' );
1236 $url = wfMsgForContent( $urlmsg, $id );
1237 return Linker
::makeExternalLink( $url, "{$keyword} {$id}", true, $CssClass );
1238 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1241 $num = strtr( $isbn, array(
1246 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1248 $titleObj->escapeLocalUrl() .
1249 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1256 * Make a free external link, given a user-supplied URL
1260 function makeFreeExternalLink( $url ) {
1262 wfProfileIn( __METHOD__
);
1266 # The characters '<' and '>' (which were escaped by
1267 # removeHTMLtags()) should not be included in
1268 # URLs, per RFC 2396.
1270 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1271 $trail = substr( $url, $m2[0][1] ) . $trail;
1272 $url = substr( $url, 0, $m2[0][1] );
1275 # Move trailing punctuation to $trail
1277 # If there is no left bracket, then consider right brackets fair game too
1278 if ( strpos( $url, '(' ) === false ) {
1282 $numSepChars = strspn( strrev( $url ), $sep );
1283 if ( $numSepChars ) {
1284 $trail = substr( $url, -$numSepChars ) . $trail;
1285 $url = substr( $url, 0, -$numSepChars );
1288 $url = Sanitizer
::cleanUrl( $url );
1290 # Is this an external image?
1291 $text = $this->maybeMakeExternalImage( $url );
1292 if ( $text === false ) {
1293 # Not an image, make a link
1294 $text = Linker
::makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1295 $this->getExternalLinkAttribs( $url ) );
1296 # Register it in the output object...
1297 # Replace unnecessary URL escape codes with their equivalent characters
1298 $pasteurized = self
::replaceUnusualEscapes( $url );
1299 $this->mOutput
->addExternalLink( $pasteurized );
1301 wfProfileOut( __METHOD__
);
1302 return $text . $trail;
1307 * Parse headers and return html
1311 function doHeadings( $text ) {
1312 wfProfileIn( __METHOD__
);
1313 for ( $i = 6; $i >= 1; --$i ) {
1314 $h = str_repeat( '=', $i );
1315 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1316 "<h$i>\\1</h$i>", $text );
1318 wfProfileOut( __METHOD__
);
1323 * Replace single quotes with HTML markup
1325 * @return string the altered text
1327 function doAllQuotes( $text ) {
1328 wfProfileIn( __METHOD__
);
1330 $lines = StringUtils
::explode( "\n", $text );
1331 foreach ( $lines as $line ) {
1332 $outtext .= $this->doQuotes( $line ) . "\n";
1334 $outtext = substr( $outtext, 0,-1 );
1335 wfProfileOut( __METHOD__
);
1340 * Helper function for doAllQuotes()
1342 public function doQuotes( $text ) {
1343 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1344 if ( count( $arr ) == 1 ) {
1347 # First, do some preliminary work. This may shift some apostrophes from
1348 # being mark-up to being text. It also counts the number of occurrences
1349 # of bold and italics mark-ups.
1352 for ( $i = 0; $i < count( $arr ); $i++
) {
1353 if ( ( $i %
2 ) == 1 ) {
1354 # If there are ever four apostrophes, assume the first is supposed to
1355 # be text, and the remaining three constitute mark-up for bold text.
1356 if ( strlen( $arr[$i] ) == 4 ) {
1359 } elseif ( strlen( $arr[$i] ) > 5 ) {
1360 # If there are more than 5 apostrophes in a row, assume they're all
1361 # text except for the last 5.
1362 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1365 # Count the number of occurrences of bold and italics mark-ups.
1366 # We are not counting sequences of five apostrophes.
1367 if ( strlen( $arr[$i] ) == 2 ) {
1369 } elseif ( strlen( $arr[$i] ) == 3 ) {
1371 } elseif ( strlen( $arr[$i] ) == 5 ) {
1378 # If there is an odd number of both bold and italics, it is likely
1379 # that one of the bold ones was meant to be an apostrophe followed
1380 # by italics. Which one we cannot know for certain, but it is more
1381 # likely to be one that has a single-letter word before it.
1382 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1384 $firstsingleletterword = -1;
1385 $firstmultiletterword = -1;
1387 foreach ( $arr as $r ) {
1388 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1389 $x1 = substr( $arr[$i-1], -1 );
1390 $x2 = substr( $arr[$i-1], -2, 1 );
1391 if ( $x1 === ' ' ) {
1392 if ( $firstspace == -1 ) {
1395 } elseif ( $x2 === ' ') {
1396 if ( $firstsingleletterword == -1 ) {
1397 $firstsingleletterword = $i;
1400 if ( $firstmultiletterword == -1 ) {
1401 $firstmultiletterword = $i;
1408 # If there is a single-letter word, use it!
1409 if ( $firstsingleletterword > -1 ) {
1410 $arr[$firstsingleletterword] = "''";
1411 $arr[$firstsingleletterword-1] .= "'";
1412 } elseif ( $firstmultiletterword > -1 ) {
1413 # If not, but there's a multi-letter word, use that one.
1414 $arr[$firstmultiletterword] = "''";
1415 $arr[$firstmultiletterword-1] .= "'";
1416 } elseif ( $firstspace > -1 ) {
1417 # ... otherwise use the first one that has neither.
1418 # (notice that it is possible for all three to be -1 if, for example,
1419 # there is only one pentuple-apostrophe in the line)
1420 $arr[$firstspace] = "''";
1421 $arr[$firstspace-1] .= "'";
1425 # Now let's actually convert our apostrophic mush to HTML!
1430 foreach ( $arr as $r ) {
1431 if ( ( $i %
2 ) == 0 ) {
1432 if ( $state === 'both' ) {
1438 if ( strlen( $r ) == 2 ) {
1439 if ( $state === 'i' ) {
1440 $output .= '</i>'; $state = '';
1441 } elseif ( $state === 'bi' ) {
1442 $output .= '</i>'; $state = 'b';
1443 } elseif ( $state === 'ib' ) {
1444 $output .= '</b></i><b>'; $state = 'b';
1445 } elseif ( $state === 'both' ) {
1446 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1447 } else { # $state can be 'b' or ''
1448 $output .= '<i>'; $state .= 'i';
1450 } elseif ( strlen( $r ) == 3 ) {
1451 if ( $state === 'b' ) {
1452 $output .= '</b>'; $state = '';
1453 } elseif ( $state === 'bi' ) {
1454 $output .= '</i></b><i>'; $state = 'i';
1455 } elseif ( $state === 'ib' ) {
1456 $output .= '</b>'; $state = 'i';
1457 } elseif ( $state === 'both' ) {
1458 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1459 } else { # $state can be 'i' or ''
1460 $output .= '<b>'; $state .= 'b';
1462 } elseif ( strlen( $r ) == 5 ) {
1463 if ( $state === 'b' ) {
1464 $output .= '</b><i>'; $state = 'i';
1465 } elseif ( $state === 'i' ) {
1466 $output .= '</i><b>'; $state = 'b';
1467 } elseif ( $state === 'bi' ) {
1468 $output .= '</i></b>'; $state = '';
1469 } elseif ( $state === 'ib' ) {
1470 $output .= '</b></i>'; $state = '';
1471 } elseif ( $state === 'both' ) {
1472 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1473 } else { # ($state == '')
1474 $buffer = ''; $state = 'both';
1480 # Now close all remaining tags. Notice that the order is important.
1481 if ( $state === 'b' ||
$state === 'ib' ) {
1484 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1487 if ( $state === 'bi' ) {
1490 # There might be lonely ''''', so make sure we have a buffer
1491 if ( $state === 'both' && $buffer ) {
1492 $output .= '<b><i>'.$buffer.'</i></b>';
1499 * Replace external links (REL)
1501 * Note: this is all very hackish and the order of execution matters a lot.
1502 * Make sure to run maintenance/parserTests.php if you change this code.
1506 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->getFunctionLang();
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 = $wgContLang->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: 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;
1588 $ns = $this->mTitle
->getNamespace();
1589 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) ) {
1590 $attribs['rel'] = 'nofollow';
1592 global $wgNoFollowDomainExceptions;
1593 if ( $wgNoFollowDomainExceptions ) {
1594 $bits = wfParseUrl( $url );
1595 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1596 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1597 if ( substr( $bits['host'], -strlen( $domain ) ) == $domain ) {
1598 unset( $attribs['rel'] );
1605 if ( $this->mOptions
->getExternalLinkTarget() ) {
1606 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1612 * Replace unusual URL escape codes with their equivalent characters
1614 * @param $url String
1617 * @todo This can merge genuinely required bits in the path or query string,
1618 * breaking legit URLs. A proper fix would treat the various parts of
1619 * the URL differently; as a workaround, just use the output for
1620 * statistical records, not for actual linking/output.
1622 static function replaceUnusualEscapes( $url ) {
1623 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1624 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1628 * Callback function used in replaceUnusualEscapes().
1629 * Replaces unusual URL escape codes with their equivalent character
1631 private static function replaceUnusualEscapesCallback( $matches ) {
1632 $char = urldecode( $matches[0] );
1633 $ord = ord( $char );
1634 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1635 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1636 # No, shouldn't be escaped
1639 # Yes, leave it escaped
1645 * make an image if it's allowed, either through the global
1646 * option, through the exception, or through the on-wiki whitelist
1649 function maybeMakeExternalImage( $url ) {
1650 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1651 $imagesexception = !empty( $imagesfrom );
1653 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1654 if ( $imagesexception && is_array( $imagesfrom ) ) {
1655 $imagematch = false;
1656 foreach ( $imagesfrom as $match ) {
1657 if ( strpos( $url, $match ) === 0 ) {
1662 } elseif ( $imagesexception ) {
1663 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1665 $imagematch = false;
1667 if ( $this->mOptions
->getAllowExternalImages()
1668 ||
( $imagesexception && $imagematch ) ) {
1669 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1671 $text = Linker
::makeExternalImage( $url );
1674 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1675 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1676 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1677 foreach ( $whitelist as $entry ) {
1678 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1679 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1682 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1683 # Image matches a whitelist entry
1684 $text = Linker
::makeExternalImage( $url );
1693 * 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 ) {
1712 wfProfileIn( __METHOD__
);
1714 wfProfileIn( __METHOD__
.'-setup' );
1715 static $tc = FALSE, $e1, $e1_img;
1716 # the % is needed to support urlencoded titles as well
1718 $tc = Title
::legalChars() . '#%';
1719 # Match a link having the form [[namespace:link|alternate]]trail
1720 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1721 # Match cases where there is no "]]", which might still be images
1722 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1725 $holders = new LinkHolderArray( $this );
1727 # split the entire text string on occurences of [[
1728 $a = StringUtils
::explode( '[[', ' ' . $s );
1729 # get the first element (all text up to first [[), and remove the space we added
1732 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1733 $s = substr( $s, 1 );
1735 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1737 if ( $useLinkPrefixExtension ) {
1738 # Match the end of a line for a word that's not followed by whitespace,
1739 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1740 $e2 = wfMsgForContent( 'linkprefix' );
1743 if ( is_null( $this->mTitle
) ) {
1744 wfProfileOut( __METHOD__
.'-setup' );
1745 wfProfileOut( __METHOD__
);
1746 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1748 $nottalk = !$this->mTitle
->isTalkPage();
1750 if ( $useLinkPrefixExtension ) {
1752 if ( preg_match( $e2, $s, $m ) ) {
1753 $first_prefix = $m[2];
1755 $first_prefix = false;
1761 if ( $wgContLang->hasVariants() ) {
1762 $selflink = $wgContLang->autoConvertToAllVariants( $this->mTitle
->getPrefixedText() );
1764 $selflink = array( $this->mTitle
->getPrefixedText() );
1766 $useSubpages = $this->areSubpagesAllowed();
1767 wfProfileOut( __METHOD__
.'-setup' );
1769 # Loop for each link
1770 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1771 # Check for excessive memory usage
1772 if ( $holders->isBig() ) {
1774 # Do the existence check, replace the link holders and clear the array
1775 $holders->replace( $s );
1779 if ( $useLinkPrefixExtension ) {
1780 wfProfileIn( __METHOD__
.'-prefixhandling' );
1781 if ( preg_match( $e2, $s, $m ) ) {
1788 if ( $first_prefix ) {
1789 $prefix = $first_prefix;
1790 $first_prefix = false;
1792 wfProfileOut( __METHOD__
.'-prefixhandling' );
1795 $might_be_img = false;
1797 wfProfileIn( __METHOD__
."-e1" );
1798 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1800 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1801 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1802 # the real problem is with the $e1 regex
1805 # Still some problems for cases where the ] is meant to be outside punctuation,
1806 # and no image is in sight. See bug 2095.
1808 if ( $text !== '' &&
1809 substr( $m[3], 0, 1 ) === ']' &&
1810 strpos( $text, '[' ) !== false
1813 $text .= ']'; # so that replaceExternalLinks($text) works later
1814 $m[3] = substr( $m[3], 1 );
1816 # fix up urlencoded title texts
1817 if ( strpos( $m[1], '%' ) !== false ) {
1818 # Should anchors '#' also be rejected?
1819 $m[1] = str_replace( array('<', '>'), array('<', '>'), rawurldecode( $m[1] ) );
1822 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1823 $might_be_img = true;
1825 if ( strpos( $m[1], '%' ) !== false ) {
1826 $m[1] = rawurldecode( $m[1] );
1829 } else { # Invalid form; output directly
1830 $s .= $prefix . '[[' . $line ;
1831 wfProfileOut( __METHOD__
."-e1" );
1834 wfProfileOut( __METHOD__
."-e1" );
1835 wfProfileIn( __METHOD__
."-misc" );
1837 # Don't allow internal links to pages containing
1838 # PROTO: where PROTO is a valid URL protocol; these
1839 # should be external links.
1840 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1841 $s .= $prefix . '[[' . $line ;
1842 wfProfileOut( __METHOD__
."-misc" );
1846 # Make subpage if necessary
1847 if ( $useSubpages ) {
1848 $link = $this->maybeDoSubpageLink( $m[1], $text );
1853 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1855 # Strip off leading ':'
1856 $link = substr( $link, 1 );
1859 wfProfileOut( __METHOD__
."-misc" );
1860 wfProfileIn( __METHOD__
."-title" );
1861 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1862 if ( $nt === null ) {
1863 $s .= $prefix . '[[' . $line;
1864 wfProfileOut( __METHOD__
."-title" );
1868 $ns = $nt->getNamespace();
1869 $iw = $nt->getInterWiki();
1870 wfProfileOut( __METHOD__
."-title" );
1872 if ( $might_be_img ) { # if this is actually an invalid link
1873 wfProfileIn( __METHOD__
."-might_be_img" );
1874 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1877 # look at the next 'line' to see if we can close it there
1879 $next_line = $a->current();
1880 if ( $next_line === false ||
$next_line === null ) {
1883 $m = explode( ']]', $next_line, 3 );
1884 if ( count( $m ) == 3 ) {
1885 # the first ]] closes the inner link, the second the image
1887 $text .= "[[{$m[0]}]]{$m[1]}";
1890 } elseif ( count( $m ) == 2 ) {
1891 # if there's exactly one ]] that's fine, we'll keep looking
1892 $text .= "[[{$m[0]}]]{$m[1]}";
1894 # if $next_line is invalid too, we need look no further
1895 $text .= '[[' . $next_line;
1900 # we couldn't find the end of this imageLink, so output it raw
1901 # but don't ignore what might be perfectly normal links in the text we've examined
1902 $holders->merge( $this->replaceInternalLinks2( $text ) );
1903 $s .= "{$prefix}[[$link|$text";
1904 # note: no $trail, because without an end, there *is* no trail
1905 wfProfileOut( __METHOD__
."-might_be_img" );
1908 } else { # it's not an image, so output it raw
1909 $s .= "{$prefix}[[$link|$text";
1910 # note: no $trail, because without an end, there *is* no trail
1911 wfProfileOut( __METHOD__
."-might_be_img" );
1914 wfProfileOut( __METHOD__
."-might_be_img" );
1917 $wasblank = ( $text == '' );
1921 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1922 # [[Lista d''e paise d''o munno]] -> <a href="...">Lista d''e paise d''o munno</a>
1923 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']]
1924 # -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1925 $text = $this->doQuotes( $text );
1928 # Link not escaped by : , create the various objects
1932 wfProfileIn( __METHOD__
."-interwiki" );
1933 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1934 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1935 $s = rtrim( $s . $prefix );
1936 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1937 wfProfileOut( __METHOD__
."-interwiki" );
1940 wfProfileOut( __METHOD__
."-interwiki" );
1942 if ( $ns == NS_FILE
) {
1943 wfProfileIn( __METHOD__
."-image" );
1944 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1946 # if no parameters were passed, $text
1947 # becomes something like "File:Foo.png",
1948 # which we don't want to pass on to the
1952 # recursively parse links inside the image caption
1953 # actually, this will parse them in any other parameters, too,
1954 # but it might be hard to fix that, and it doesn't matter ATM
1955 $text = $this->replaceExternalLinks( $text );
1956 $holders->merge( $this->replaceInternalLinks2( $text ) );
1958 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1959 $s .= $prefix . $this->armorLinks(
1960 $this->makeImage( $nt, $text, $holders ) ) . $trail;
1962 $s .= $prefix . $trail;
1964 wfProfileOut( __METHOD__
."-image" );
1968 if ( $ns == NS_CATEGORY
) {
1969 wfProfileIn( __METHOD__
."-category" );
1970 $s = rtrim( $s . "\n" ); # bug 87
1973 $sortkey = $this->getDefaultSort();
1977 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1978 $sortkey = str_replace( "\n", '', $sortkey );
1979 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1980 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1983 * Strip the whitespace Category links produce, see bug 87
1984 * @todo We might want to use trim($tmp, "\n") here.
1986 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
1988 wfProfileOut( __METHOD__
."-category" );
1993 # Self-link checking
1994 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1995 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1996 $s .= $prefix . Linker
::makeSelfLinkObj( $nt, $text, '', $trail );
2001 # NS_MEDIA is a pseudo-namespace for linking directly to a file
2002 # @todo FIXME: Should do batch file existence checks, see comment below
2003 if ( $ns == NS_MEDIA
) {
2004 wfProfileIn( __METHOD__
."-media" );
2005 # Give extensions a chance to select the file revision for us
2006 $time = $sha1 = $descQuery = false;
2007 wfRunHooks( 'BeforeParserFetchFileAndTitle',
2008 array( $this, $nt, &$time, &$sha1, &$descQuery ) );
2009 # Fetch and register the file (file title may be different via hooks)
2010 list( $file, $nt ) = $this->fetchFileAndTitle( $nt, $time, $sha1 );
2011 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
2012 $s .= $prefix . $this->armorLinks(
2013 Linker
::makeMediaLinkFile( $nt, $file, $text ) ) . $trail;
2014 wfProfileOut( __METHOD__
."-media" );
2018 wfProfileIn( __METHOD__
."-always_known" );
2019 # Some titles, such as valid special pages or files in foreign repos, should
2020 # be shown as bluelinks even though they're not included in the page table
2022 # @todo FIXME: isAlwaysKnown() can be expensive for file links; we should really do
2023 # batch file existence checks for NS_FILE and NS_MEDIA
2024 if ( $iw == '' && $nt->isAlwaysKnown() ) {
2025 $this->mOutput
->addLink( $nt );
2026 $s .= $this->makeKnownLinkHolder( $nt, $text, array(), $trail, $prefix );
2028 # Links will be added to the output link list after checking
2029 $s .= $holders->makeHolder( $nt, $text, array(), $trail, $prefix );
2031 wfProfileOut( __METHOD__
."-always_known" );
2033 wfProfileOut( __METHOD__
);
2038 * Render a forced-blue link inline; protect against double expansion of
2039 * URLs if we're in a mode that prepends full URL prefixes to internal links.
2040 * Since this little disaster has to split off the trail text to avoid
2041 * breaking URLs in the following text without breaking trails on the
2042 * wiki links, it's been made into a horrible function.
2045 * @param $text String
2046 * @param $query Array or String
2047 * @param $trail String
2048 * @param $prefix String
2049 * @return String: HTML-wikitext mix oh yuck
2051 function makeKnownLinkHolder( $nt, $text = '', $query = array(), $trail = '', $prefix = '' ) {
2052 list( $inside, $trail ) = Linker
::splitTrail( $trail );
2054 if ( is_string( $query ) ) {
2055 $query = wfCgiToArray( $query );
2057 if ( $text == '' ) {
2058 $text = htmlspecialchars( $nt->getPrefixedText() );
2061 $link = Linker
::linkKnown( $nt, "$prefix$text$inside", array(), $query );
2063 return $this->armorLinks( $link ) . $trail;
2067 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
2068 * going to go through further parsing steps before inline URL expansion.
2070 * Not needed quite as much as it used to be since free links are a bit
2071 * more sensible these days. But bracketed links are still an issue.
2073 * @param $text String: more-or-less HTML
2074 * @return String: less-or-more HTML with NOPARSE bits
2076 function armorLinks( $text ) {
2077 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
2078 "{$this->mUniqPrefix}NOPARSE$1", $text );
2082 * Return true if subpage links should be expanded on this page.
2085 function areSubpagesAllowed() {
2086 # Some namespaces don't allow subpages
2087 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2091 * Handle link to subpage if necessary
2093 * @param $target String: the source of the link
2094 * @param &$text String: the link text, modified as necessary
2095 * @return string the full name of the link
2098 function maybeDoSubpageLink( $target, &$text ) {
2099 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2103 * Used by doBlockLevels()
2108 function closeParagraph() {
2110 if ( $this->mLastSection
!= '' ) {
2111 $result = '</' . $this->mLastSection
. ">\n";
2113 $this->mInPre
= false;
2114 $this->mLastSection
= '';
2119 * getCommon() returns the length of the longest common substring
2120 * of both arguments, starting at the beginning of both.
2123 function getCommon( $st1, $st2 ) {
2124 $fl = strlen( $st1 );
2125 $shorter = strlen( $st2 );
2126 if ( $fl < $shorter ) {
2130 for ( $i = 0; $i < $shorter; ++
$i ) {
2131 if ( $st1[$i] != $st2[$i] ) {
2139 * These next three functions open, continue, and close the list
2140 * element appropriate to the prefix character passed into them.
2145 function openList( $char ) {
2146 $result = $this->closeParagraph();
2148 if ( '*' === $char ) {
2149 $result .= '<ul><li>';
2150 } elseif ( '#' === $char ) {
2151 $result .= '<ol><li>';
2152 } elseif ( ':' === $char ) {
2153 $result .= '<dl><dd>';
2154 } elseif ( ';' === $char ) {
2155 $result .= '<dl><dt>';
2156 $this->mDTopen
= true;
2158 $result = '<!-- ERR 1 -->';
2166 * @param $char String
2171 function nextItem( $char ) {
2172 if ( '*' === $char ||
'#' === $char ) {
2174 } elseif ( ':' === $char ||
';' === $char ) {
2176 if ( $this->mDTopen
) {
2179 if ( ';' === $char ) {
2180 $this->mDTopen
= true;
2181 return $close . '<dt>';
2183 $this->mDTopen
= false;
2184 return $close . '<dd>';
2187 return '<!-- ERR 2 -->';
2192 * @param $char String
2197 function closeList( $char ) {
2198 if ( '*' === $char ) {
2199 $text = '</li></ul>';
2200 } elseif ( '#' === $char ) {
2201 $text = '</li></ol>';
2202 } elseif ( ':' === $char ) {
2203 if ( $this->mDTopen
) {
2204 $this->mDTopen
= false;
2205 $text = '</dt></dl>';
2207 $text = '</dd></dl>';
2210 return '<!-- ERR 3 -->';
2217 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2219 * @param $text String
2220 * @param $linestart Boolean: whether or not this is at the start of a line.
2222 * @return string the lists rendered as HTML
2224 function doBlockLevels( $text, $linestart ) {
2225 wfProfileIn( __METHOD__
);
2227 # Parsing through the text line by line. The main thing
2228 # happening here is handling of block-level elements p, pre,
2229 # and making lists from lines starting with * # : etc.
2231 $textLines = StringUtils
::explode( "\n", $text );
2233 $lastPrefix = $output = '';
2234 $this->mDTopen
= $inBlockElem = false;
2236 $paragraphStack = false;
2238 foreach ( $textLines as $oLine ) {
2240 if ( !$linestart ) {
2250 $lastPrefixLength = strlen( $lastPrefix );
2251 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2252 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2253 # If not in a <pre> element, scan for and figure out what prefixes are there.
2254 if ( !$this->mInPre
) {
2255 # Multiple prefixes may abut each other for nested lists.
2256 $prefixLength = strspn( $oLine, '*#:;' );
2257 $prefix = substr( $oLine, 0, $prefixLength );
2260 # ; and : are both from definition-lists, so they're equivalent
2261 # for the purposes of determining whether or not we need to open/close
2263 $prefix2 = str_replace( ';', ':', $prefix );
2264 $t = substr( $oLine, $prefixLength );
2265 $this->mInPre
= (bool)$preOpenMatch;
2267 # Don't interpret any other prefixes in preformatted text
2269 $prefix = $prefix2 = '';
2274 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2275 # Same as the last item, so no need to deal with nesting or opening stuff
2276 $output .= $this->nextItem( substr( $prefix, -1 ) );
2277 $paragraphStack = false;
2279 if ( substr( $prefix, -1 ) === ';') {
2280 # The one nasty exception: definition lists work like this:
2281 # ; title : definition text
2282 # So we check for : in the remainder text to split up the
2283 # title and definition, without b0rking links.
2285 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2287 $output .= $term . $this->nextItem( ':' );
2290 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2291 # We need to open or close prefixes, or both.
2293 # Either open or close a level...
2294 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2295 $paragraphStack = false;
2297 # Close all the prefixes which aren't shared.
2298 while ( $commonPrefixLength < $lastPrefixLength ) {
2299 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2300 --$lastPrefixLength;
2303 # Continue the current prefix if appropriate.
2304 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2305 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2308 # Open prefixes where appropriate.
2309 while ( $prefixLength > $commonPrefixLength ) {
2310 $char = substr( $prefix, $commonPrefixLength, 1 );
2311 $output .= $this->openList( $char );
2313 if ( ';' === $char ) {
2314 # @todo FIXME: This is dupe of code above
2315 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2317 $output .= $term . $this->nextItem( ':' );
2320 ++
$commonPrefixLength;
2322 $lastPrefix = $prefix2;
2325 # If we have no prefixes, go to paragraph mode.
2326 if ( 0 == $prefixLength ) {
2327 wfProfileIn( __METHOD__
."-paragraph" );
2328 # No prefix (not in list)--go to paragraph mode
2329 # XXX: use a stack for nestable elements like span, table and div
2330 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2331 $closematch = preg_match(
2332 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2333 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2334 if ( $openmatch or $closematch ) {
2335 $paragraphStack = false;
2336 # TODO bug 5718: paragraph closed
2337 $output .= $this->closeParagraph();
2338 if ( $preOpenMatch and !$preCloseMatch ) {
2339 $this->mInPre
= true;
2341 $inBlockElem = !$closematch;
2342 } elseif ( !$inBlockElem && !$this->mInPre
) {
2343 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2345 if ( $this->mLastSection
!== 'pre' ) {
2346 $paragraphStack = false;
2347 $output .= $this->closeParagraph().'<pre>';
2348 $this->mLastSection
= 'pre';
2350 $t = substr( $t, 1 );
2353 if ( trim( $t ) === '' ) {
2354 if ( $paragraphStack ) {
2355 $output .= $paragraphStack.'<br />';
2356 $paragraphStack = false;
2357 $this->mLastSection
= 'p';
2359 if ( $this->mLastSection
!== 'p' ) {
2360 $output .= $this->closeParagraph();
2361 $this->mLastSection
= '';
2362 $paragraphStack = '<p>';
2364 $paragraphStack = '</p><p>';
2368 if ( $paragraphStack ) {
2369 $output .= $paragraphStack;
2370 $paragraphStack = false;
2371 $this->mLastSection
= 'p';
2372 } elseif ( $this->mLastSection
!== 'p' ) {
2373 $output .= $this->closeParagraph().'<p>';
2374 $this->mLastSection
= 'p';
2379 wfProfileOut( __METHOD__
."-paragraph" );
2381 # somewhere above we forget to get out of pre block (bug 785)
2382 if ( $preCloseMatch && $this->mInPre
) {
2383 $this->mInPre
= false;
2385 if ( $paragraphStack === false ) {
2389 while ( $prefixLength ) {
2390 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2393 if ( $this->mLastSection
!= '' ) {
2394 $output .= '</' . $this->mLastSection
. '>';
2395 $this->mLastSection
= '';
2398 wfProfileOut( __METHOD__
);
2403 * Split up a string on ':', ignoring any occurences inside tags
2404 * to prevent illegal overlapping.
2406 * @param $str String: the string to split
2407 * @param &$before String: set to everything before the ':'
2408 * @param &$after String: set to everything after the ':'
2409 * return String: the position of the ':', or false if none found
2411 function findColonNoLinks( $str, &$before, &$after ) {
2412 wfProfileIn( __METHOD__
);
2414 $pos = strpos( $str, ':' );
2415 if ( $pos === false ) {
2417 wfProfileOut( __METHOD__
);
2421 $lt = strpos( $str, '<' );
2422 if ( $lt === false ||
$lt > $pos ) {
2423 # Easy; no tag nesting to worry about
2424 $before = substr( $str, 0, $pos );
2425 $after = substr( $str, $pos+
1 );
2426 wfProfileOut( __METHOD__
);
2430 # Ugly state machine to walk through avoiding tags.
2431 $state = self
::COLON_STATE_TEXT
;
2433 $len = strlen( $str );
2434 for( $i = 0; $i < $len; $i++
) {
2438 # (Using the number is a performance hack for common cases)
2439 case 0: # self::COLON_STATE_TEXT:
2442 # Could be either a <start> tag or an </end> tag
2443 $state = self
::COLON_STATE_TAGSTART
;
2446 if ( $stack == 0 ) {
2448 $before = substr( $str, 0, $i );
2449 $after = substr( $str, $i +
1 );
2450 wfProfileOut( __METHOD__
);
2453 # Embedded in a tag; don't break it.
2456 # Skip ahead looking for something interesting
2457 $colon = strpos( $str, ':', $i );
2458 if ( $colon === false ) {
2459 # Nothing else interesting
2460 wfProfileOut( __METHOD__
);
2463 $lt = strpos( $str, '<', $i );
2464 if ( $stack === 0 ) {
2465 if ( $lt === false ||
$colon < $lt ) {
2467 $before = substr( $str, 0, $colon );
2468 $after = substr( $str, $colon +
1 );
2469 wfProfileOut( __METHOD__
);
2473 if ( $lt === false ) {
2474 # Nothing else interesting to find; abort!
2475 # We're nested, but there's no close tags left. Abort!
2478 # Skip ahead to next tag start
2480 $state = self
::COLON_STATE_TAGSTART
;
2483 case 1: # self::COLON_STATE_TAG:
2488 $state = self
::COLON_STATE_TEXT
;
2491 # Slash may be followed by >?
2492 $state = self
::COLON_STATE_TAGSLASH
;
2498 case 2: # self::COLON_STATE_TAGSTART:
2501 $state = self
::COLON_STATE_CLOSETAG
;
2504 $state = self
::COLON_STATE_COMMENT
;
2507 # Illegal early close? This shouldn't happen D:
2508 $state = self
::COLON_STATE_TEXT
;
2511 $state = self
::COLON_STATE_TAG
;
2514 case 3: # self::COLON_STATE_CLOSETAG:
2519 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2520 wfProfileOut( __METHOD__
);
2523 $state = self
::COLON_STATE_TEXT
;
2526 case self
::COLON_STATE_TAGSLASH
:
2528 # Yes, a self-closed tag <blah/>
2529 $state = self
::COLON_STATE_TEXT
;
2531 # Probably we're jumping the gun, and this is an attribute
2532 $state = self
::COLON_STATE_TAG
;
2535 case 5: # self::COLON_STATE_COMMENT:
2537 $state = self
::COLON_STATE_COMMENTDASH
;
2540 case self
::COLON_STATE_COMMENTDASH
:
2542 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2544 $state = self
::COLON_STATE_COMMENT
;
2547 case self
::COLON_STATE_COMMENTDASHDASH
:
2549 $state = self
::COLON_STATE_TEXT
;
2551 $state = self
::COLON_STATE_COMMENT
;
2555 throw new MWException( "State machine error in " . __METHOD__
);
2559 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2560 wfProfileOut( __METHOD__
);
2563 wfProfileOut( __METHOD__
);
2568 * Return value of a magic variable (like PAGENAME)
2572 * @param $index integer
2573 * @param $frame PPFrame
2575 function getVariableValue( $index, $frame=false ) {
2576 global $wgContLang, $wgSitename, $wgServer;
2577 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2580 * Some of these require message or data lookups and can be
2581 * expensive to check many times.
2583 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2584 if ( isset( $this->mVarCache
[$index] ) ) {
2585 return $this->mVarCache
[$index];
2589 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2590 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2593 global $wgLocaltimezone;
2594 if ( isset( $wgLocaltimezone ) ) {
2595 $oldtz = date_default_timezone_get();
2596 date_default_timezone_set( $wgLocaltimezone );
2599 $localTimestamp = date( 'YmdHis', $ts );
2600 $localMonth = date( 'm', $ts );
2601 $localMonth1 = date( 'n', $ts );
2602 $localMonthName = date( 'n', $ts );
2603 $localDay = date( 'j', $ts );
2604 $localDay2 = date( 'd', $ts );
2605 $localDayOfWeek = date( 'w', $ts );
2606 $localWeek = date( 'W', $ts );
2607 $localYear = date( 'Y', $ts );
2608 $localHour = date( 'H', $ts );
2609 if ( isset( $wgLocaltimezone ) ) {
2610 date_default_timezone_set( $oldtz );
2614 case 'currentmonth':
2615 $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2617 case 'currentmonth1':
2618 $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2620 case 'currentmonthname':
2621 $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2623 case 'currentmonthnamegen':
2624 $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2626 case 'currentmonthabbrev':
2627 $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2630 $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2633 $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2636 $value = $wgContLang->formatNum( $localMonth );
2639 $value = $wgContLang->formatNum( $localMonth1 );
2641 case 'localmonthname':
2642 $value = $wgContLang->getMonthName( $localMonthName );
2644 case 'localmonthnamegen':
2645 $value = $wgContLang->getMonthNameGen( $localMonthName );
2647 case 'localmonthabbrev':
2648 $value = $wgContLang->getMonthAbbreviation( $localMonthName );
2651 $value = $wgContLang->formatNum( $localDay );
2654 $value = $wgContLang->formatNum( $localDay2 );
2657 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2660 $value = wfEscapeWikiText( $this->mTitle
->getPartialURL() );
2662 case 'fullpagename':
2663 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2665 case 'fullpagenamee':
2666 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedURL() );
2669 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2671 case 'subpagenamee':
2672 $value = wfEscapeWikiText( $this->mTitle
->getSubpageUrlForm() );
2674 case 'basepagename':
2675 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2677 case 'basepagenamee':
2678 $value = wfEscapeWikiText( wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) ) );
2680 case 'talkpagename':
2681 if ( $this->mTitle
->canTalk() ) {
2682 $talkPage = $this->mTitle
->getTalkPage();
2683 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2688 case 'talkpagenamee':
2689 if ( $this->mTitle
->canTalk() ) {
2690 $talkPage = $this->mTitle
->getTalkPage();
2691 $value = wfEscapeWikiText( $talkPage->getPrefixedUrl() );
2696 case 'subjectpagename':
2697 $subjPage = $this->mTitle
->getSubjectPage();
2698 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2700 case 'subjectpagenamee':
2701 $subjPage = $this->mTitle
->getSubjectPage();
2702 $value = wfEscapeWikiText( $subjPage->getPrefixedUrl() );
2705 # Let the edit saving system know we should parse the page
2706 # *after* a revision ID has been assigned.
2707 $this->mOutput
->setFlag( 'vary-revision' );
2708 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2709 $value = $this->mRevisionId
;
2712 # Let the edit saving system know we should parse the page
2713 # *after* a revision ID has been assigned. This is for null edits.
2714 $this->mOutput
->setFlag( 'vary-revision' );
2715 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2716 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2718 case 'revisionday2':
2719 # Let the edit saving system know we should parse the page
2720 # *after* a revision ID has been assigned. This is for null edits.
2721 $this->mOutput
->setFlag( 'vary-revision' );
2722 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2723 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2725 case 'revisionmonth':
2726 # Let the edit saving system know we should parse the page
2727 # *after* a revision ID has been assigned. This is for null edits.
2728 $this->mOutput
->setFlag( 'vary-revision' );
2729 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2730 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2732 case 'revisionmonth1':
2733 # Let the edit saving system know we should parse the page
2734 # *after* a revision ID has been assigned. This is for null edits.
2735 $this->mOutput
->setFlag( 'vary-revision' );
2736 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2737 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2739 case 'revisionyear':
2740 # Let the edit saving system know we should parse the page
2741 # *after* a revision ID has been assigned. This is for null edits.
2742 $this->mOutput
->setFlag( 'vary-revision' );
2743 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2744 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2746 case 'revisiontimestamp':
2747 # Let the edit saving system know we should parse the page
2748 # *after* a revision ID has been assigned. This is for null edits.
2749 $this->mOutput
->setFlag( 'vary-revision' );
2750 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2751 $value = $this->getRevisionTimestamp();
2753 case 'revisionuser':
2754 # Let the edit saving system know we should parse the page
2755 # *after* a revision ID has been assigned. This is for null edits.
2756 $this->mOutput
->setFlag( 'vary-revision' );
2757 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2758 $value = $this->getRevisionUser();
2761 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2764 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2767 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2770 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2772 case 'subjectspace':
2773 $value = $this->mTitle
->getSubjectNsText();
2775 case 'subjectspacee':
2776 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2778 case 'currentdayname':
2779 $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2782 $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2785 $value = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2788 $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2791 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2792 # int to remove the padding
2793 $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2796 $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2798 case 'localdayname':
2799 $value = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2802 $value = $wgContLang->formatNum( $localYear, true );
2805 $value = $wgContLang->time( $localTimestamp, false, false );
2808 $value = $wgContLang->formatNum( $localHour, true );
2811 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2812 # int to remove the padding
2813 $value = $wgContLang->formatNum( (int)$localWeek );
2816 $value = $wgContLang->formatNum( $localDayOfWeek );
2818 case 'numberofarticles':
2819 $value = $wgContLang->formatNum( SiteStats
::articles() );
2821 case 'numberoffiles':
2822 $value = $wgContLang->formatNum( SiteStats
::images() );
2824 case 'numberofusers':
2825 $value = $wgContLang->formatNum( SiteStats
::users() );
2827 case 'numberofactiveusers':
2828 $value = $wgContLang->formatNum( SiteStats
::activeUsers() );
2830 case 'numberofpages':
2831 $value = $wgContLang->formatNum( SiteStats
::pages() );
2833 case 'numberofadmins':
2834 $value = $wgContLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2836 case 'numberofedits':
2837 $value = $wgContLang->formatNum( SiteStats
::edits() );
2839 case 'numberofviews':
2840 $value = $wgContLang->formatNum( SiteStats
::views() );
2842 case 'currenttimestamp':
2843 $value = wfTimestamp( TS_MW
, $ts );
2845 case 'localtimestamp':
2846 $value = $localTimestamp;
2848 case 'currentversion':
2849 $value = SpecialVersion
::getVersion();
2852 return $wgArticlePath;
2858 wfSuppressWarnings(); # May give an E_WARNING in PHP < 5.3.3
2859 $serverName = parse_url( $wgServer, PHP_URL_HOST
);
2860 wfRestoreWarnings();
2861 return $serverName ?
$serverName : $wgServer;
2863 return $wgScriptPath;
2865 return $wgStylePath;
2866 case 'directionmark':
2867 return $wgContLang->getDirMark();
2868 case 'contentlanguage':
2869 global $wgLanguageCode;
2870 return $wgLanguageCode;
2873 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2881 $this->mVarCache
[$index] = $value;
2887 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2891 function initialiseVariables() {
2892 wfProfileIn( __METHOD__
);
2893 $variableIDs = MagicWord
::getVariableIDs();
2894 $substIDs = MagicWord
::getSubstIDs();
2896 $this->mVariables
= new MagicWordArray( $variableIDs );
2897 $this->mSubstWords
= new MagicWordArray( $substIDs );
2898 wfProfileOut( __METHOD__
);
2902 * Preprocess some wikitext and return the document tree.
2903 * This is the ghost of replace_variables().
2905 * @param $text String: The text to parse
2906 * @param $flags Integer: bitwise combination of:
2907 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2908 * included. Default is to assume a direct page view.
2910 * The generated DOM tree must depend only on the input text and the flags.
2911 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2913 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2914 * change in the DOM tree for a given text, must be passed through the section identifier
2915 * in the section edit link and thus back to extractSections().
2917 * The output of this function is currently only cached in process memory, but a persistent
2918 * cache may be implemented at a later date which takes further advantage of these strict
2919 * dependency requirements.
2925 function preprocessToDom( $text, $flags = 0 ) {
2926 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2931 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2935 public static function splitWhitespace( $s ) {
2936 $ltrimmed = ltrim( $s );
2937 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2938 $trimmed = rtrim( $ltrimmed );
2939 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2941 $w2 = substr( $ltrimmed, -$diff );
2945 return array( $w1, $trimmed, $w2 );
2949 * Replace magic variables, templates, and template arguments
2950 * with the appropriate text. Templates are substituted recursively,
2951 * taking care to avoid infinite loops.
2953 * Note that the substitution depends on value of $mOutputType:
2954 * self::OT_WIKI: only {{subst:}} templates
2955 * self::OT_PREPROCESS: templates but not extension tags
2956 * self::OT_HTML: all templates and extension tags
2958 * @param $text String: the text to transform
2959 * @param $frame PPFrame Object describing the arguments passed to the template.
2960 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2961 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2962 * @param $argsOnly Boolean: only do argument (triple-brace) expansion, not double-brace expansion
2967 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2968 # Is there any text? Also, Prevent too big inclusions!
2969 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2972 wfProfileIn( __METHOD__
);
2974 if ( $frame === false ) {
2975 $frame = $this->getPreprocessor()->newFrame();
2976 } elseif ( !( $frame instanceof PPFrame
) ) {
2977 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2978 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2981 $dom = $this->preprocessToDom( $text );
2982 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2983 $text = $frame->expand( $dom, $flags );
2985 wfProfileOut( __METHOD__
);
2990 * Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2994 static function createAssocArgs( $args ) {
2995 $assocArgs = array();
2997 foreach ( $args as $arg ) {
2998 $eqpos = strpos( $arg, '=' );
2999 if ( $eqpos === false ) {
3000 $assocArgs[$index++
] = $arg;
3002 $name = trim( substr( $arg, 0, $eqpos ) );
3003 $value = trim( substr( $arg, $eqpos+
1 ) );
3004 if ( $value === false ) {
3007 if ( $name !== false ) {
3008 $assocArgs[$name] = $value;
3017 * Warn the user when a parser limitation is reached
3018 * Will warn at most once the user per limitation type
3020 * @param $limitationType String: should be one of:
3021 * 'expensive-parserfunction' (corresponding messages:
3022 * 'expensive-parserfunction-warning',
3023 * 'expensive-parserfunction-category')
3024 * 'post-expand-template-argument' (corresponding messages:
3025 * 'post-expand-template-argument-warning',
3026 * 'post-expand-template-argument-category')
3027 * 'post-expand-template-inclusion' (corresponding messages:
3028 * 'post-expand-template-inclusion-warning',
3029 * 'post-expand-template-inclusion-category')
3030 * @param $current Current value
3031 * @param $max Maximum allowed, when an explicit limit has been
3032 * exceeded, provide the values (optional)
3034 function limitationWarn( $limitationType, $current=null, $max=null) {
3035 # does no harm if $current and $max are present but are unnecessary for the message
3036 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
3037 $this->mOutput
->addWarning( $warning );
3038 $this->addTrackingCategory( "$limitationType-category" );
3042 * Return the text of a template, after recursively
3043 * replacing any variables or templates within the template.
3045 * @param $piece Array: the parts of the template
3046 * $piece['title']: the title, i.e. the part before the |
3047 * $piece['parts']: the parameter array
3048 * $piece['lineStart']: whether the brace was at the start of a line
3049 * @param $frame PPFrame The current frame, contains template arguments
3050 * @return String: the text of the template
3053 function braceSubstitution( $piece, $frame ) {
3054 global $wgContLang, $wgNonincludableNamespaces;
3055 wfProfileIn( __METHOD__
);
3056 wfProfileIn( __METHOD__
.'-setup' );
3059 $found = false; # $text has been filled
3060 $nowiki = false; # wiki markup in $text should be escaped
3061 $isHTML = false; # $text is HTML, armour it against wikitext transformation
3062 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
3063 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
3064 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
3066 # Title object, where $text came from
3069 # $part1 is the bit before the first |, and must contain only title characters.
3070 # Various prefixes will be stripped from it later.
3071 $titleWithSpaces = $frame->expand( $piece['title'] );
3072 $part1 = trim( $titleWithSpaces );
3075 # Original title text preserved for various purposes
3076 $originalTitle = $part1;
3078 # $args is a list of argument nodes, starting from index 0, not including $part1
3079 # @todo FIXME: If piece['parts'] is null then the call to getLength() below won't work b/c this $args isn't an object
3080 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
3081 wfProfileOut( __METHOD__
.'-setup' );
3082 wfProfileIn( __METHOD__
."-title-$originalTitle" );
3085 wfProfileIn( __METHOD__
.'-modifiers' );
3088 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
3090 # Possibilities for substMatch: "subst", "safesubst" or FALSE
3091 # Decide whether to expand template or keep wikitext as-is.
3092 if ( $this->ot
['wiki'] ) {
3093 if ( $substMatch === false ) {
3094 $literal = true; # literal when in PST with no prefix
3096 $literal = false; # expand when in PST with subst: or safesubst:
3099 if ( $substMatch == 'subst' ) {
3100 $literal = true; # literal when not in PST with plain subst:
3102 $literal = false; # expand when not in PST with safesubst: or no prefix
3106 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3113 if ( !$found && $args->getLength() == 0 ) {
3114 $id = $this->mVariables
->matchStartToEnd( $part1 );
3115 if ( $id !== false ) {
3116 $text = $this->getVariableValue( $id, $frame );
3117 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3118 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3124 # MSG, MSGNW and RAW
3127 $mwMsgnw = MagicWord
::get( 'msgnw' );
3128 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3131 # Remove obsolete MSG:
3132 $mwMsg = MagicWord
::get( 'msg' );
3133 $mwMsg->matchStartAndRemove( $part1 );
3137 $mwRaw = MagicWord
::get( 'raw' );
3138 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3139 $forceRawInterwiki = true;
3142 wfProfileOut( __METHOD__
.'-modifiers' );
3146 wfProfileIn( __METHOD__
. '-pfunc' );
3148 $colonPos = strpos( $part1, ':' );
3149 if ( $colonPos !== false ) {
3150 # Case sensitive functions
3151 $function = substr( $part1, 0, $colonPos );
3152 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3153 $function = $this->mFunctionSynonyms
[1][$function];
3155 # Case insensitive functions
3156 $function = $wgContLang->lc( $function );
3157 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3158 $function = $this->mFunctionSynonyms
[0][$function];
3164 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3165 $initialArgs = array( &$this );
3166 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3167 if ( $flags & SFH_OBJECT_ARGS
) {
3168 # Add a frame parameter, and pass the arguments as an array
3169 $allArgs = $initialArgs;
3170 $allArgs[] = $frame;
3171 for ( $i = 0; $i < $args->getLength(); $i++
) {
3172 $funcArgs[] = $args->item( $i );
3174 $allArgs[] = $funcArgs;
3176 # Convert arguments to plain text
3177 for ( $i = 0; $i < $args->getLength(); $i++
) {
3178 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3180 $allArgs = array_merge( $initialArgs, $funcArgs );
3183 # Workaround for PHP bug 35229 and similar
3184 if ( !is_callable( $callback ) ) {
3185 wfProfileOut( __METHOD__
. '-pfunc' );
3186 wfProfileOut( __METHOD__
);
3187 throw new MWException( "Tag hook for $function is not callable\n" );
3189 $result = call_user_func_array( $callback, $allArgs );
3192 $preprocessFlags = 0;
3194 if ( is_array( $result ) ) {
3195 if ( isset( $result[0] ) ) {
3197 unset( $result[0] );
3200 # Extract flags into the local scope
3201 # This allows callers to set flags such as nowiki, found, etc.
3207 $text = $this->preprocessToDom( $text, $preprocessFlags );
3212 wfProfileOut( __METHOD__
. '-pfunc' );
3215 # Finish mangling title and then check for loops.
3216 # Set $title to a Title object and $titleText to the PDBK
3219 # Split the title into page and subpage
3221 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3222 if ( $subpage !== '' ) {
3223 $ns = $this->mTitle
->getNamespace();
3225 $title = Title
::newFromText( $part1, $ns );
3227 $titleText = $title->getPrefixedText();
3228 # Check for language variants if the template is not found
3229 if ( $wgContLang->hasVariants() && $title->getArticleID() == 0 ) {
3230 $wgContLang->findVariantLink( $part1, $title, true );
3232 # Do recursion depth check
3233 $limit = $this->mOptions
->getMaxTemplateDepth();
3234 if ( $frame->depth
>= $limit ) {
3236 $text = '<span class="error">'
3237 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
3243 # Load from database
3244 if ( !$found && $title ) {
3245 wfProfileIn( __METHOD__
. '-loadtpl' );
3246 if ( !$title->isExternal() ) {
3247 if ( $title->getNamespace() == NS_SPECIAL
3248 && $this->mOptions
->getAllowSpecialInclusion()
3249 && $this->ot
['html'] )
3251 $text = SpecialPageFactory
::capturePath( $title );
3252 if ( is_string( $text ) ) {
3255 $this->disableCache();
3257 } elseif ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3258 $found = false; # access denied
3259 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3261 list( $text, $title ) = $this->getTemplateDom( $title );
3262 if ( $text !== false ) {
3268 # If the title is valid but undisplayable, make a link to it
3269 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3270 $text = "[[:$titleText]]";
3273 } elseif ( $title->isTrans() ) {
3274 # Interwiki transclusion
3275 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3276 $text = $this->interwikiTransclude( $title, 'render' );
3279 $text = $this->interwikiTransclude( $title, 'raw' );
3280 # Preprocess it like a template
3281 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3287 # Do infinite loop check
3288 # This has to be done after redirect resolution to avoid infinite loops via redirects
3289 if ( !$frame->loopCheck( $title ) ) {
3291 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3292 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3294 wfProfileOut( __METHOD__
. '-loadtpl' );
3297 # If we haven't found text to substitute by now, we're done
3298 # Recover the source wikitext and return it
3300 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3301 wfProfileOut( __METHOD__
."-title-$originalTitle" );
3302 wfProfileOut( __METHOD__
);
3303 return array( 'object' => $text );
3306 # Expand DOM-style return values in a child frame
3307 if ( $isChildObj ) {
3308 # Clean up argument array
3309 $newFrame = $frame->newChild( $args, $title );
3312 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3313 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3314 # Expansion is eligible for the empty-frame cache
3315 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3316 $text = $this->mTplExpandCache
[$titleText];
3318 $text = $newFrame->expand( $text );
3319 $this->mTplExpandCache
[$titleText] = $text;
3322 # Uncached expansion
3323 $text = $newFrame->expand( $text );
3326 if ( $isLocalObj && $nowiki ) {
3327 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3328 $isLocalObj = false;
3331 # Replace raw HTML by a placeholder
3332 # Add a blank line preceding, to prevent it from mucking up
3333 # immediately preceding headings
3335 $text = "\n\n" . $this->insertStripItem( $text );
3336 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3337 # Escape nowiki-style return values
3338 $text = wfEscapeWikiText( $text );
3339 } elseif ( is_string( $text )
3340 && !$piece['lineStart']
3341 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3343 # Bug 529: if the template begins with a table or block-level
3344 # element, it should be treated as beginning a new line.
3345 # This behaviour is somewhat controversial.
3346 $text = "\n" . $text;
3349 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3350 # Error, oversize inclusion
3351 if ( $titleText !== false ) {
3352 # Make a working, properly escaped link if possible (bug 23588)
3353 $text = "[[:$titleText]]";
3355 # This will probably not be a working link, but at least it may
3356 # provide some hint of where the problem is
3357 preg_replace( '/^:/', '', $originalTitle );
3358 $text = "[[:$originalTitle]]";
3360 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3361 $this->limitationWarn( 'post-expand-template-inclusion' );
3364 if ( $isLocalObj ) {
3365 $ret = array( 'object' => $text );
3367 $ret = array( 'text' => $text );
3370 wfProfileOut( __METHOD__
."-title-$originalTitle" );
3371 wfProfileOut( __METHOD__
);
3376 * Get the semi-parsed DOM representation of a template with a given title,
3377 * and its redirect destination title. Cached.
3381 function getTemplateDom( $title ) {
3382 $cacheTitle = $title;
3383 $titleText = $title->getPrefixedDBkey();
3385 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3386 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3387 $title = Title
::makeTitle( $ns, $dbk );
3388 $titleText = $title->getPrefixedDBkey();
3390 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3391 return array( $this->mTplDomCache
[$titleText], $title );
3394 # Cache miss, go to the database
3395 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3397 if ( $text === false ) {
3398 $this->mTplDomCache
[$titleText] = false;
3399 return array( false, $title );
3402 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3403 $this->mTplDomCache
[ $titleText ] = $dom;
3405 if ( !$title->equals( $cacheTitle ) ) {
3406 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3407 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3410 return array( $dom, $title );
3414 * Fetch the unparsed text of a template and register a reference to it.
3415 * @param Title $title
3416 * @return Array ( string or false, Title )
3418 function fetchTemplateAndTitle( $title ) {
3419 $templateCb = $this->mOptions
->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3420 $stuff = call_user_func( $templateCb, $title, $this );
3421 $text = $stuff['text'];
3422 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3423 if ( isset( $stuff['deps'] ) ) {
3424 foreach ( $stuff['deps'] as $dep ) {
3425 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3428 return array( $text, $finalTitle );
3432 * Fetch the unparsed text of a template and register a reference to it.
3433 * @param Title $title
3434 * @return mixed string or false
3436 function fetchTemplate( $title ) {
3437 $rv = $this->fetchTemplateAndTitle( $title );
3442 * Static function to get a template
3443 * Can be overridden via ParserOptions::setTemplateCallback().
3447 static function statelessFetchTemplate( $title, $parser = false ) {
3448 $text = $skip = false;
3449 $finalTitle = $title;
3452 # Loop to fetch the article, with up to 1 redirect
3453 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3454 # Give extensions a chance to select the revision instead
3455 $id = false; # Assume current
3456 wfRunHooks( 'BeforeParserFetchTemplateAndtitle',
3457 array( $parser, $title, &$skip, &$id ) );
3463 'page_id' => $title->getArticleID(),
3470 ? Revision
::newFromId( $id )
3471 : Revision
::newFromTitle( $title );
3472 $rev_id = $rev ?
$rev->getId() : 0;
3473 # If there is no current revision, there is no page
3474 if ( $id === false && !$rev ) {
3475 $linkCache = LinkCache
::singleton();
3476 $linkCache->addBadLinkObj( $title );
3481 'page_id' => $title->getArticleID(),
3482 'rev_id' => $rev_id );
3483 if ( $rev && !$title->equals( $rev->getTitle() ) ) {
3484 # We fetched a rev from a different title; register it too...
3486 'title' => $rev->getTitle(),
3487 'page_id' => $rev->getPage(),
3488 'rev_id' => $rev_id );
3492 $text = $rev->getText();
3493 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3495 $message = wfMessage( $wgContLang->lcfirst( $title->getText() ) )->inContentLanguage();
3496 if ( !$message->exists() ) {
3500 $text = $message->plain();
3504 if ( $text === false ) {
3508 $finalTitle = $title;
3509 $title = Title
::newFromRedirect( $text );
3513 'finalTitle' => $finalTitle,
3518 * Fetch a file and its title and register a reference to it.
3519 * @param Title $title
3520 * @param string $time MW timestamp
3521 * @param string $sha1 base 36 SHA-1
3522 * @return mixed File or false
3524 function fetchFile( $title, $time = false, $sha1 = false ) {
3525 $res = $this->fetchFileAndTitle( $title, $time, $sha1 );
3530 * Fetch a file and its title and register a reference to it.
3531 * @param Title $title
3532 * @param string $time MW timestamp
3533 * @param string $sha1 base 36 SHA-1
3534 * @return Array ( File or false, Title of file )
3536 function fetchFileAndTitle( $title, $time = false, $sha1 = false ) {
3537 if ( $time === '0' ) {
3538 $file = false; // broken thumbnail forced by hook
3539 } elseif ( $sha1 ) { // get by (sha1,timestamp)
3540 $file = RepoGroup
::singleton()->findFileFromKey( $sha1, array( 'time' => $time ) );
3541 } else { // get by (name,timestamp)
3542 $file = wfFindFile( $title, array( 'time' => $time ) );
3544 $time = $file ?
$file->getTimestamp() : false;
3545 $sha1 = $file ?
$file->getSha1() : false;
3546 # Register the file as a dependency...
3547 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3548 if ( $file && !$title->equals( $file->getTitle() ) ) {
3549 # Update fetched file title
3550 $title = $file->getTitle();
3551 if ( is_null( $file->getRedirectedTitle() ) ) {
3552 # This file was not a redirect, but the title does not match.
3553 # Register under the new name because otherwise the link will
3555 $this->mOutput
->addImage( $title->getDBkey(), $time, $sha1 );
3558 return array( $file, $title );
3562 * Transclude an interwiki link.
3564 * @param $title Title
3569 function interwikiTransclude( $title, $action ) {
3570 global $wgEnableScaryTranscluding;
3572 if ( !$wgEnableScaryTranscluding ) {
3573 return wfMsgForContent('scarytranscludedisabled');
3576 $url = $title->getFullUrl( "action=$action" );
3578 if ( strlen( $url ) > 255 ) {
3579 return wfMsgForContent( 'scarytranscludetoolong' );
3581 return $this->fetchScaryTemplateMaybeFromCache( $url );
3585 * @param $url string
3586 * @return Mixed|String
3588 function fetchScaryTemplateMaybeFromCache( $url ) {
3589 global $wgTranscludeCacheExpiry;
3590 $dbr = wfGetDB( DB_SLAVE
);
3591 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3592 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3593 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3595 return $obj->tc_contents
;
3598 $text = Http
::get( $url );
3600 return wfMsgForContent( 'scarytranscludefailed', $url );
3603 $dbw = wfGetDB( DB_MASTER
);
3604 $dbw->replace( 'transcache', array('tc_url'), array(
3606 'tc_time' => $dbw->timestamp( time() ),
3607 'tc_contents' => $text)
3613 * Triple brace replacement -- used for template arguments
3616 * @param $peice array
3617 * @param $frame PPFrame
3621 function argSubstitution( $piece, $frame ) {
3622 wfProfileIn( __METHOD__
);
3625 $parts = $piece['parts'];
3626 $nameWithSpaces = $frame->expand( $piece['title'] );
3627 $argName = trim( $nameWithSpaces );
3629 $text = $frame->getArgument( $argName );
3630 if ( $text === false && $parts->getLength() > 0
3634 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3637 # No match in frame, use the supplied default
3638 $object = $parts->item( 0 )->getChildren();
3640 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3641 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3642 $this->limitationWarn( 'post-expand-template-argument' );
3645 if ( $text === false && $object === false ) {
3647 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3649 if ( $error !== false ) {
3652 if ( $object !== false ) {
3653 $ret = array( 'object' => $object );
3655 $ret = array( 'text' => $text );
3658 wfProfileOut( __METHOD__
);
3663 * Return the text to be used for a given extension tag.
3664 * This is the ghost of strip().
3666 * @param $params Associative array of parameters:
3667 * name PPNode for the tag name
3668 * attr PPNode for unparsed text where tag attributes are thought to be
3669 * attributes Optional associative array of parsed attributes
3670 * inner Contents of extension element
3671 * noClose Original text did not have a close tag
3672 * @param $frame PPFrame
3676 function extensionSubstitution( $params, $frame ) {
3677 $name = $frame->expand( $params['name'] );
3678 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3679 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3680 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3682 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3683 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3684 if ( $isFunctionTag ) {
3685 $markerType = 'none';
3687 $markerType = 'general';
3689 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3690 $name = strtolower( $name );
3691 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3692 if ( isset( $params['attributes'] ) ) {
3693 $attributes = $attributes +
$params['attributes'];
3696 if ( isset( $this->mTagHooks
[$name] ) ) {
3697 # Workaround for PHP bug 35229 and similar
3698 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3699 throw new MWException( "Tag hook for $name is not callable\n" );
3701 $output = call_user_func_array( $this->mTagHooks
[$name],
3702 array( $content, $attributes, $this, $frame ) );
3703 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3704 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3705 if ( !is_callable( $callback ) ) {
3706 throw new MWException( "Tag hook for $name is not callable\n" );
3709 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3711 $output = '<span class="error">Invalid tag extension name: ' .
3712 htmlspecialchars( $name ) . '</span>';
3715 if ( is_array( $output ) ) {
3716 # Extract flags to local scope (to override $markerType)
3718 $output = $flags[0];
3723 if ( is_null( $attrText ) ) {
3726 if ( isset( $params['attributes'] ) ) {
3727 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3728 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3729 htmlspecialchars( $attrValue ) . '"';
3732 if ( $content === null ) {
3733 $output = "<$name$attrText/>";
3735 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3736 $output = "<$name$attrText>$content$close";
3740 if ( $markerType === 'none' ) {
3742 } elseif ( $markerType === 'nowiki' ) {
3743 $this->mStripState
->addNoWiki( $marker, $output );
3744 } elseif ( $markerType === 'general' ) {
3745 $this->mStripState
->addGeneral( $marker, $output );
3747 throw new MWException( __METHOD__
.': invalid marker type' );
3753 * Increment an include size counter
3755 * @param $type String: the type of expansion
3756 * @param $size Integer: the size of the text
3757 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3759 function incrementIncludeSize( $type, $size ) {
3760 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize() ) {
3763 $this->mIncludeSizes
[$type] +
= $size;
3769 * Increment the expensive function count
3771 * @return Boolean: false if the limit has been exceeded
3773 function incrementExpensiveFunctionCount() {
3774 global $wgExpensiveParserFunctionLimit;
3775 $this->mExpensiveFunctionCount++
;
3776 if ( $this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit ) {
3783 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3784 * Fills $this->mDoubleUnderscores, returns the modified text
3786 function doDoubleUnderscore( $text ) {
3787 wfProfileIn( __METHOD__
);
3789 # The position of __TOC__ needs to be recorded
3790 $mw = MagicWord
::get( 'toc' );
3791 if ( $mw->match( $text ) ) {
3792 $this->mShowToc
= true;
3793 $this->mForceTocPosition
= true;
3795 # Set a placeholder. At the end we'll fill it in with the TOC.
3796 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3798 # Only keep the first one.
3799 $text = $mw->replace( '', $text );
3802 # Now match and remove the rest of them
3803 $mwa = MagicWord
::getDoubleUnderscoreArray();
3804 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3806 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3807 $this->mOutput
->mNoGallery
= true;
3809 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3810 $this->mShowToc
= false;
3812 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3813 $this->addTrackingCategory( 'hidden-category-category' );
3815 # (bug 8068) Allow control over whether robots index a page.
3817 # @todo FIXME: Bug 14899: __INDEX__ always overrides __NOINDEX__ here! This
3818 # is not desirable, the last one on the page should win.
3819 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3820 $this->mOutput
->setIndexPolicy( 'noindex' );
3821 $this->addTrackingCategory( 'noindex-category' );
3823 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3824 $this->mOutput
->setIndexPolicy( 'index' );
3825 $this->addTrackingCategory( 'index-category' );
3828 # Cache all double underscores in the database
3829 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
3830 $this->mOutput
->setProperty( $key, '' );
3833 wfProfileOut( __METHOD__
);
3838 * Add a tracking category, getting the title from a system message,
3839 * or print a debug message if the title is invalid.
3841 * @param $msg String: message key
3842 * @return Boolean: whether the addition was successful
3844 protected function addTrackingCategory( $msg ) {
3845 $cat = wfMsgForContent( $msg );
3847 # Allow tracking categories to be disabled by setting them to "-"
3848 if ( $cat === '-' ) {
3852 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3853 if ( $containerCategory ) {
3854 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3857 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3863 * This function accomplishes several tasks:
3864 * 1) Auto-number headings if that option is enabled
3865 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3866 * 3) Add a Table of contents on the top for users who have enabled the option
3867 * 4) Auto-anchor headings
3869 * It loops through all headlines, collects the necessary data, then splits up the
3870 * string and re-inserts the newly formatted headlines.
3872 * @param $text String
3873 * @param $origText String: original, untouched wikitext
3874 * @param $isMain Boolean
3877 function formatHeadings( $text, $origText, $isMain=true ) {
3878 global $wgMaxTocLevel, $wgHtml5, $wgExperimentalHtmlIds;
3880 # Inhibit editsection links if requested in the page
3881 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3884 $showEditLink = $this->mOptions
->getEditSection();
3886 if ( $showEditLink ) {
3887 $this->mOutput
->setEditSectionTokens( true );
3890 # Get all headlines for numbering them and adding funky stuff like [edit]
3891 # links - this is for later, but we need the number of headlines right now
3893 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3895 # if there are fewer than 4 headlines in the article, do not show TOC
3896 # unless it's been explicitly enabled.
3897 $enoughToc = $this->mShowToc
&&
3898 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
3900 # Allow user to stipulate that a page should have a "new section"
3901 # link added via __NEWSECTIONLINK__
3902 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3903 $this->mOutput
->setNewSection( true );
3906 # Allow user to remove the "new section"
3907 # link via __NONEWSECTIONLINK__
3908 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3909 $this->mOutput
->hideNewSection( true );
3912 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3913 # override above conditions and always show TOC above first header
3914 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3915 $this->mShowToc
= true;
3923 # Ugh .. the TOC should have neat indentation levels which can be
3924 # passed to the skin functions. These are determined here
3928 $sublevelCount = array();
3929 $levelCount = array();
3934 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3935 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3936 $oldType = $this->mOutputType
;
3937 $this->setOutputType( self
::OT_WIKI
);
3938 $frame = $this->getPreprocessor()->newFrame();
3939 $root = $this->preprocessToDom( $origText );
3940 $node = $root->getFirstChild();
3945 foreach ( $matches[3] as $headline ) {
3946 $isTemplate = false;
3948 $sectionIndex = false;
3950 $markerMatches = array();
3951 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
3952 $serial = $markerMatches[1];
3953 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3954 $isTemplate = ( $titleText != $baseTitleText );
3955 $headline = preg_replace( "/^$markerRegex/", "", $headline );
3959 $prevlevel = $level;
3961 $level = $matches[1][$headlineCount];
3963 if ( $level > $prevlevel ) {
3964 # Increase TOC level
3966 $sublevelCount[$toclevel] = 0;
3967 if ( $toclevel<$wgMaxTocLevel ) {
3968 $prevtoclevel = $toclevel;
3969 $toc .= Linker
::tocIndent();
3972 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
3973 # Decrease TOC level, find level to jump to
3975 for ( $i = $toclevel; $i > 0; $i-- ) {
3976 if ( $levelCount[$i] == $level ) {
3977 # Found last matching level
3980 } elseif ( $levelCount[$i] < $level ) {
3981 # Found first matching level below current level
3989 if ( $toclevel<$wgMaxTocLevel ) {
3990 if ( $prevtoclevel < $wgMaxTocLevel ) {
3991 # Unindent only if the previous toc level was shown :p
3992 $toc .= Linker
::tocUnindent( $prevtoclevel - $toclevel );
3993 $prevtoclevel = $toclevel;
3995 $toc .= Linker
::tocLineEnd();
3999 # No change in level, end TOC line
4000 if ( $toclevel<$wgMaxTocLevel ) {
4001 $toc .= Linker
::tocLineEnd();
4005 $levelCount[$toclevel] = $level;
4007 # count number of headlines for each level
4008 @$sublevelCount[$toclevel]++
;
4010 for( $i = 1; $i <= $toclevel; $i++
) {
4011 if ( !empty( $sublevelCount[$i] ) ) {
4015 $numbering .= $this->getFunctionLang()->formatNum( $sublevelCount[$i] );
4020 # The safe header is a version of the header text safe to use for links
4021 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
4022 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
4024 # Remove link placeholders by the link text.
4025 # <!--LINK number-->
4027 # link text with suffix
4028 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
4030 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
4031 $tocline = preg_replace(
4032 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
4033 array( '', '<$1>' ),
4036 $tocline = trim( $tocline );
4038 # For the anchor, strip out HTML-y stuff period
4039 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
4040 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
4042 # Save headline for section edit hint before it's escaped
4043 $headlineHint = $safeHeadline;
4045 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
4046 # For reverse compatibility, provide an id that's
4047 # HTML4-compatible, like we used to.
4049 # It may be worth noting, academically, that it's possible for
4050 # the legacy anchor to conflict with a non-legacy headline
4051 # anchor on the page. In this case likely the "correct" thing
4052 # would be to either drop the legacy anchors or make sure
4053 # they're numbered first. However, this would require people
4054 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
4055 # manually, so let's not bother worrying about it.
4056 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
4057 array( 'noninitial', 'legacy' ) );
4058 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
4060 if ( $legacyHeadline == $safeHeadline ) {
4061 # No reason to have both (in fact, we can't)
4062 $legacyHeadline = false;
4065 $legacyHeadline = false;
4066 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
4070 # HTML names must be case-insensitively unique (bug 10721).
4071 # This does not apply to Unicode characters per
4072 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
4073 # @todo FIXME: We may be changing them depending on the current locale.
4074 $arrayKey = strtolower( $safeHeadline );
4075 if ( $legacyHeadline === false ) {
4076 $legacyArrayKey = false;
4078 $legacyArrayKey = strtolower( $legacyHeadline );
4081 # count how many in assoc. array so we can track dupes in anchors
4082 if ( isset( $refers[$arrayKey] ) ) {
4083 $refers[$arrayKey]++
;
4085 $refers[$arrayKey] = 1;
4087 if ( isset( $refers[$legacyArrayKey] ) ) {
4088 $refers[$legacyArrayKey]++
;
4090 $refers[$legacyArrayKey] = 1;
4093 # Don't number the heading if it is the only one (looks silly)
4094 if ( count( $matches[3] ) > 1 && $this->mOptions
->getNumberHeadings() ) {
4095 # the two are different if the line contains a link
4096 $headline = $numbering . ' ' . $headline;
4099 # Create the anchor for linking from the TOC to the section
4100 $anchor = $safeHeadline;
4101 $legacyAnchor = $legacyHeadline;
4102 if ( $refers[$arrayKey] > 1 ) {
4103 $anchor .= '_' . $refers[$arrayKey];
4105 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
4106 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
4108 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
4109 $toc .= Linker
::tocLine( $anchor, $tocline,
4110 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
4113 # Add the section to the section tree
4114 # Find the DOM node for this header
4115 while ( $node && !$isTemplate ) {
4116 if ( $node->getName() === 'h' ) {
4117 $bits = $node->splitHeading();
4118 if ( $bits['i'] == $sectionIndex ) {
4122 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
4123 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
4124 $node = $node->getNextSibling();
4127 'toclevel' => $toclevel,
4130 'number' => $numbering,
4131 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
4132 'fromtitle' => $titleText,
4133 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
4134 'anchor' => $anchor,
4137 # give headline the correct <h#> tag
4138 if ( $showEditLink && $sectionIndex !== false ) {
4139 // Output edit section links as markers with styles that can be customized by skins
4140 if ( $isTemplate ) {
4141 # Put a T flag in the section identifier, to indicate to extractSections()
4142 # that sections inside <includeonly> should be counted.
4143 $editlinkArgs = array( $titleText, "T-$sectionIndex"/*, null */ );
4145 $editlinkArgs = array( $this->mTitle
->getPrefixedText(), $sectionIndex, $headlineHint );
4147 // We use a bit of pesudo-xml for editsection markers. The language converter is run later on
4148 // Using a UNIQ style marker leads to the converter screwing up the tokens when it converts stuff
4149 // And trying to insert strip tags fails too. At this point all real inputted tags have already been escaped
4150 // so we don't have to worry about a user trying to input one of these markers directly.
4151 // We use a page and section attribute to stop the language converter from converting these important bits
4152 // of data, but put the headline hint inside a content block because the language converter is supposed to
4153 // be able to convert that piece of data.
4154 $editlink = '<mw:editsection page="' . htmlspecialchars($editlinkArgs[0]);
4155 $editlink .= '" section="' . htmlspecialchars($editlinkArgs[1]) .'"';
4156 if ( isset($editlinkArgs[2]) ) {
4157 $editlink .= '>' . $editlinkArgs[2] . '</mw:editsection>';
4164 $head[$headlineCount] = Linker
::makeHeadline( $level,
4165 $matches['attrib'][$headlineCount], $anchor, $headline,
4166 $editlink, $legacyAnchor );
4171 $this->setOutputType( $oldType );
4173 # Never ever show TOC if no headers
4174 if ( $numVisible < 1 ) {
4179 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
4180 $toc .= Linker
::tocUnindent( $prevtoclevel - 1 );
4182 $toc = Linker
::tocList( $toc, $this->mOptions
->getUserLang() );
4183 $this->mOutput
->setTOCHTML( $toc );
4187 $this->mOutput
->setSections( $tocraw );
4190 # split up and insert constructed headlines
4191 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4194 // build an array of document sections
4195 $sections = array();
4196 foreach ( $blocks as $block ) {
4197 // $head is zero-based, sections aren't.
4198 if ( empty( $head[$i - 1] ) ) {
4199 $sections[$i] = $block;
4201 $sections[$i] = $head[$i - 1] . $block;
4205 * Send a hook, one per section.
4206 * The idea here is to be able to make section-level DIVs, but to do so in a
4207 * lower-impact, more correct way than r50769
4210 * $section : the section number
4211 * &$sectionContent : ref to the content of the section
4212 * $showEditLinks : boolean describing whether this section has an edit link
4214 wfRunHooks( 'ParserSectionCreate', array( $this, $i, &$sections[$i], $showEditLink ) );
4219 if ( $enoughToc && $isMain && !$this->mForceTocPosition
) {
4220 // append the TOC at the beginning
4221 // Top anchor now in skin
4222 $sections[0] = $sections[0] . $toc . "\n";
4225 $full .= join( '', $sections );
4227 if ( $this->mForceTocPosition
) {
4228 return str_replace( '<!--MWTOC-->', $toc, $full );
4235 * Transform wiki markup when saving a page by doing \r\n -> \n
4236 * conversion, substitting signatures, {{subst:}} templates, etc.
4238 * @param $text String: the text to transform
4239 * @param $title Title: the Title object for the current article
4240 * @param $user User: the User object describing the current user
4241 * @param $options ParserOptions: parsing options
4242 * @param $clearState Boolean: whether to clear the parser state first
4243 * @return String: the altered wiki markup
4245 public function preSaveTransform( $text, Title
$title, User
$user, ParserOptions
$options, $clearState = true ) {
4246 $this->startParse( $title, $options, self
::OT_WIKI
, $clearState );
4247 $this->setUser( $user );
4252 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4253 if( $options->getPreSaveTransform() ) {
4254 $text = $this->pstPass2( $text, $user );
4256 $text = $this->mStripState
->unstripBoth( $text );
4258 $this->setUser( null ); #Reset
4264 * Pre-save transform helper function
4267 function pstPass2( $text, $user ) {
4268 global $wgContLang, $wgLocaltimezone;
4270 # Note: This is the timestamp saved as hardcoded wikitext to
4271 # the database, we use $wgContLang here in order to give
4272 # everyone the same signature and use the default one rather
4273 # than the one selected in each user's preferences.
4274 # (see also bug 12815)
4275 $ts = $this->mOptions
->getTimestamp();
4276 if ( isset( $wgLocaltimezone ) ) {
4277 $tz = $wgLocaltimezone;
4279 $tz = date_default_timezone_get();
4282 $unixts = wfTimestamp( TS_UNIX
, $ts );
4283 $oldtz = date_default_timezone_get();
4284 date_default_timezone_set( $tz );
4285 $ts = date( 'YmdHis', $unixts );
4286 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4288 # Allow translation of timezones through wiki. date() can return
4289 # whatever crap the system uses, localised or not, so we cannot
4290 # ship premade translations.
4291 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4292 $msg = wfMessage( $key )->inContentLanguage();
4293 if ( $msg->exists() ) {
4294 $tzMsg = $msg->text();
4297 date_default_timezone_set( $oldtz );
4299 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4301 # Variable replacement
4302 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4303 $text = $this->replaceVariables( $text );
4305 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4306 # which may corrupt this parser instance via its wfMsgExt( parsemag ) call-
4309 $sigText = $this->getUserSig( $user );
4310 $text = strtr( $text, array(
4312 '~~~~' => "$sigText $d",
4316 # Context links: [[|name]] and [[name (context)|]]
4317 global $wgLegalTitleChars;
4318 $tc = "[$wgLegalTitleChars]";
4319 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4321 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4322 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
4323 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4324 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4326 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4327 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4328 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4329 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4331 $t = $this->mTitle
->getText();
4333 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4334 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4335 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4336 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4338 # if there's no context, don't bother duplicating the title
4339 $text = preg_replace( $p2, '[[\\1]]', $text );
4342 # Trim trailing whitespace
4343 $text = rtrim( $text );
4349 * Fetch the user's signature text, if any, and normalize to
4350 * validated, ready-to-insert wikitext.
4351 * If you have pre-fetched the nickname or the fancySig option, you can
4352 * specify them here to save a database query.
4353 * Do not reuse this parser instance after calling getUserSig(),
4354 * as it may have changed if it's the $wgParser.
4357 * @param $nickname String: nickname to use or false to use user's default nickname
4358 * @param $fancySig Boolean: whether the nicknname is the complete signature
4359 * or null to use default value
4362 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4363 global $wgMaxSigChars;
4365 $username = $user->getName();
4367 # If not given, retrieve from the user object.
4368 if ( $nickname === false )
4369 $nickname = $user->getOption( 'nickname' );
4371 if ( is_null( $fancySig ) ) {
4372 $fancySig = $user->getBoolOption( 'fancysig' );
4375 $nickname = $nickname == null ?
$username : $nickname;
4377 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4378 $nickname = $username;
4379 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4380 } elseif ( $fancySig !== false ) {
4381 # Sig. might contain markup; validate this
4382 if ( $this->validateSig( $nickname ) !== false ) {
4383 # Validated; clean up (if needed) and return it
4384 return $this->cleanSig( $nickname, true );
4386 # Failed to validate; fall back to the default
4387 $nickname = $username;
4388 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4392 # Make sure nickname doesnt get a sig in a sig
4393 $nickname = $this->cleanSigInSig( $nickname );
4395 # If we're still here, make it a link to the user page
4396 $userText = wfEscapeWikiText( $username );
4397 $nickText = wfEscapeWikiText( $nickname );
4398 $msgName = $user->isAnon() ?
'signature-anon' : 'signature';
4400 return wfMessage( $msgName, $userText, $nickText )->inContentLanguage()->title( $this->getTitle() )->text();
4404 * Check that the user's signature contains no bad XML
4406 * @param $text String
4407 * @return mixed An expanded string, or false if invalid.
4409 function validateSig( $text ) {
4410 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4414 * Clean up signature text
4416 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4417 * 2) Substitute all transclusions
4419 * @param $text String
4420 * @param $parsing Whether we're cleaning (preferences save) or parsing
4421 * @return String: signature text
4423 function cleanSig( $text, $parsing = false ) {
4426 $this->mOptions
= new ParserOptions
;
4427 $this->clearState();
4428 $this->setTitle( $wgTitle );
4429 $this->setOutputType
= self
::OT_PREPROCESS
;
4432 # Option to disable this feature
4433 if ( !$this->mOptions
->getCleanSignatures() ) {
4437 # @todo FIXME: Regex doesn't respect extension tags or nowiki
4438 # => Move this logic to braceSubstitution()
4439 $substWord = MagicWord
::get( 'subst' );
4440 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4441 $substText = '{{' . $substWord->getSynonym( 0 );
4443 $text = preg_replace( $substRegex, $substText, $text );
4444 $text = $this->cleanSigInSig( $text );
4445 $dom = $this->preprocessToDom( $text );
4446 $frame = $this->getPreprocessor()->newFrame();
4447 $text = $frame->expand( $dom );
4450 $text = $this->mStripState
->unstripBoth( $text );
4457 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4459 * @param $text String
4460 * @return String: signature text with /~{3,5}/ removed
4462 function cleanSigInSig( $text ) {
4463 $text = preg_replace( '/~{3,5}/', '', $text );
4468 * Set up some variables which are usually set up in parse()
4469 * so that an external function can call some class members with confidence
4471 public function startExternalParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4472 $this->startParse( $title, $options, $outputType, $clearState );
4475 private function startParse( Title
$title = null, ParserOptions
$options, $outputType, $clearState = true ) {
4476 $this->setTitle( $title );
4477 $this->mOptions
= $options;
4478 $this->setOutputType( $outputType );
4479 if ( $clearState ) {
4480 $this->clearState();
4485 * Wrapper for preprocess()
4487 * @param $text String: the text to preprocess
4488 * @param $options ParserOptions: options
4489 * @param $title Title object or null to use $wgTitle
4492 public function transformMsg( $text, $options, $title = null ) {
4493 static $executing = false;
4495 # Guard against infinite recursion
4501 wfProfileIn( __METHOD__
);
4507 # It's not uncommon having a null $wgTitle in scripts. See r80898
4508 # Create a ghost title in such case
4509 $title = Title
::newFromText( 'Dwimmerlaik' );
4511 $text = $this->preprocess( $text, $title, $options );
4514 wfProfileOut( __METHOD__
);
4519 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4520 * The callback should have the following form:
4521 * function myParserHook( $text, $params, $parser, $frame ) { ... }
4523 * Transform and return $text. Use $parser for any required context, e.g. use
4524 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4526 * Hooks may return extended information by returning an array, of which the
4527 * first numbered element (index 0) must be the return string, and all other
4528 * entries are extracted into local variables within an internal function
4529 * in the Parser class.
4531 * This interface (introduced r61913) appears to be undocumented, but
4532 * 'markerName' is used by some core tag hooks to override which strip
4533 * array their results are placed in. **Use great caution if attempting
4534 * this interface, as it is not documented and injudicious use could smash
4535 * private variables.**
4537 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4538 * @param $callback Mixed: the callback function (and object) to use for the tag
4539 * @return The old value of the mTagHooks array associated with the hook
4541 public function setHook( $tag, $callback ) {
4542 $tag = strtolower( $tag );
4543 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setHook('$tag', ...) call" );
4544 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4545 $this->mTagHooks
[$tag] = $callback;
4546 if ( !in_array( $tag, $this->mStripList
) ) {
4547 $this->mStripList
[] = $tag;
4554 * As setHook(), but letting the contents be parsed.
4556 * Transparent tag hooks are like regular XML-style tag hooks, except they
4557 * operate late in the transformation sequence, on HTML instead of wikitext.
4559 * This is probably obsoleted by things dealing with parser frames?
4560 * The only extension currently using it is geoserver.
4563 * @todo better document or deprecate this
4565 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4566 * @param $callback Mixed: the callback function (and object) to use for the tag
4567 * @return The old value of the mTagHooks array associated with the hook
4569 function setTransparentTagHook( $tag, $callback ) {
4570 $tag = strtolower( $tag );
4571 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setTransparentHook('$tag', ...) call" );
4572 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4573 $this->mTransparentTagHooks
[$tag] = $callback;
4579 * Remove all tag hooks
4581 function clearTagHooks() {
4582 $this->mTagHooks
= array();
4583 $this->mStripList
= $this->mDefaultStripList
;
4587 * Remove a specific tag hook. Should not be called on $wgParser.
4588 * Does not change the strip list.
4590 * @param string $tag
4593 function clearTagHook( $tag ) {
4594 if ( isset( $this->mTagHooks
[$tag] ) ) {
4595 unset( $this->mTagHooks
[$tag] );
4600 * Create a function, e.g. {{sum:1|2|3}}
4601 * The callback function should have the form:
4602 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4604 * Or with SFH_OBJECT_ARGS:
4605 * function myParserFunction( $parser, $frame, $args ) { ... }
4607 * The callback may either return the text result of the function, or an array with the text
4608 * in element 0, and a number of flags in the other elements. The names of the flags are
4609 * specified in the keys. Valid flags are:
4610 * found The text returned is valid, stop processing the template. This
4612 * nowiki Wiki markup in the return value should be escaped
4613 * isHTML The returned text is HTML, armour it against wikitext transformation
4615 * @param $id String: The magic word ID
4616 * @param $callback Mixed: the callback function (and object) to use
4617 * @param $flags Integer: a combination of the following flags:
4618 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4620 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4621 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4622 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4623 * the arguments, and to control the way they are expanded.
4625 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4626 * arguments, for instance:
4627 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4629 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4630 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4631 * working if/when this is changed.
4633 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4636 * Please read the documentation in includes/parser/Preprocessor.php for more information
4637 * about the methods available in PPFrame and PPNode.
4639 * @return The old callback function for this name, if any
4641 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4644 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4645 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4647 # Add to function cache
4648 $mw = MagicWord
::get( $id );
4650 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4652 $synonyms = $mw->getSynonyms();
4653 $sensitive = intval( $mw->isCaseSensitive() );
4655 foreach ( $synonyms as $syn ) {
4657 if ( !$sensitive ) {
4658 $syn = $wgContLang->lc( $syn );
4661 if ( !( $flags & SFH_NO_HASH
) ) {
4664 # Remove trailing colon
4665 if ( substr( $syn, -1, 1 ) === ':' ) {
4666 $syn = substr( $syn, 0, -1 );
4668 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4674 * Get all registered function hook identifiers
4678 function getFunctionHooks() {
4679 return array_keys( $this->mFunctionHooks
);
4683 * Create a tag function, e.g. <test>some stuff</test>.
4684 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4685 * Unlike parser functions, their content is not preprocessed.
4687 function setFunctionTagHook( $tag, $callback, $flags ) {
4688 $tag = strtolower( $tag );
4689 if ( preg_match( '/[<>\r\n]/', $tag, $m ) ) throw new MWException( "Invalid character {$m[0]} in setFunctionTagHook('$tag', ...) call" );
4690 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4691 $this->mFunctionTagHooks
[$tag] : null;
4692 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4694 if ( !in_array( $tag, $this->mStripList
) ) {
4695 $this->mStripList
[] = $tag;
4702 * @todo FIXME: Update documentation. makeLinkObj() is deprecated.
4703 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4704 * Placeholders created in Skin::makeLinkObj()
4705 * Returns an array of link CSS classes, indexed by PDBK.
4707 function replaceLinkHolders( &$text, $options = 0 ) {
4708 return $this->mLinkHolders
->replace( $text );
4712 * Replace <!--LINK--> link placeholders with plain text of links
4713 * (not HTML-formatted).
4715 * @param $text String
4718 function replaceLinkHoldersText( $text ) {
4719 return $this->mLinkHolders
->replaceText( $text );
4723 * Renders an image gallery from a text with one line per image.
4724 * text labels may be given by using |-style alternative text. E.g.
4725 * Image:one.jpg|The number "1"
4726 * Image:tree.jpg|A tree
4727 * given as text will return the HTML of a gallery with two images,
4728 * labeled 'The number "1"' and
4731 * @param string $text
4732 * @param array $param
4733 * @return string HTML
4735 function renderImageGallery( $text, $params ) {
4736 $ig = new ImageGallery();
4737 $ig->setContextTitle( $this->mTitle
);
4738 $ig->setShowBytes( false );
4739 $ig->setShowFilename( false );
4740 $ig->setParser( $this );
4741 $ig->setHideBadImages();
4742 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4744 if ( isset( $params['showfilename'] ) ) {
4745 $ig->setShowFilename( true );
4747 $ig->setShowFilename( false );
4749 if ( isset( $params['caption'] ) ) {
4750 $caption = $params['caption'];
4751 $caption = htmlspecialchars( $caption );
4752 $caption = $this->replaceInternalLinks( $caption );
4753 $ig->setCaptionHtml( $caption );
4755 if ( isset( $params['perrow'] ) ) {
4756 $ig->setPerRow( $params['perrow'] );
4758 if ( isset( $params['widths'] ) ) {
4759 $ig->setWidths( $params['widths'] );
4761 if ( isset( $params['heights'] ) ) {
4762 $ig->setHeights( $params['heights'] );
4765 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4767 $lines = StringUtils
::explode( "\n", $text );
4768 foreach ( $lines as $line ) {
4769 # match lines like these:
4770 # Image:someimage.jpg|This is some image
4772 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4774 if ( count( $matches ) == 0 ) {
4778 if ( strpos( $matches[0], '%' ) !== false ) {
4779 $matches[1] = rawurldecode( $matches[1] );
4781 $title = Title
::newFromText( $matches[1], NS_FILE
);
4782 if ( is_null( $title ) ) {
4783 # Bogus title. Ignore these so we don't bomb out later.
4789 if ( isset( $matches[3] ) ) {
4790 // look for an |alt= definition while trying not to break existing
4791 // captions with multiple pipes (|) in it, until a more sensible grammar
4792 // is defined for images in galleries
4794 $matches[3] = $this->recursiveTagParse( trim( $matches[3] ) );
4795 $altmatches = StringUtils
::explode('|', $matches[3]);
4796 $magicWordAlt = MagicWord
::get( 'img_alt' );
4798 foreach ( $altmatches as $altmatch ) {
4799 $match = $magicWordAlt->matchVariableStartToEnd( $altmatch );
4801 $alt = $this->stripAltText( $match, false );
4804 // concatenate all other pipes
4805 $label .= '|' . $altmatch;
4808 // remove the first pipe
4809 $label = substr( $label, 1 );
4812 $ig->add( $title, $label, $alt );
4814 return $ig->toHTML();
4817 function getImageParams( $handler ) {
4819 $handlerClass = get_class( $handler );
4823 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4824 # Initialise static lists
4825 static $internalParamNames = array(
4826 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4827 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4828 'bottom', 'text-bottom' ),
4829 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4830 'upright', 'border', 'link', 'alt' ),
4832 static $internalParamMap;
4833 if ( !$internalParamMap ) {
4834 $internalParamMap = array();
4835 foreach ( $internalParamNames as $type => $names ) {
4836 foreach ( $names as $name ) {
4837 $magicName = str_replace( '-', '_', "img_$name" );
4838 $internalParamMap[$magicName] = array( $type, $name );
4843 # Add handler params
4844 $paramMap = $internalParamMap;
4846 $handlerParamMap = $handler->getParamMap();
4847 foreach ( $handlerParamMap as $magic => $paramName ) {
4848 $paramMap[$magic] = array( 'handler', $paramName );
4851 $this->mImageParams
[$handlerClass] = $paramMap;
4852 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4854 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4858 * Parse image options text and use it to make an image
4860 * @param $title Title
4861 * @param $options String
4862 * @param $holders LinkHolderArray
4863 * @return string HTML
4865 function makeImage( $title, $options, $holders = false ) {
4866 # Check if the options text is of the form "options|alt text"
4868 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4869 # * left no resizing, just left align. label is used for alt= only
4870 # * right same, but right aligned
4871 # * none same, but not aligned
4872 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4873 # * center center the image
4874 # * frame Keep original image size, no magnify-button.
4875 # * framed Same as "frame"
4876 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4877 # * upright reduce width for upright images, rounded to full __0 px
4878 # * border draw a 1px border around the image
4879 # * alt Text for HTML alt attribute (defaults to empty)
4880 # * link Set the target of the image link. Can be external, interwiki, or local
4881 # vertical-align values (no % or length right now):
4891 $parts = StringUtils
::explode( "|", $options );
4893 # Give extensions a chance to select the file revision for us
4894 $time = $sha1 = $descQuery = false;
4895 wfRunHooks( 'BeforeParserFetchFileAndTitle',
4896 array( $this, $title, &$time, &$sha1, &$descQuery ) );
4897 # Fetch and register the file (file title may be different via hooks)
4898 list( $file, $title ) = $this->fetchFileAndTitle( $title, $time, $sha1 );
4901 $handler = $file ?
$file->getHandler() : false;
4903 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4906 $this->addTrackingCategory( 'broken-file-category' );
4909 # Process the input parameters
4911 $params = array( 'frame' => array(), 'handler' => array(),
4912 'horizAlign' => array(), 'vertAlign' => array() );
4913 foreach ( $parts as $part ) {
4914 $part = trim( $part );
4915 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4917 if ( isset( $paramMap[$magicName] ) ) {
4918 list( $type, $paramName ) = $paramMap[$magicName];
4920 # Special case; width and height come in one variable together
4921 if ( $type === 'handler' && $paramName === 'width' ) {
4923 # (bug 13500) In both cases (width/height and width only),
4924 # permit trailing "px" for backward compatibility.
4925 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4926 $width = intval( $m[1] );
4927 $height = intval( $m[2] );
4928 if ( $handler->validateParam( 'width', $width ) ) {
4929 $params[$type]['width'] = $width;
4932 if ( $handler->validateParam( 'height', $height ) ) {
4933 $params[$type]['height'] = $height;
4936 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4937 $width = intval( $value );
4938 if ( $handler->validateParam( 'width', $width ) ) {
4939 $params[$type]['width'] = $width;
4942 } # else no validation -- bug 13436
4944 if ( $type === 'handler' ) {
4945 # Validate handler parameter
4946 $validated = $handler->validateParam( $paramName, $value );
4948 # Validate internal parameters
4949 switch( $paramName ) {
4952 # @todo FIXME: Possibly check validity here for
4953 # manualthumb? downstream behavior seems odd with
4954 # missing manual thumbs.
4956 $value = $this->stripAltText( $value, $holders );
4959 $chars = self
::EXT_LINK_URL_CLASS
;
4960 $prots = $this->mUrlProtocols
;
4961 if ( $value === '' ) {
4962 $paramName = 'no-link';
4965 } elseif ( preg_match( "/^$prots/", $value ) ) {
4966 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4967 $paramName = 'link-url';
4968 $this->mOutput
->addExternalLink( $value );
4969 if ( $this->mOptions
->getExternalLinkTarget() ) {
4970 $params[$type]['link-target'] = $this->mOptions
->getExternalLinkTarget();
4975 $linkTitle = Title
::newFromText( $value );
4977 $paramName = 'link-title';
4978 $value = $linkTitle;
4979 $this->mOutput
->addLink( $linkTitle );
4985 # Most other things appear to be empty or numeric...
4986 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4991 $params[$type][$paramName] = $value;
4995 if ( !$validated ) {
5000 # Process alignment parameters
5001 if ( $params['horizAlign'] ) {
5002 $params['frame']['align'] = key( $params['horizAlign'] );
5004 if ( $params['vertAlign'] ) {
5005 $params['frame']['valign'] = key( $params['vertAlign'] );
5008 $params['frame']['caption'] = $caption;
5010 # Will the image be presented in a frame, with the caption below?
5011 $imageIsFramed = isset( $params['frame']['frame'] ) ||
5012 isset( $params['frame']['framed'] ) ||
5013 isset( $params['frame']['thumbnail'] ) ||
5014 isset( $params['frame']['manualthumb'] );
5016 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
5017 # came to also set the caption, ordinary text after the image -- which
5018 # makes no sense, because that just repeats the text multiple times in
5019 # screen readers. It *also* came to set the title attribute.
5021 # Now that we have an alt attribute, we should not set the alt text to
5022 # equal the caption: that's worse than useless, it just repeats the
5023 # text. This is the framed/thumbnail case. If there's no caption, we
5024 # use the unnamed parameter for alt text as well, just for the time be-
5025 # ing, if the unnamed param is set and the alt param is not.
5027 # For the future, we need to figure out if we want to tweak this more,
5028 # e.g., introducing a title= parameter for the title; ignoring the un-
5029 # named parameter entirely for images without a caption; adding an ex-
5030 # plicit caption= parameter and preserving the old magic unnamed para-
5032 if ( $imageIsFramed ) { # Framed image
5033 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
5034 # No caption or alt text, add the filename as the alt text so
5035 # that screen readers at least get some description of the image
5036 $params['frame']['alt'] = $title->getText();
5038 # Do not set $params['frame']['title'] because tooltips don't make sense
5040 } else { # Inline image
5041 if ( !isset( $params['frame']['alt'] ) ) {
5042 # No alt text, use the "caption" for the alt text
5043 if ( $caption !== '') {
5044 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
5046 # No caption, fall back to using the filename for the
5048 $params['frame']['alt'] = $title->getText();
5051 # Use the "caption" for the tooltip text
5052 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
5055 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
5057 # Linker does the rest
5058 $ret = Linker
::makeImageLink2( $title, $file, $params['frame'], $params['handler'],
5059 $time, $descQuery, $this->mOptions
->getThumbSize() );
5061 # Give the handler a chance to modify the parser object
5063 $handler->parserTransformHook( $this, $file );
5071 * @param $holders LinkHolderArray
5072 * @return mixed|String
5074 protected function stripAltText( $caption, $holders ) {
5075 # Strip bad stuff out of the title (tooltip). We can't just use
5076 # replaceLinkHoldersText() here, because if this function is called
5077 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
5079 $tooltip = $holders->replaceText( $caption );
5081 $tooltip = $this->replaceLinkHoldersText( $caption );
5084 # make sure there are no placeholders in thumbnail attributes
5085 # that are later expanded to html- so expand them now and
5087 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
5088 $tooltip = Sanitizer
::stripAllTags( $tooltip );
5094 * Set a flag in the output object indicating that the content is dynamic and
5095 * shouldn't be cached.
5097 function disableCache() {
5098 wfDebug( "Parser output marked as uncacheable.\n" );
5099 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
5100 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
5104 * Callback from the Sanitizer for expanding items found in HTML attribute
5105 * values, so they can be safely tested and escaped.
5107 * @param $text String
5108 * @param $frame PPFrame
5111 function attributeStripCallback( &$text, $frame = false ) {
5112 $text = $this->replaceVariables( $text, $frame );
5113 $text = $this->mStripState
->unstripBoth( $text );
5122 function getTags() {
5123 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) );
5127 * Replace transparent tags in $text with the values given by the callbacks.
5129 * Transparent tag hooks are like regular XML-style tag hooks, except they
5130 * operate late in the transformation sequence, on HTML instead of wikitext.
5132 * @param $text string
5136 function replaceTransparentTags( $text ) {
5138 $elements = array_keys( $this->mTransparentTagHooks
);
5139 $text = self
::extractTagsAndParams( $elements, $text, $matches, $this->mUniqPrefix
);
5140 $replacements = array();
5142 foreach ( $matches as $marker => $data ) {
5143 list( $element, $content, $params, $tag ) = $data;
5144 $tagName = strtolower( $element );
5145 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
5146 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
5150 $replacements[$marker] = $output;
5152 return strtr( $text, $replacements );
5156 * Break wikitext input into sections, and either pull or replace
5157 * some particular section's text.
5159 * External callers should use the getSection and replaceSection methods.
5161 * @param $text String: Page wikitext
5162 * @param $section String: a section identifier string of the form:
5163 * <flag1> - <flag2> - ... - <section number>
5165 * Currently the only recognised flag is "T", which means the target section number
5166 * was derived during a template inclusion parse, in other words this is a template
5167 * section edit link. If no flags are given, it was an ordinary section edit link.
5168 * This flag is required to avoid a section numbering mismatch when a section is
5169 * enclosed by <includeonly> (bug 6563).
5171 * The section number 0 pulls the text before the first heading; other numbers will
5172 * pull the given section along with its lower-level subsections. If the section is
5173 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
5175 * @param $mode String: one of "get" or "replace"
5176 * @param $newText String: replacement text for section data.
5177 * @return String: for "get", the extracted section text.
5178 * for "replace", the whole page with the section replaced.
5179 * If the page is empty and section 0 is requested, $text (as '')
5182 private function extractSections( $text, $section, $mode, $newText='' ) {
5183 global $wgTitle; # not generally used but removes an ugly failure mode
5184 $this->startParse( $wgTitle, new ParserOptions
, self
::OT_PLAIN
, true );
5186 $frame = $this->getPreprocessor()->newFrame();
5188 # Process section extraction flags
5190 $sectionParts = explode( '-', $section );
5191 $sectionIndex = array_pop( $sectionParts );
5192 foreach ( $sectionParts as $part ) {
5193 if ( $part === 'T' ) {
5194 $flags |
= self
::PTD_FOR_INCLUSION
;
5197 # Preprocess the text
5198 $root = $this->preprocessToDom( $text, $flags );
5200 # <h> nodes indicate section breaks
5201 # They can only occur at the top level, so we can find them by iterating the root's children
5202 $node = $root->getFirstChild();
5204 # Find the target section
5205 if ( $sectionIndex == 0 ) {
5206 # Section zero doesn't nest, level=big
5207 $targetLevel = 1000;
5209 # The page definitely exists - we checked that earlier - so it must be blank: see bug #14005
5214 if ( $node->getName() === 'h' ) {
5215 $bits = $node->splitHeading();
5216 if ( $bits['i'] == $sectionIndex ) {
5217 $targetLevel = $bits['level'];
5221 if ( $mode === 'replace' ) {
5222 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5224 $node = $node->getNextSibling();
5230 if ( $mode === 'get' ) {
5237 # Find the end of the section, including nested sections
5239 if ( $node->getName() === 'h' ) {
5240 $bits = $node->splitHeading();
5241 $curLevel = $bits['level'];
5242 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5246 if ( $mode === 'get' ) {
5247 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5249 $node = $node->getNextSibling();
5252 # Write out the remainder (in replace mode only)
5253 if ( $mode === 'replace' ) {
5254 # Output the replacement text
5255 # Add two newlines on -- trailing whitespace in $newText is conventionally
5256 # stripped by the editor, so we need both newlines to restore the paragraph gap
5257 # Only add trailing whitespace if there is newText
5258 if ( $newText != "" ) {
5259 $outText .= $newText . "\n\n";
5263 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5264 $node = $node->getNextSibling();
5268 if ( is_string( $outText ) ) {
5269 # Re-insert stripped tags
5270 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5277 * This function returns the text of a section, specified by a number ($section).
5278 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5279 * the first section before any such heading (section 0).
5281 * If a section contains subsections, these are also returned.
5283 * @param $text String: text to look in
5284 * @param $section String: section identifier
5285 * @param $deftext String: default to return if section is not found
5286 * @return string text of the requested section
5288 public function getSection( $text, $section, $deftext='' ) {
5289 return $this->extractSections( $text, $section, "get", $deftext );
5293 * This function returns $oldtext after the content of the section
5294 * specified by $section has been replaced with $text.
5296 * @param $oldtext String: former text of the article
5297 * @param $section Numeric: section identifier
5298 * @param $text String: replacing text
5299 * @return String: modified text
5301 public function replaceSection( $oldtext, $section, $text ) {
5302 return $this->extractSections( $oldtext, $section, "replace", $text );
5306 * Get the ID of the revision we are parsing
5308 * @return Mixed: integer or null
5310 function getRevisionId() {
5311 return $this->mRevisionId
;
5315 * Get the revision object for $this->mRevisionId
5317 * @return Revision|null either a Revision object or null
5319 protected function getRevisionObject() {
5320 if ( !is_null( $this->mRevisionObject
) ) {
5321 return $this->mRevisionObject
;
5323 if ( is_null( $this->mRevisionId
) ) {
5327 $this->mRevisionObject
= Revision
::newFromId( $this->mRevisionId
);
5328 return $this->mRevisionObject
;
5332 * Get the timestamp associated with the current revision, adjusted for
5333 * the default server-local timestamp
5335 function getRevisionTimestamp() {
5336 if ( is_null( $this->mRevisionTimestamp
) ) {
5337 wfProfileIn( __METHOD__
);
5339 $revObject = $this->getRevisionObject();
5340 $timestamp = $revObject ?
$revObject->getTimestamp() : false;
5342 if( $timestamp !== false ) {
5345 # The cryptic '' timezone parameter tells to use the site-default
5346 # timezone offset instead of the user settings.
5348 # Since this value will be saved into the parser cache, served
5349 # to other users, and potentially even used inside links and such,
5350 # it needs to be consistent for all visitors.
5351 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5354 wfProfileOut( __METHOD__
);
5356 return $this->mRevisionTimestamp
;
5360 * Get the name of the user that edited the last revision
5362 * @return String: user name
5364 function getRevisionUser() {
5365 if( is_null( $this->mRevisionUser
) ) {
5366 $revObject = $this->getRevisionObject();
5368 # if this template is subst: the revision id will be blank,
5369 # so just use the current user's name
5371 $this->mRevisionUser
= $revObject->getUserText();
5372 } elseif( $this->ot
['wiki'] ||
$this->mOptions
->getIsPreview() ) {
5373 $this->mRevisionUser
= $this->getUser()->getName();
5376 return $this->mRevisionUser
;
5380 * Mutator for $mDefaultSort
5382 * @param $sort New value
5384 public function setDefaultSort( $sort ) {
5385 $this->mDefaultSort
= $sort;
5386 $this->mOutput
->setProperty( 'defaultsort', $sort );
5390 * Accessor for $mDefaultSort
5391 * Will use the empty string if none is set.
5393 * This value is treated as a prefix, so the
5394 * empty string is equivalent to sorting by
5399 public function getDefaultSort() {
5400 if ( $this->mDefaultSort
!== false ) {
5401 return $this->mDefaultSort
;
5408 * Accessor for $mDefaultSort
5409 * Unlike getDefaultSort(), will return false if none is set
5411 * @return string or false
5413 public function getCustomDefaultSort() {
5414 return $this->mDefaultSort
;
5418 * Try to guess the section anchor name based on a wikitext fragment
5419 * presumably extracted from a heading, for example "Header" from
5422 * @param $text string
5426 public function guessSectionNameFromWikiText( $text ) {
5427 # Strip out wikitext links(they break the anchor)
5428 $text = $this->stripSectionName( $text );
5429 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5430 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5434 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5435 * instead. For use in redirects, since IE6 interprets Redirect: headers
5436 * as something other than UTF-8 (apparently?), resulting in breakage.
5438 * @param $text String: The section name
5439 * @return string An anchor
5441 public function guessLegacySectionNameFromWikiText( $text ) {
5442 # Strip out wikitext links(they break the anchor)
5443 $text = $this->stripSectionName( $text );
5444 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5445 return '#' . Sanitizer
::escapeId( $text, array( 'noninitial', 'legacy' ) );
5449 * Strips a text string of wikitext for use in a section anchor
5451 * Accepts a text string and then removes all wikitext from the
5452 * string and leaves only the resultant text (i.e. the result of
5453 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5454 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5455 * to create valid section anchors by mimicing the output of the
5456 * parser when headings are parsed.
5458 * @param $text String: text string to be stripped of wikitext
5459 * for use in a Section anchor
5460 * @return Filtered text string
5462 public function stripSectionName( $text ) {
5463 # Strip internal link markup
5464 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5465 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5467 # Strip external link markup
5468 # @todo FIXME: Not tolerant to blank link text
5469 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5470 # on how many empty links there are on the page - need to figure that out.
5471 $text = preg_replace( '/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5473 # Parse wikitext quotes (italics & bold)
5474 $text = $this->doQuotes( $text );
5477 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5482 * strip/replaceVariables/unstrip for preprocessor regression testing
5486 function testSrvus( $text, Title
$title, ParserOptions
$options, $outputType = self
::OT_HTML
) {
5487 $this->startParse( $title, $options, $outputType, true );
5489 $text = $this->replaceVariables( $text );
5490 $text = $this->mStripState
->unstripBoth( $text );
5491 $text = Sanitizer
::removeHTMLtags( $text );
5495 function testPst( $text, Title
$title, ParserOptions
$options ) {
5496 return $this->preSaveTransform( $text, $title, $options->getUser(), $options );
5499 function testPreprocess( $text, Title
$title, ParserOptions
$options ) {
5500 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5504 * Call a callback function on all regions of the given text that are not
5505 * inside strip markers, and replace those regions with the return value
5506 * of the callback. For example, with input:
5510 * This will call the callback function twice, with 'aaa' and 'bbb'. Those
5511 * two strings will be replaced with the value returned by the callback in
5516 function markerSkipCallback( $s, $callback ) {
5519 while ( $i < strlen( $s ) ) {
5520 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5521 if ( $markerStart === false ) {
5522 $out .= call_user_func( $callback, substr( $s, $i ) );
5525 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5526 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5527 if ( $markerEnd === false ) {
5528 $out .= substr( $s, $markerStart );
5531 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5532 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5541 * Save the parser state required to convert the given half-parsed text to
5542 * HTML. "Half-parsed" in this context means the output of
5543 * recursiveTagParse() or internalParse(). This output has strip markers
5544 * from replaceVariables (extensionSubstitution() etc.), and link
5545 * placeholders from replaceLinkHolders().
5547 * Returns an array which can be serialized and stored persistently. This
5548 * array can later be loaded into another parser instance with
5549 * unserializeHalfParsedText(). The text can then be safely incorporated into
5550 * the return value of a parser hook.
5554 function serializeHalfParsedText( $text ) {
5555 wfProfileIn( __METHOD__
);
5558 'version' => self
::HALF_PARSED_VERSION
,
5559 'stripState' => $this->mStripState
->getSubState( $text ),
5560 'linkHolders' => $this->mLinkHolders
->getSubArray( $text )
5562 wfProfileOut( __METHOD__
);
5567 * Load the parser state given in the $data array, which is assumed to
5568 * have been generated by serializeHalfParsedText(). The text contents is
5569 * extracted from the array, and its markers are transformed into markers
5570 * appropriate for the current Parser instance. This transformed text is
5571 * returned, and can be safely included in the return value of a parser
5574 * If the $data array has been stored persistently, the caller should first
5575 * check whether it is still valid, by calling isValidHalfParsedText().
5577 * @param $data Serialized data
5580 function unserializeHalfParsedText( $data ) {
5581 if ( !isset( $data['version'] ) ||
$data['version'] != self
::HALF_PARSED_VERSION
) {
5582 throw new MWException( __METHOD__
.': invalid version' );
5585 # First, extract the strip state.
5586 $texts = array( $data['text'] );
5587 $texts = $this->mStripState
->merge( $data['stripState'], $texts );
5589 # Now renumber links
5590 $texts = $this->mLinkHolders
->mergeForeign( $data['linkHolders'], $texts );
5592 # Should be good to go.
5597 * Returns true if the given array, presumed to be generated by
5598 * serializeHalfParsedText(), is compatible with the current version of the
5601 * @param $data Array
5605 function isValidHalfParsedText( $data ) {
5606 return isset( $data['version'] ) && $data['version'] == self
::HALF_PARSED_VERSION
;