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 six main entry points into the Parser class:
20 * produces HTML output
22 * produces altered wiki markup.
24 * removes HTML comments and expands templates
26 * Cleans a signature before saving it to preferences
28 * Extracts sections from an article for section editing
29 * getTransclusionText()
30 * Extracts the text of a template with only <includeonly>, etc., parsed
33 * objects: $wgLang, $wgContLang
35 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
38 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
39 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
40 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
43 * * only within ParserOptions
51 * Update this version number when the ParserOutput format
52 * changes in an incompatible way, so the parser cache
53 * can automatically discard old data.
55 const VERSION
= '1.6.4';
57 # Flags for Parser::setFunctionHook
58 # Also available as global constants from Defines.php
59 const SFH_NO_HASH
= 1;
60 const SFH_OBJECT_ARGS
= 2;
62 # Constants needed for external link processing
63 # Everything except bracket, space, or control characters
64 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F]';
65 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
66 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
68 // State constants for the definition list colon extraction
69 const COLON_STATE_TEXT
= 0;
70 const COLON_STATE_TAG
= 1;
71 const COLON_STATE_TAGSTART
= 2;
72 const COLON_STATE_CLOSETAG
= 3;
73 const COLON_STATE_TAGSLASH
= 4;
74 const COLON_STATE_COMMENT
= 5;
75 const COLON_STATE_COMMENTDASH
= 6;
76 const COLON_STATE_COMMENTDASHDASH
= 7;
78 // Flags for preprocessToDom
79 const PTD_FOR_INCLUSION
= 1;
81 // Allowed values for $this->mOutputType
82 // Parameter to startExternalParse().
85 const OT_PREPROCESS
= 3;
87 const OT_INCLUDES
= 4;
89 // Marker Suffix needs to be accessible staticly.
90 const MARKER_SUFFIX
= "-QINU\x7f";
96 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables,
97 $mSubsts, $mImageParams, $mImageParamsMagicArray, $mStripList, $mMarkerIndex,
98 $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols, $mDefaultStripList,
99 $mVarCache, $mConf, $mFunctionTagHooks;
102 # Cleared with clearState():
103 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
104 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
105 var $mLinkHolders, $mLinkID;
106 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
107 var $mTplExpandCache; // empty-frame expansion cache
108 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
109 var $mExpensiveFunctionCount; // number of expensive parser function calls
112 # These are variables reset at least once per parse regardless of $clearState
113 var $mOptions, // ParserOptions object
114 $mTitle, // Title context, used for self-link rendering and similar things
115 $mOutputType, // Output type, one of the OT_xxx constants
116 $ot, // Shortcut alias, see setOutputType()
117 $mRevisionId, // ID to display in {{REVISIONID}} tags
118 $mRevisionTimestamp, // The timestamp of the specified revision ID
119 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
128 function __construct( $conf = array() ) {
129 $this->mConf
= $conf;
130 $this->mTagHooks
= array();
131 $this->mTransparentTagHooks
= array();
132 $this->mFunctionHooks
= array();
133 $this->mFunctionTagHooks
= array();
134 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
135 $this->mDefaultStripList
= $this->mStripList
= array();
136 $this->mUrlProtocols
= wfUrlProtocols();
137 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
138 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
139 $this->mVarCache
= array();
140 if ( isset( $conf['preprocessorClass'] ) ) {
141 $this->mPreprocessorClass
= $conf['preprocessorClass'];
142 } elseif ( extension_loaded( 'domxml' ) ) {
143 // PECL extension that conflicts with the core DOM extension (bug 13770)
144 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
145 $this->mPreprocessorClass
= 'Preprocessor_Hash';
146 } elseif ( extension_loaded( 'dom' ) ) {
147 $this->mPreprocessorClass
= 'Preprocessor_DOM';
149 $this->mPreprocessorClass
= 'Preprocessor_Hash';
151 $this->mMarkerIndex
= 0;
152 $this->mFirstCall
= true;
156 * Reduce memory usage to reduce the impact of circular references
158 function __destruct() {
159 if ( isset( $this->mLinkHolders
) ) {
160 $this->mLinkHolders
->__destruct();
162 foreach ( $this as $name => $value ) {
163 unset( $this->$name );
168 * Do various kinds of initialisation on the first call of the parser
170 function firstCallInit() {
171 if ( !$this->mFirstCall
) {
174 $this->mFirstCall
= false;
176 wfProfileIn( __METHOD__
);
178 CoreParserFunctions
::register( $this );
179 CoreTagHooks
::register( $this );
180 $this->initialiseVariables();
182 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
183 wfProfileOut( __METHOD__
);
191 function clearState() {
192 wfProfileIn( __METHOD__
);
193 if ( $this->mFirstCall
) {
194 $this->firstCallInit();
196 $this->mOutput
= new ParserOutput
;
197 $this->mAutonumber
= 0;
198 $this->mLastSection
= '';
199 $this->mDTopen
= false;
200 $this->mIncludeCount
= array();
201 $this->mStripState
= new StripState
;
202 $this->mArgStack
= false;
203 $this->mInPre
= false;
204 $this->mLinkHolders
= new LinkHolderArray( $this );
206 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
207 $this->mVarCache
= array();
210 * Prefix for temporary replacement strings for the multipass parser.
211 * \x07 should never appear in input as it's disallowed in XML.
212 * Using it at the front also gives us a little extra robustness
213 * since it shouldn't match when butted up against identifier-like
216 * Must not consist of all title characters, or else it will change
217 * the behaviour of <nowiki> in a link.
219 #$this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
220 # Changed to \x7f to allow XML double-parsing -- TS
221 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
224 # Clear these on every parse, bug 4549
225 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
227 $this->mShowToc
= true;
228 $this->mForceTocPosition
= false;
229 $this->mIncludeSizes
= array(
233 $this->mPPNodeCount
= 0;
234 $this->mDefaultSort
= false;
235 $this->mHeadings
= array();
236 $this->mDoubleUnderscores
= array();
237 $this->mExpensiveFunctionCount
= 0;
240 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
241 $this->mPreprocessor
= null;
244 wfRunHooks( 'ParserClearState', array( &$this ) );
245 wfProfileOut( __METHOD__
);
248 function setOutputType( $ot ) {
249 $this->mOutputType
= $ot;
252 'html' => $ot == self
::OT_HTML
,
253 'wiki' => $ot == self
::OT_WIKI
,
254 'pre' => $ot == self
::OT_PREPROCESS
,
259 * Set the context title
261 function setTitle( $t ) {
262 if ( !$t ||
$t instanceof FakeTitle
) {
263 $t = Title
::newFromText( 'NO TITLE' );
266 if ( strval( $t->getFragment() ) !== '' ) {
267 # Strip the fragment to avoid various odd effects
268 $this->mTitle
= clone $t;
269 $this->mTitle
->setFragment( '' );
276 * Accessor for mUniqPrefix.
280 function uniqPrefix() {
281 if( !isset( $this->mUniqPrefix
) ) {
282 // @todo Fixme: this is probably *horribly wrong*
283 // LanguageConverter seems to want $wgParser's uniqPrefix, however
284 // if this is called for a parser cache hit, the parser may not
285 // have ever been initialized in the first place.
286 // Not really sure what the heck is supposed to be going on here.
288 //throw new MWException( "Accessing uninitialized mUniqPrefix" );
290 return $this->mUniqPrefix
;
294 * Convert wikitext to HTML
295 * Do not call this function recursively.
297 * @param $text String: text we want to parse
298 * @param $title A title object
299 * @param $options ParserOptions
300 * @param $linestart boolean
301 * @param $clearState boolean
302 * @param $revid Int: number to pass in {{REVISIONID}}
303 * @return ParserOutput a ParserOutput
305 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
307 * First pass--just handle <nowiki> sections, pass the rest off
308 * to internalParse() which does all the real work.
311 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang, $wgDisableLangConversion;
312 $fname = __METHOD__
.'-' . wfGetCaller();
313 wfProfileIn( __METHOD__
);
314 wfProfileIn( $fname );
320 $this->mOptions
= $options;
321 $this->setTitle( $title ); // Page title has to be set for the pre-processor
323 $oldRevisionId = $this->mRevisionId
;
324 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
325 if( $revid !== null ) {
326 $this->mRevisionId
= $revid;
327 $this->mRevisionTimestamp
= null;
329 $this->setOutputType( self
::OT_HTML
);
330 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
332 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
333 $text = $this->internalParse( $text );
335 $text = $this->mStripState
->unstripGeneral( $text );
337 # Clean up special characters, only run once, next-to-last before doBlockLevels
339 # french spaces, last one Guillemet-left
340 # only if there is something before the space
341 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
342 # french spaces, Guillemet-right
343 '/(\\302\\253) /' => '\\1 ',
344 '/ (!\s*important)/' => ' \\1', #Beware of CSS magic word !important, bug #11874.
346 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
348 $text = $this->doBlockLevels( $text, $linestart );
350 $this->replaceLinkHolders( $text );
352 // The position of the convert() call should not be changed. it
353 // assumes that the links are all replaced and the only thing left
354 // is the <nowiki> mark.
355 if ( !( $wgDisableLangConversion
356 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
357 ||
$this->mTitle
->isTalkPage()
358 ||
$this->mTitle
->isConversionTable() ) ) {
359 $text = $wgContLang->convert( $text );
362 // A title may have been set in a conversion rule.
363 // Note that if a user tries to set a title in a conversion
364 // rule but content conversion was not done, then the parser
365 // won't pick it up. This is probably expected behavior.
366 if ( $wgContLang->getConvRuleTitle() ) {
367 $this->mOutput
->setTitleText( $wgContLang->getConvRuleTitle() );
368 } elseif ( !( $wgDisableLangConversion
369 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] ) ) ) {
370 $this->mOutput
->setTitleText( $wgContLang->convert( $title->getPrefixedText() ) );
373 $text = $this->mStripState
->unstripNoWiki( $text );
375 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
377 //!JF Move to its own function
379 $uniq_prefix = $this->mUniqPrefix
;
381 $elements = array_keys( $this->mTransparentTagHooks
);
382 $text = self
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
384 foreach( $matches as $marker => $data ) {
385 list( $element, $content, $params, $tag ) = $data;
386 $tagName = strtolower( $element );
387 if( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
388 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName],
389 array( $content, $params, $this ) );
393 $this->mStripState
->general
->setPair( $marker, $output );
395 $text = $this->mStripState
->unstripGeneral( $text );
397 $text = Sanitizer
::normalizeCharReferences( $text );
399 if ( ( $wgUseTidy && $this->mOptions
->mTidy
) ||
$wgAlwaysUseTidy ) {
400 $text = MWTidy
::tidy( $text );
402 # attempt to sanitize at least some nesting problems
403 # (bug #2702 and quite a few others)
405 # ''Something [http://www.cool.com cool''] -->
406 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
407 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
408 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
409 # fix up an anchor inside another anchor, only
410 # at least for a single single nested link (bug 3695)
411 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
412 '\\1\\2</a>\\3</a>\\1\\4</a>',
413 # fix div inside inline elements- doBlockLevels won't wrap a line which
414 # contains a div, so fix it up here; replace
415 # div with escaped text
416 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
417 '\\1\\3<div\\5>\\6</div>\\8\\9',
418 # remove empty italic or bold tag pairs, some
419 # introduced by rules above
420 '/<([bi])><\/\\1>/' => '',
423 $text = preg_replace(
424 array_keys( $tidyregs ),
425 array_values( $tidyregs ),
428 global $wgExpensiveParserFunctionLimit;
429 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
430 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
433 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
435 # Information on include size limits, for the benefit of users who try to skirt them
436 if ( $this->mOptions
->getEnableLimitReport() ) {
437 global $wgExpensiveParserFunctionLimit;
438 $max = $this->mOptions
->getMaxIncludeSize();
439 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
441 "NewPP limit report\n" .
442 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
443 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
444 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
446 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
447 $text .= "\n<!-- \n$limitReport-->\n";
449 $this->mOutput
->setText( $text );
451 $this->mRevisionId
= $oldRevisionId;
452 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
453 wfProfileOut( $fname );
454 wfProfileOut( __METHOD__
);
456 return $this->mOutput
;
460 * Recursive parser entry point that can be called from an extension tag
463 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
465 * @param $text String: text extension wants to have parsed
466 * @param PPFrame $frame: The frame to use for expanding any template variables
468 function recursiveTagParse( $text, $frame=false ) {
469 wfProfileIn( __METHOD__
);
470 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
471 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
472 $text = $this->internalParse( $text, false, $frame );
473 wfProfileOut( __METHOD__
);
478 * Expand templates and variables in the text, producing valid, static wikitext.
479 * Also removes comments.
481 function preprocess( $text, $title, $options, $revid = null ) {
482 wfProfileIn( __METHOD__
);
484 $this->setOutputType( self
::OT_PREPROCESS
);
485 $this->mOptions
= $options;
486 $this->setTitle( $title );
487 if( $revid !== null ) {
488 $this->mRevisionId
= $revid;
490 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
491 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
492 $text = $this->replaceVariables( $text );
493 $text = $this->mStripState
->unstripBoth( $text );
494 wfProfileOut( __METHOD__
);
499 * Get the wikitext of a page as though it was transcluded.
501 * Specifically <includeonly> etc. are parsed, redirects are followed, comments
502 * are removed, but templates arguments and parser functions are untouched.
504 * This is not called by the parser itself, see braceSubstitution for its transclusion.
506 public function getTransclusionText( $title, $options ) {
507 // Must initialize first
509 $this->setOutputType( self
::OT_INCLUDES
);
510 $this->mOptions
= $options;
511 $this->setTitle( new FakeTitle
);
513 list( $text, $title ) = $this->getTemplateDom( $title );
514 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
515 return $this->getPreprocessor()->newFrame()->expand( $text, $flags );
519 * Get a random string
524 function getRandomString() {
525 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
528 function &getTitle() { return $this->mTitle
; }
529 function getOptions() { return $this->mOptions
; }
530 function getRevisionId() { return $this->mRevisionId
; }
531 function getOutput() { return $this->mOutput
; }
532 function nextLinkID() { return $this->mLinkID++
; }
534 function getFunctionLang() {
535 global $wgLang, $wgContLang;
537 $target = $this->mOptions
->getTargetLanguage();
538 if ( $target !== null ) {
541 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
546 * Get a preprocessor object
548 function getPreprocessor() {
549 if ( !isset( $this->mPreprocessor
) ) {
550 $class = $this->mPreprocessorClass
;
551 $this->mPreprocessor
= new $class( $this );
553 return $this->mPreprocessor
;
557 * Replaces all occurrences of HTML-style comments and the given tags
558 * in the text with a random marker and returns the next text. The output
559 * parameter $matches will be an associative array filled with data in
561 * 'UNIQ-xxxxx' => array(
564 * array( 'param' => 'x' ),
565 * '<element param="x">tag content</element>' ) )
567 * @param $elements list of element names. Comments are always extracted.
568 * @param $text Source text string.
569 * @param $uniq_prefix
574 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
579 $taglist = implode( '|', $elements );
580 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
582 while ( $text != '' ) {
583 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
585 if( count( $p ) < 5 ) {
588 if( count( $p ) > 5 ) {
602 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . self
::MARKER_SUFFIX
;
603 $stripped .= $marker;
605 if ( $close === '/>' ) {
606 // Empty element tag, <tag />
611 if( $element === '!--' ) {
614 $end = "/(<\\/$element\\s*>)/i";
616 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
618 if( count( $q ) < 3 ) {
619 # No end tag -- let it run out to the end of the text.
628 $matches[$marker] = array( $element,
630 Sanitizer
::decodeTagAttributes( $attributes ),
631 "<$element$attributes$close$content$tail" );
637 * Get a list of strippable XML-like elements
639 function getStripList() {
640 return $this->mStripList
;
644 * @deprecated use replaceVariables
646 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
651 * Restores pre, math, and other extensions removed by strip()
653 * always call unstripNoWiki() after this one
655 * @deprecated use $this->mStripState->unstrip()
657 function unstrip( $text, $state ) {
658 return $state->unstripGeneral( $text );
662 * Always call this after unstrip() to preserve the order
665 * @deprecated use $this->mStripState->unstrip()
667 function unstripNoWiki( $text, $state ) {
668 return $state->unstripNoWiki( $text );
672 * @deprecated use $this->mStripState->unstripBoth()
674 function unstripForHTML( $text ) {
675 return $this->mStripState
->unstripBoth( $text );
679 * Add an item to the strip state
680 * Returns the unique tag which must be inserted into the stripped text
681 * The tag will be replaced with the original text in unstrip()
685 function insertStripItem( $text ) {
686 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
687 $this->mMarkerIndex++
;
688 $this->mStripState
->general
->setPair( $rnd, $text );
693 * Interface with html tidy
694 * @deprecated Use MWTidy::tidy()
696 public static function tidy( $text ) {
697 wfDeprecated( __METHOD__
);
698 return MWTidy
::tidy( $text );
702 * parse the wiki syntax used to render tables
706 function doTableStuff ( $text ) {
707 wfProfileIn( __METHOD__
);
709 $lines = StringUtils
::explode( "\n", $text );
711 $td_history = array (); // Is currently a td tag open?
712 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
713 $tr_history = array (); // Is currently a tr tag open?
714 $tr_attributes = array (); // history of tr attributes
715 $has_opened_tr = array(); // Did this table open a <tr> element?
716 $indent_level = 0; // indent level of the table
718 foreach ( $lines as $outLine ) {
719 $line = trim( $outLine );
721 if( $line == '' ) { // empty line, go to next line
722 $out .= $outLine."\n";
725 $first_character = $line[0];
728 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
729 // First check if we are starting a new table
730 $indent_level = strlen( $matches[1] );
732 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
733 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
735 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
736 array_push( $td_history , false );
737 array_push( $last_tag_history , '' );
738 array_push( $tr_history , false );
739 array_push( $tr_attributes , '' );
740 array_push( $has_opened_tr , false );
741 } else if ( count ( $td_history ) == 0 ) {
742 // Don't do any of the following
743 $out .= $outLine."\n";
745 } else if ( substr ( $line , 0 , 2 ) === '|}' ) {
746 // We are ending a table
747 $line = '</table>' . substr ( $line , 2 );
748 $last_tag = array_pop ( $last_tag_history );
750 if ( !array_pop ( $has_opened_tr ) ) {
751 $line = "<tr><td></td></tr>{$line}";
754 if ( array_pop ( $tr_history ) ) {
755 $line = "</tr>{$line}";
758 if ( array_pop ( $td_history ) ) {
759 $line = "</{$last_tag}>{$line}";
761 array_pop ( $tr_attributes );
762 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
763 } else if ( substr ( $line , 0 , 2 ) === '|-' ) {
764 // Now we have a table row
765 $line = preg_replace( '#^\|-+#', '', $line );
767 // Whats after the tag is now only attributes
768 $attributes = $this->mStripState
->unstripBoth( $line );
769 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
770 array_pop( $tr_attributes );
771 array_push( $tr_attributes, $attributes );
774 $last_tag = array_pop ( $last_tag_history );
775 array_pop ( $has_opened_tr );
776 array_push ( $has_opened_tr , true );
778 if ( array_pop ( $tr_history ) ) {
782 if ( array_pop ( $td_history ) ) {
783 $line = "</{$last_tag}>{$line}";
787 array_push ( $tr_history , false );
788 array_push ( $td_history , false );
789 array_push ( $last_tag_history , '' );
791 else if ( $first_character === '|' ||
$first_character === '!' ||
substr ( $line , 0 , 2 ) === '|+' ) {
792 // This might be cell elements, td, th or captions
793 if ( substr ( $line , 0 , 2 ) === '|+' ) {
794 $first_character = '+';
795 $line = substr ( $line , 1 );
798 $line = substr ( $line , 1 );
800 if ( $first_character === '!' ) {
801 $line = str_replace ( '!!' , '||' , $line );
804 // Split up multiple cells on the same line.
805 // FIXME : This can result in improper nesting of tags processed
806 // by earlier parser steps, but should avoid splitting up eg
807 // attribute values containing literal "||".
808 $cells = StringUtils
::explodeMarkup( '||' , $line );
812 // Loop through each table cell
813 foreach ( $cells as $cell )
816 if ( $first_character !== '+' )
818 $tr_after = array_pop ( $tr_attributes );
819 if ( !array_pop ( $tr_history ) ) {
820 $previous = "<tr{$tr_after}>\n";
822 array_push ( $tr_history , true );
823 array_push ( $tr_attributes , '' );
824 array_pop ( $has_opened_tr );
825 array_push ( $has_opened_tr , true );
828 $last_tag = array_pop ( $last_tag_history );
830 if ( array_pop ( $td_history ) ) {
831 $previous = "</{$last_tag}>{$previous}";
834 if ( $first_character === '|' ) {
836 } else if ( $first_character === '!' ) {
838 } else if ( $first_character === '+' ) {
839 $last_tag = 'caption';
844 array_push ( $last_tag_history , $last_tag );
846 // A cell could contain both parameters and data
847 $cell_data = explode ( '|' , $cell , 2 );
849 // Bug 553: Note that a '|' inside an invalid link should not
850 // be mistaken as delimiting cell parameters
851 if ( strpos( $cell_data[0], '[[' ) !== false ) {
852 $cell = "{$previous}<{$last_tag}>{$cell}";
853 } else if ( count ( $cell_data ) == 1 )
854 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
856 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
857 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
858 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
862 array_push ( $td_history , true );
865 $out .= $outLine . "\n";
868 // Closing open td, tr && table
869 while ( count ( $td_history ) > 0 )
871 if ( array_pop ( $td_history ) ) {
874 if ( array_pop ( $tr_history ) ) {
877 if ( !array_pop ( $has_opened_tr ) ) {
878 $out .= "<tr><td></td></tr>\n" ;
881 $out .= "</table>\n";
884 // Remove trailing line-ending (b/c)
885 if ( substr( $out, -1 ) === "\n" ) {
886 $out = substr( $out, 0, -1 );
889 // special case: don't return empty table
890 if( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
894 wfProfileOut( __METHOD__
);
900 * Helper function for parse() that transforms wiki markup into
901 * HTML. Only called for $mOutputType == self::OT_HTML.
905 function internalParse( $text, $isMain = true, $frame=false ) {
906 wfProfileIn( __METHOD__
);
910 # Hook to suspend the parser in this state
911 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
912 wfProfileOut( __METHOD__
);
916 // if $frame is provided, then use $frame for replacing any variables
918 // use frame depth to infer how include/noinclude tags should be handled
919 // depth=0 means this is the top-level document; otherwise it's an included document
923 $flag = Parser
::PTD_FOR_INCLUSION
;
924 $dom = $this->preprocessToDom( $text, $flag );
925 $text = $frame->expand( $dom );
927 // if $frame is not provided, then use old-style replaceVariables
929 $text = $this->replaceVariables( $text );
932 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
933 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
935 // Tables need to come after variable replacement for things to work
936 // properly; putting them before other transformations should keep
937 // exciting things like link expansions from showing up in surprising
939 $text = $this->doTableStuff( $text );
941 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
943 $text = $this->doDoubleUnderscore( $text );
945 $text = $this->doHeadings( $text );
946 if( $this->mOptions
->getUseDynamicDates() ) {
947 $df = DateFormatter
::getInstance();
948 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
950 $text = $this->doAllQuotes( $text );
951 $text = $this->replaceInternalLinks( $text );
952 $text = $this->replaceExternalLinks( $text );
954 # replaceInternalLinks may sometimes leave behind
955 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
956 $text = str_replace($this->mUniqPrefix
.'NOPARSE', '', $text);
958 $text = $this->doMagicLinks( $text );
959 $text = $this->formatHeadings( $text, $origText, $isMain );
961 wfProfileOut( __METHOD__
);
966 * Replace special strings like "ISBN xxx" and "RFC xxx" with
967 * magic external links.
972 function doMagicLinks( $text ) {
973 wfProfileIn( __METHOD__
);
974 $prots = $this->mUrlProtocols
;
975 $urlChar = self
::EXT_LINK_URL_CLASS
;
976 $text = preg_replace_callback(
978 (<a.*?</a>) | # m[1]: Skip link text
979 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
980 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
981 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
982 ISBN\s+(\b # m[5]: ISBN, capture number
983 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
984 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
985 [0-9Xx] # check digit
987 )!x', array( &$this, 'magicLinkCallback' ), $text );
988 wfProfileOut( __METHOD__
);
992 function magicLinkCallback( $m ) {
993 if ( isset( $m[1] ) && $m[1] !== '' ) {
996 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
999 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1000 # Free external link
1001 return $this->makeFreeExternalLink( $m[0] );
1002 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1005 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1008 $CssClass = 'mw-magiclink-rfc';
1010 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1012 $urlmsg = 'pubmedurl';
1013 $CssClass = 'mw-magiclink-pmid';
1016 throw new MWException( __METHOD__
.': unrecognised match type "' .
1017 substr($m[0], 0, 20 ) . '"' );
1019 $url = wfMsg( $urlmsg, $id);
1020 $sk = $this->mOptions
->getSkin();
1021 $la = $sk->getExternalLinkAttributes( "external $CssClass" );
1022 return "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1023 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1026 $num = strtr( $isbn, array(
1031 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1033 $titleObj->escapeLocalUrl() .
1034 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1041 * Make a free external link, given a user-supplied URL
1045 function makeFreeExternalLink( $url ) {
1047 wfProfileIn( __METHOD__
);
1049 $sk = $this->mOptions
->getSkin();
1052 # The characters '<' and '>' (which were escaped by
1053 # removeHTMLtags()) should not be included in
1054 # URLs, per RFC 2396.
1056 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1057 $trail = substr($url, $m2[0][1]) . $trail;
1058 $url = substr($url, 0, $m2[0][1]);
1061 # Move trailing punctuation to $trail
1063 # If there is no left bracket, then consider right brackets fair game too
1064 if ( strpos( $url, '(' ) === false ) {
1068 $numSepChars = strspn( strrev( $url ), $sep );
1069 if ( $numSepChars ) {
1070 $trail = substr( $url, -$numSepChars ) . $trail;
1071 $url = substr( $url, 0, -$numSepChars );
1074 $url = Sanitizer
::cleanUrl( $url );
1076 # Is this an external image?
1077 $text = $this->maybeMakeExternalImage( $url );
1078 if ( $text === false ) {
1079 # Not an image, make a link
1080 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1081 $this->getExternalLinkAttribs( $url ) );
1082 # Register it in the output object...
1083 # Replace unnecessary URL escape codes with their equivalent characters
1084 $pasteurized = self
::replaceUnusualEscapes( $url );
1085 $this->mOutput
->addExternalLink( $pasteurized );
1087 wfProfileOut( __METHOD__
);
1088 return $text . $trail;
1093 * Parse headers and return html
1097 function doHeadings( $text ) {
1098 wfProfileIn( __METHOD__
);
1099 for ( $i = 6; $i >= 1; --$i ) {
1100 $h = str_repeat( '=', $i );
1101 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1102 "<h$i>\\1</h$i>", $text );
1104 wfProfileOut( __METHOD__
);
1109 * Replace single quotes with HTML markup
1111 * @return string the altered text
1113 function doAllQuotes( $text ) {
1114 wfProfileIn( __METHOD__
);
1116 $lines = StringUtils
::explode( "\n", $text );
1117 foreach ( $lines as $line ) {
1118 $outtext .= $this->doQuotes( $line ) . "\n";
1120 $outtext = substr($outtext, 0,-1);
1121 wfProfileOut( __METHOD__
);
1126 * Helper function for doAllQuotes()
1128 public function doQuotes( $text ) {
1129 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1130 if ( count( $arr ) == 1 )
1134 # First, do some preliminary work. This may shift some apostrophes from
1135 # being mark-up to being text. It also counts the number of occurrences
1136 # of bold and italics mark-ups.
1140 foreach ( $arr as $r )
1142 if ( ( $i %
2 ) == 1 )
1144 # If there are ever four apostrophes, assume the first is supposed to
1145 # be text, and the remaining three constitute mark-up for bold text.
1146 if ( strlen( $arr[$i] ) == 4 )
1151 # If there are more than 5 apostrophes in a row, assume they're all
1152 # text except for the last 5.
1153 else if ( strlen( $arr[$i] ) > 5 )
1155 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1158 # Count the number of occurrences of bold and italics mark-ups.
1159 # We are not counting sequences of five apostrophes.
1160 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1161 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1162 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1167 # If there is an odd number of both bold and italics, it is likely
1168 # that one of the bold ones was meant to be an apostrophe followed
1169 # by italics. Which one we cannot know for certain, but it is more
1170 # likely to be one that has a single-letter word before it.
1171 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1174 $firstsingleletterword = -1;
1175 $firstmultiletterword = -1;
1177 foreach ( $arr as $r )
1179 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1181 $x1 = substr ($arr[$i-1], -1);
1182 $x2 = substr ($arr[$i-1], -2, 1);
1184 if ($firstspace == -1) $firstspace = $i;
1185 } else if ($x2 === ' ') {
1186 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1188 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1194 # If there is a single-letter word, use it!
1195 if ($firstsingleletterword > -1)
1197 $arr [ $firstsingleletterword ] = "''";
1198 $arr [ $firstsingleletterword-1 ] .= "'";
1200 # If not, but there's a multi-letter word, use that one.
1201 else if ($firstmultiletterword > -1)
1203 $arr [ $firstmultiletterword ] = "''";
1204 $arr [ $firstmultiletterword-1 ] .= "'";
1206 # ... otherwise use the first one that has neither.
1207 # (notice that it is possible for all three to be -1 if, for example,
1208 # there is only one pentuple-apostrophe in the line)
1209 else if ($firstspace > -1)
1211 $arr [ $firstspace ] = "''";
1212 $arr [ $firstspace-1 ] .= "'";
1216 # Now let's actually convert our apostrophic mush to HTML!
1221 foreach ($arr as $r)
1225 if ($state === 'both')
1232 if (strlen ($r) == 2)
1235 { $output .= '</i>'; $state = ''; }
1236 else if ($state === 'bi')
1237 { $output .= '</i>'; $state = 'b'; }
1238 else if ($state === 'ib')
1239 { $output .= '</b></i><b>'; $state = 'b'; }
1240 else if ($state === 'both')
1241 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1242 else # $state can be 'b' or ''
1243 { $output .= '<i>'; $state .= 'i'; }
1245 else if (strlen ($r) == 3)
1248 { $output .= '</b>'; $state = ''; }
1249 else if ($state === 'bi')
1250 { $output .= '</i></b><i>'; $state = 'i'; }
1251 else if ($state === 'ib')
1252 { $output .= '</b>'; $state = 'i'; }
1253 else if ($state === 'both')
1254 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1255 else # $state can be 'i' or ''
1256 { $output .= '<b>'; $state .= 'b'; }
1258 else if (strlen ($r) == 5)
1261 { $output .= '</b><i>'; $state = 'i'; }
1262 else if ($state === 'i')
1263 { $output .= '</i><b>'; $state = 'b'; }
1264 else if ($state === 'bi')
1265 { $output .= '</i></b>'; $state = ''; }
1266 else if ($state === 'ib')
1267 { $output .= '</b></i>'; $state = ''; }
1268 else if ($state === 'both')
1269 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1270 else # ($state == '')
1271 { $buffer = ''; $state = 'both'; }
1276 # Now close all remaining tags. Notice that the order is important.
1277 if ($state === 'b' ||
$state === 'ib')
1279 if ($state === 'i' ||
$state === 'bi' ||
$state === 'ib')
1281 if ($state === 'bi')
1283 # There might be lonely ''''', so make sure we have a buffer
1284 if ($state === 'both' && $buffer)
1285 $output .= '<b><i>'.$buffer.'</i></b>';
1291 * Replace external links (REL)
1293 * Note: this is all very hackish and the order of execution matters a lot.
1294 * Make sure to run maintenance/parserTests.php if you change this code.
1298 function replaceExternalLinks( $text ) {
1300 wfProfileIn( __METHOD__
);
1302 $sk = $this->mOptions
->getSkin();
1304 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1305 $s = array_shift( $bits );
1308 while ( $i<count( $bits ) ) {
1310 $protocol = $bits[$i++
];
1311 $text = $bits[$i++
];
1312 $trail = $bits[$i++
];
1314 # The characters '<' and '>' (which were escaped by
1315 # removeHTMLtags()) should not be included in
1316 # URLs, per RFC 2396.
1318 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1319 $text = substr($url, $m2[0][1]) . ' ' . $text;
1320 $url = substr($url, 0, $m2[0][1]);
1323 # If the link text is an image URL, replace it with an <img> tag
1324 # This happened by accident in the original parser, but some people used it extensively
1325 $img = $this->maybeMakeExternalImage( $text );
1326 if ( $img !== false ) {
1332 # Set linktype for CSS - if URL==text, link is essentially free
1333 $linktype = ($text === $url) ?
'free' : 'text';
1335 # No link text, e.g. [http://domain.tld/some.link]
1336 if ( $text == '' ) {
1337 # Autonumber if allowed. See bug #5918
1338 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1339 $langObj = $this->getFunctionLang();
1340 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1341 $linktype = 'autonumber';
1343 # Otherwise just use the URL
1344 $text = htmlspecialchars( $url );
1348 # Have link text, e.g. [http://domain.tld/some.link text]s
1350 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1353 $text = $wgContLang->markNoConversion($text);
1355 $url = Sanitizer
::cleanUrl( $url );
1357 # Use the encoded URL
1358 # This means that users can paste URLs directly into the text
1359 # Funny characters like ö aren't valid in URLs anyway
1360 # This was changed in August 2004
1361 $s .= $sk->makeExternalLink( $url, $text, false, $linktype,
1362 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1364 # Register link in the output object.
1365 # Replace unnecessary URL escape codes with the referenced character
1366 # This prevents spammers from hiding links from the filters
1367 $pasteurized = self
::replaceUnusualEscapes( $url );
1368 $this->mOutput
->addExternalLink( $pasteurized );
1371 wfProfileOut( __METHOD__
);
1376 * Get an associative array of additional HTML attributes appropriate for a
1377 * particular external link. This currently may include rel => nofollow
1378 * (depending on configuration, namespace, and the URL's domain) and/or a
1379 * target attribute (depending on configuration).
1381 * @param string $url Optional URL, to extract the domain from for rel =>
1382 * nofollow if appropriate
1383 * @return array Associative array of HTML attributes
1385 function getExternalLinkAttribs( $url = false ) {
1387 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1388 $ns = $this->mTitle
->getNamespace();
1389 if( $wgNoFollowLinks && !in_array($ns, $wgNoFollowNsExceptions) ) {
1390 $attribs['rel'] = 'nofollow';
1392 global $wgNoFollowDomainExceptions;
1393 if ( $wgNoFollowDomainExceptions ) {
1394 $bits = wfParseUrl( $url );
1395 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1396 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1397 if( substr( $bits['host'], -strlen( $domain ) )
1399 unset( $attribs['rel'] );
1406 if ( $this->mOptions
->getExternalLinkTarget() ) {
1407 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1414 * Replace unusual URL escape codes with their equivalent characters
1418 * @todo This can merge genuinely required bits in the path or query string,
1419 * breaking legit URLs. A proper fix would treat the various parts of
1420 * the URL differently; as a workaround, just use the output for
1421 * statistical records, not for actual linking/output.
1423 static function replaceUnusualEscapes( $url ) {
1424 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1425 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1429 * Callback function used in replaceUnusualEscapes().
1430 * Replaces unusual URL escape codes with their equivalent character
1434 private static function replaceUnusualEscapesCallback( $matches ) {
1435 $char = urldecode( $matches[0] );
1436 $ord = ord( $char );
1437 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1438 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1439 // No, shouldn't be escaped
1442 // Yes, leave it escaped
1448 * make an image if it's allowed, either through the global
1449 * option, through the exception, or through the on-wiki whitelist
1452 function maybeMakeExternalImage( $url ) {
1453 $sk = $this->mOptions
->getSkin();
1454 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1455 $imagesexception = !empty($imagesfrom);
1457 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1458 if( $imagesexception && is_array( $imagesfrom ) ) {
1459 $imagematch = false;
1460 foreach( $imagesfrom as $match ) {
1461 if( strpos( $url, $match ) === 0 ) {
1466 } elseif( $imagesexception ) {
1467 $imagematch = (strpos( $url, $imagesfrom ) === 0);
1469 $imagematch = false;
1471 if ( $this->mOptions
->getAllowExternalImages()
1472 ||
( $imagesexception && $imagematch ) ) {
1473 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1475 $text = $sk->makeExternalImage( $url );
1478 if( !$text && $this->mOptions
->getEnableImageWhitelist()
1479 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1480 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1481 foreach( $whitelist as $entry ) {
1482 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1483 if( strpos( $entry, '#' ) === 0 ||
$entry === '' )
1485 if( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1486 # Image matches a whitelist entry
1487 $text = $sk->makeExternalImage( $url );
1496 * Process [[ ]] wikilinks
1497 * @return processed text
1501 function replaceInternalLinks( $s ) {
1502 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1507 * Process [[ ]] wikilinks (RIL)
1508 * @return LinkHolderArray
1512 function replaceInternalLinks2( &$s ) {
1515 wfProfileIn( __METHOD__
);
1517 wfProfileIn( __METHOD__
.'-setup' );
1518 static $tc = FALSE, $e1, $e1_img;
1519 # the % is needed to support urlencoded titles as well
1521 $tc = Title
::legalChars() . '#%';
1522 # Match a link having the form [[namespace:link|alternate]]trail
1523 $e1 = "/^([{$tc}]*)(\\|.*?)?]](.*)\$/sD";
1524 # Match cases where there is no "]]", which might still be images
1525 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1528 $sk = $this->mOptions
->getSkin();
1529 $holders = new LinkHolderArray( $this );
1531 #split the entire text string on occurences of [[
1532 $a = StringUtils
::explode( '[[', ' ' . $s );
1533 #get the first element (all text up to first [[), and remove the space we added
1536 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1537 $s = substr( $s, 1 );
1539 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1541 if ( $useLinkPrefixExtension ) {
1542 # Match the end of a line for a word that's not followed by whitespace,
1543 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1544 $e2 = wfMsgForContent( 'linkprefix' );
1547 if( is_null( $this->mTitle
) ) {
1548 wfProfileOut( __METHOD__
.'-setup' );
1549 wfProfileOut( __METHOD__
);
1550 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1552 $nottalk = !$this->mTitle
->isTalkPage();
1554 if ( $useLinkPrefixExtension ) {
1556 if ( preg_match( $e2, $s, $m ) ) {
1557 $first_prefix = $m[2];
1559 $first_prefix = false;
1565 if($wgContLang->hasVariants()) {
1566 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1568 $selflink = array($this->mTitle
->getPrefixedText());
1570 $useSubpages = $this->areSubpagesAllowed();
1571 wfProfileOut( __METHOD__
.'-setup' );
1573 # Loop for each link
1574 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1575 # Check for excessive memory usage
1576 if ( $holders->isBig() ) {
1578 # Do the existence check, replace the link holders and clear the array
1579 $holders->replace( $s );
1583 if ( $useLinkPrefixExtension ) {
1584 wfProfileIn( __METHOD__
.'-prefixhandling' );
1585 if ( preg_match( $e2, $s, $m ) ) {
1593 $prefix = $first_prefix;
1594 $first_prefix = false;
1596 wfProfileOut( __METHOD__
.'-prefixhandling' );
1599 $might_be_img = false;
1601 wfProfileIn( __METHOD__
."-e1" );
1602 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1604 if( $m[2] === '' ) {
1606 } elseif( $m[2] === '|' ) {
1607 $text = $this->getPipeTrickText( $m[1] );
1609 $text = substr( $m[2], 1 );
1612 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1613 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1614 # the real problem is with the $e1 regex
1617 # Still some problems for cases where the ] is meant to be outside punctuation,
1618 # and no image is in sight. See bug 2095.
1621 substr( $m[3], 0, 1 ) === ']' &&
1622 strpos($text, '[') !== false
1625 $text .= ']'; # so that replaceExternalLinks($text) works later
1626 $m[3] = substr( $m[3], 1 );
1629 # Handle pipe-trick for [[|<blah>]]
1630 $lnk = $m[1] === '' ?
$this->getPipeTrickLink( $text ) : $m[1];
1631 # fix up urlencoded title texts
1632 if( strpos( $lnk, '%' ) !== false ) {
1633 # Should anchors '#' also be rejected?
1634 $lnk = str_replace( array('<', '>'), array('<', '>'), urldecode($lnk) );
1638 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1639 $might_be_img = true;
1641 $lnk = strpos( $m[1], '%' ) === false ?
$m[1] : urldecode( $m[1] );
1643 } else { # Invalid form; output directly
1644 $s .= $prefix . '[[' . $line ;
1645 wfProfileOut( __METHOD__
."-e1" );
1648 wfProfileOut( __METHOD__
."-e1" );
1649 wfProfileIn( __METHOD__
."-misc" );
1651 # Don't allow internal links to pages containing
1652 # PROTO: where PROTO is a valid URL protocol; these
1653 # should be external links.
1654 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $lnk ) ) {
1655 $s .= $prefix . '[[' . $line ;
1656 wfProfileOut( __METHOD__
."-misc" );
1660 # Make subpage if necessary
1661 if ( $useSubpages ) {
1662 $link = $this->maybeDoSubpageLink( $lnk, $text );
1667 $noforce = (substr( $lnk, 0, 1 ) !== ':');
1669 # Strip off leading ':'
1670 $link = substr( $link, 1 );
1673 wfProfileOut( __METHOD__
."-misc" );
1674 wfProfileIn( __METHOD__
."-title" );
1675 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1676 if ( $nt === null ) {
1677 $s .= $prefix . '[[' . $line;
1678 wfProfileOut( __METHOD__
."-title" );
1682 $ns = $nt->getNamespace();
1683 $iw = $nt->getInterWiki();
1684 wfProfileOut( __METHOD__
."-title" );
1686 if ( $might_be_img ) { # if this is actually an invalid link
1687 wfProfileIn( __METHOD__
."-might_be_img" );
1688 if ( $ns == NS_FILE
&& $noforce ) { #but might be an image
1691 #look at the next 'line' to see if we can close it there
1693 $next_line = $a->current();
1694 if ( $next_line === false ||
$next_line === null ) {
1697 $m = explode( ']]', $next_line, 3 );
1698 if ( count( $m ) == 3 ) {
1699 # the first ]] closes the inner link, the second the image
1701 $text .= "[[{$m[0]}]]{$m[1]}";
1704 } elseif ( count( $m ) == 2 ) {
1705 #if there's exactly one ]] that's fine, we'll keep looking
1706 $text .= "[[{$m[0]}]]{$m[1]}";
1708 #if $next_line is invalid too, we need look no further
1709 $text .= '[[' . $next_line;
1714 # we couldn't find the end of this imageLink, so output it raw
1715 #but don't ignore what might be perfectly normal links in the text we've examined
1716 $holders->merge( $this->replaceInternalLinks2( $text ) );
1717 $s .= "{$prefix}[[$link|$text";
1718 # note: no $trail, because without an end, there *is* no trail
1719 wfProfileOut( __METHOD__
."-might_be_img" );
1722 } else { #it's not an image, so output it raw
1723 $s .= "{$prefix}[[$link|$text";
1724 # note: no $trail, because without an end, there *is* no trail
1725 wfProfileOut( __METHOD__
."-might_be_img" );
1728 wfProfileOut( __METHOD__
."-might_be_img" );
1731 $wasblank = ( $text == '' );
1732 if ( $wasblank ) $text = $link;
1734 # Link not escaped by : , create the various objects
1738 wfProfileIn( __METHOD__
."-interwiki" );
1739 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1740 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1741 $s = rtrim($s . $prefix);
1742 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1743 wfProfileOut( __METHOD__
."-interwiki" );
1746 wfProfileOut( __METHOD__
."-interwiki" );
1748 if ( $ns == NS_FILE
) {
1749 wfProfileIn( __METHOD__
."-image" );
1750 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1752 # if no parameters were passed, $text
1753 # becomes something like "File:Foo.png",
1754 # which we don't want to pass on to the
1758 # recursively parse links inside the image caption
1759 # actually, this will parse them in any other parameters, too,
1760 # but it might be hard to fix that, and it doesn't matter ATM
1761 $text = $this->replaceExternalLinks($text);
1762 $holders->merge( $this->replaceInternalLinks2( $text ) );
1764 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1765 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1767 $s .= $prefix . $trail;
1769 $this->mOutput
->addImage( $nt->getDBkey() );
1770 wfProfileOut( __METHOD__
."-image" );
1775 if ( $ns == NS_CATEGORY
) {
1776 wfProfileIn( __METHOD__
."-category" );
1777 $s = rtrim($s . "\n"); # bug 87
1780 $sortkey = $this->getDefaultSort();
1784 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1785 $sortkey = str_replace( "\n", '', $sortkey );
1786 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1787 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1790 * Strip the whitespace Category links produce, see bug 87
1791 * @todo We might want to use trim($tmp, "\n") here.
1793 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1795 wfProfileOut( __METHOD__
."-category" );
1800 # Self-link checking
1801 if( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1802 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1803 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1808 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1809 # FIXME: Should do batch file existence checks, see comment below
1810 if( $ns == NS_MEDIA
) {
1811 wfProfileIn( __METHOD__
."-media" );
1812 # Give extensions a chance to select the file revision for us
1813 $skip = $time = false;
1814 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1816 $link = $sk->link( $nt );
1818 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1820 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1821 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1822 $this->mOutput
->addImage( $nt->getDBkey() );
1823 wfProfileOut( __METHOD__
."-media" );
1827 wfProfileIn( __METHOD__
."-always_known" );
1828 # Some titles, such as valid special pages or files in foreign repos, should
1829 # be shown as bluelinks even though they're not included in the page table
1831 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1832 # batch file existence checks for NS_FILE and NS_MEDIA
1833 if( $iw == '' && $nt->isAlwaysKnown() ) {
1834 $this->mOutput
->addLink( $nt );
1835 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1837 # Links will be added to the output link list after checking
1838 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1840 wfProfileOut( __METHOD__
."-always_known" );
1842 wfProfileOut( __METHOD__
);
1847 * Make a link placeholder. The text returned can be later resolved to a real link with
1848 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1849 * parsing of interwiki links, and secondly to allow all existence checks and
1850 * article length checks (for stub links) to be bundled into a single query.
1854 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1855 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1859 * Render a forced-blue link inline; protect against double expansion of
1860 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1861 * Since this little disaster has to split off the trail text to avoid
1862 * breaking URLs in the following text without breaking trails on the
1863 * wiki links, it's been made into a horrible function.
1866 * @param string $text
1867 * @param string $query
1868 * @param string $trail
1869 * @param string $prefix
1870 * @return string HTML-wikitext mix oh yuck
1872 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1873 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1874 $sk = $this->mOptions
->getSkin();
1875 // FIXME: use link() instead of deprecated makeKnownLinkObj()
1876 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1877 return $this->armorLinks( $link ) . $trail;
1881 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1882 * going to go through further parsing steps before inline URL expansion.
1884 * Not needed quite as much as it used to be since free links are a bit
1885 * more sensible these days. But bracketed links are still an issue.
1887 * @param string more-or-less HTML
1888 * @return string less-or-more HTML with NOPARSE bits
1890 function armorLinks( $text ) {
1891 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1892 "{$this->mUniqPrefix}NOPARSE$1", $text );
1896 * Return true if subpage links should be expanded on this page.
1899 function areSubpagesAllowed() {
1900 # Some namespaces don't allow subpages
1901 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
1905 * Handle link to subpage if necessary
1906 * @param string $target the source of the link
1907 * @param string &$text the link text, modified as necessary
1908 * @return string the full name of the link
1911 function maybeDoSubpageLink($target, &$text) {
1912 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
1916 * From the [[title|]] return link-text as though the used typed [[title|link-text]]
1917 * @param string $link from [[$link|]]
1918 * @return string $text for [[$link|$text]]
1920 function getPipeTrickText( $link ) {
1921 return Linker
::getPipeTrickText( $link );
1925 * From the [[|link-text]] return the title as though the user typed [[title|link-text]]
1926 * @param string $text from [[|$text]]
1927 * @param Title $title to resolve the link against
1928 * @return string $link for [[$link|$text]]
1930 function getPipeTrickLink( $text ) {
1931 return Linker
::getPipeTrickLink( $text, $this->mTitle
);
1935 * Used by doBlockLevels()
1938 /* private */ function closeParagraph() {
1940 if ( $this->mLastSection
!= '' ) {
1941 $result = '</' . $this->mLastSection
. ">\n";
1943 $this->mInPre
= false;
1944 $this->mLastSection
= '';
1947 # getCommon() returns the length of the longest common substring
1948 # of both arguments, starting at the beginning of both.
1950 /* private */ function getCommon( $st1, $st2 ) {
1951 $fl = strlen( $st1 );
1952 $shorter = strlen( $st2 );
1953 if ( $fl < $shorter ) { $shorter = $fl; }
1955 for ( $i = 0; $i < $shorter; ++
$i ) {
1956 if ( $st1{$i} != $st2{$i} ) { break; }
1960 # These next three functions open, continue, and close the list
1961 # element appropriate to the prefix character passed into them.
1963 /* private */ function openList( $char ) {
1964 $result = $this->closeParagraph();
1966 if ( '*' === $char ) { $result .= '<ul><li>'; }
1967 elseif ( '#' === $char ) { $result .= '<ol><li>'; }
1968 elseif ( ':' === $char ) { $result .= '<dl><dd>'; }
1969 elseif ( ';' === $char ) {
1970 $result .= '<dl><dt>';
1971 $this->mDTopen
= true;
1973 else { $result = '<!-- ERR 1 -->'; }
1978 /* private */ function nextItem( $char ) {
1979 if ( '*' === $char ||
'#' === $char ) { return '</li><li>'; }
1980 elseif ( ':' === $char ||
';' === $char ) {
1982 if ( $this->mDTopen
) { $close = '</dt>'; }
1983 if ( ';' === $char ) {
1984 $this->mDTopen
= true;
1985 return $close . '<dt>';
1987 $this->mDTopen
= false;
1988 return $close . '<dd>';
1991 return '<!-- ERR 2 -->';
1994 /* private */ function closeList( $char ) {
1995 if ( '*' === $char ) { $text = '</li></ul>'; }
1996 elseif ( '#' === $char ) { $text = '</li></ol>'; }
1997 elseif ( ':' === $char ) {
1998 if ( $this->mDTopen
) {
1999 $this->mDTopen
= false;
2000 $text = '</dt></dl>';
2002 $text = '</dd></dl>';
2005 else { return '<!-- ERR 3 -->'; }
2011 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2013 * @param $linestart bool whether or not this is at the start of a line.
2015 * @return string the lists rendered as HTML
2017 function doBlockLevels( $text, $linestart ) {
2018 wfProfileIn( __METHOD__
);
2020 # Parsing through the text line by line. The main thing
2021 # happening here is handling of block-level elements p, pre,
2022 # and making lists from lines starting with * # : etc.
2024 $textLines = StringUtils
::explode( "\n", $text );
2026 $lastPrefix = $output = '';
2027 $this->mDTopen
= $inBlockElem = false;
2029 $paragraphStack = false;
2031 foreach ( $textLines as $oLine ) {
2033 if ( !$linestart ) {
2043 $lastPrefixLength = strlen( $lastPrefix );
2044 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2045 $preOpenMatch = preg_match('/<pre/i', $oLine );
2046 // If not in a <pre> element, scan for and figure out what prefixes are there.
2047 if ( !$this->mInPre
) {
2048 # Multiple prefixes may abut each other for nested lists.
2049 $prefixLength = strspn( $oLine, '*#:;' );
2050 $prefix = substr( $oLine, 0, $prefixLength );
2053 // ; and : are both from definition-lists, so they're equivalent
2054 // for the purposes of determining whether or not we need to open/close
2056 $prefix2 = str_replace( ';', ':', $prefix );
2057 $t = substr( $oLine, $prefixLength );
2058 $this->mInPre
= (bool)$preOpenMatch;
2060 # Don't interpret any other prefixes in preformatted text
2062 $prefix = $prefix2 = '';
2067 if( $prefixLength && $lastPrefix === $prefix2 ) {
2068 # Same as the last item, so no need to deal with nesting or opening stuff
2069 $output .= $this->nextItem( substr( $prefix, -1 ) );
2070 $paragraphStack = false;
2072 if ( substr( $prefix, -1 ) === ';') {
2073 # The one nasty exception: definition lists work like this:
2074 # ; title : definition text
2075 # So we check for : in the remainder text to split up the
2076 # title and definition, without b0rking links.
2078 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2080 $output .= $term . $this->nextItem( ':' );
2083 } elseif( $prefixLength ||
$lastPrefixLength ) {
2084 // We need to open or close prefixes, or both.
2086 # Either open or close a level...
2087 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2088 $paragraphStack = false;
2090 // Close all the prefixes which aren't shared.
2091 while( $commonPrefixLength < $lastPrefixLength ) {
2092 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2093 --$lastPrefixLength;
2096 // Continue the current prefix if appropriate.
2097 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2098 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2101 // Open prefixes where appropriate.
2102 while ( $prefixLength > $commonPrefixLength ) {
2103 $char = substr( $prefix, $commonPrefixLength, 1 );
2104 $output .= $this->openList( $char );
2106 if ( ';' === $char ) {
2107 # FIXME: This is dupe of code above
2108 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2110 $output .= $term . $this->nextItem( ':' );
2113 ++
$commonPrefixLength;
2115 $lastPrefix = $prefix2;
2118 // If we have no prefixes, go to paragraph mode.
2119 if( 0 == $prefixLength ) {
2120 wfProfileIn( __METHOD__
."-paragraph" );
2121 # No prefix (not in list)--go to paragraph mode
2122 // XXX: use a stack for nestable elements like span, table and div
2123 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2124 $closematch = preg_match(
2125 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2126 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2127 if ( $openmatch or $closematch ) {
2128 $paragraphStack = false;
2129 #Â TODO bug 5718: paragraph closed
2130 $output .= $this->closeParagraph();
2131 if ( $preOpenMatch and !$preCloseMatch ) {
2132 $this->mInPre
= true;
2134 if ( $closematch ) {
2135 $inBlockElem = false;
2137 $inBlockElem = true;
2139 } else if ( !$inBlockElem && !$this->mInPre
) {
2140 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' or trim($t) != '' ) ) {
2142 if ($this->mLastSection
!== 'pre') {
2143 $paragraphStack = false;
2144 $output .= $this->closeParagraph().'<pre>';
2145 $this->mLastSection
= 'pre';
2147 $t = substr( $t, 1 );
2150 if ( trim($t) == '' ) {
2151 if ( $paragraphStack ) {
2152 $output .= $paragraphStack.'<br />';
2153 $paragraphStack = false;
2154 $this->mLastSection
= 'p';
2156 if ($this->mLastSection
!== 'p' ) {
2157 $output .= $this->closeParagraph();
2158 $this->mLastSection
= '';
2159 $paragraphStack = '<p>';
2161 $paragraphStack = '</p><p>';
2165 if ( $paragraphStack ) {
2166 $output .= $paragraphStack;
2167 $paragraphStack = false;
2168 $this->mLastSection
= 'p';
2169 } else if ($this->mLastSection
!== 'p') {
2170 $output .= $this->closeParagraph().'<p>';
2171 $this->mLastSection
= 'p';
2176 wfProfileOut( __METHOD__
."-paragraph" );
2178 // somewhere above we forget to get out of pre block (bug 785)
2179 if($preCloseMatch && $this->mInPre
) {
2180 $this->mInPre
= false;
2182 if ($paragraphStack === false) {
2186 while ( $prefixLength ) {
2187 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2190 if ( $this->mLastSection
!= '' ) {
2191 $output .= '</' . $this->mLastSection
. '>';
2192 $this->mLastSection
= '';
2195 wfProfileOut( __METHOD__
);
2200 * Split up a string on ':', ignoring any occurences inside tags
2201 * to prevent illegal overlapping.
2202 * @param string $str the string to split
2203 * @param string &$before set to everything before the ':'
2204 * @param string &$after set to everything after the ':'
2205 * return string the position of the ':', or false if none found
2207 function findColonNoLinks($str, &$before, &$after) {
2208 wfProfileIn( __METHOD__
);
2210 $pos = strpos( $str, ':' );
2211 if( $pos === false ) {
2213 wfProfileOut( __METHOD__
);
2217 $lt = strpos( $str, '<' );
2218 if( $lt === false ||
$lt > $pos ) {
2219 // Easy; no tag nesting to worry about
2220 $before = substr( $str, 0, $pos );
2221 $after = substr( $str, $pos+
1 );
2222 wfProfileOut( __METHOD__
);
2226 // Ugly state machine to walk through avoiding tags.
2227 $state = self
::COLON_STATE_TEXT
;
2229 $len = strlen( $str );
2230 for( $i = 0; $i < $len; $i++
) {
2234 // (Using the number is a performance hack for common cases)
2235 case 0: // self::COLON_STATE_TEXT:
2238 // Could be either a <start> tag or an </end> tag
2239 $state = self
::COLON_STATE_TAGSTART
;
2244 $before = substr( $str, 0, $i );
2245 $after = substr( $str, $i +
1 );
2246 wfProfileOut( __METHOD__
);
2249 // Embedded in a tag; don't break it.
2252 // Skip ahead looking for something interesting
2253 $colon = strpos( $str, ':', $i );
2254 if( $colon === false ) {
2255 // Nothing else interesting
2256 wfProfileOut( __METHOD__
);
2259 $lt = strpos( $str, '<', $i );
2260 if( $stack === 0 ) {
2261 if( $lt === false ||
$colon < $lt ) {
2263 $before = substr( $str, 0, $colon );
2264 $after = substr( $str, $colon +
1 );
2265 wfProfileOut( __METHOD__
);
2269 if( $lt === false ) {
2270 // Nothing else interesting to find; abort!
2271 // We're nested, but there's no close tags left. Abort!
2274 // Skip ahead to next tag start
2276 $state = self
::COLON_STATE_TAGSTART
;
2279 case 1: // self::COLON_STATE_TAG:
2284 $state = self
::COLON_STATE_TEXT
;
2287 // Slash may be followed by >?
2288 $state = self
::COLON_STATE_TAGSLASH
;
2294 case 2: // self::COLON_STATE_TAGSTART:
2297 $state = self
::COLON_STATE_CLOSETAG
;
2300 $state = self
::COLON_STATE_COMMENT
;
2303 // Illegal early close? This shouldn't happen D:
2304 $state = self
::COLON_STATE_TEXT
;
2307 $state = self
::COLON_STATE_TAG
;
2310 case 3: // self::COLON_STATE_CLOSETAG:
2315 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2316 wfProfileOut( __METHOD__
);
2319 $state = self
::COLON_STATE_TEXT
;
2322 case self
::COLON_STATE_TAGSLASH
:
2324 // Yes, a self-closed tag <blah/>
2325 $state = self
::COLON_STATE_TEXT
;
2327 // Probably we're jumping the gun, and this is an attribute
2328 $state = self
::COLON_STATE_TAG
;
2331 case 5: // self::COLON_STATE_COMMENT:
2333 $state = self
::COLON_STATE_COMMENTDASH
;
2336 case self
::COLON_STATE_COMMENTDASH
:
2338 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2340 $state = self
::COLON_STATE_COMMENT
;
2343 case self
::COLON_STATE_COMMENTDASHDASH
:
2345 $state = self
::COLON_STATE_TEXT
;
2347 $state = self
::COLON_STATE_COMMENT
;
2351 throw new MWException( "State machine error in " . __METHOD__
);
2355 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2358 wfProfileOut( __METHOD__
);
2363 * Return value of a magic variable (like PAGENAME)
2367 function getVariableValue( $index, $frame=false ) {
2368 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2369 global $wgScriptPath, $wgStylePath;
2372 * Some of these require message or data lookups and can be
2373 * expensive to check many times.
2375 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2376 if ( isset( $this->mVarCache
[$index] ) ) {
2377 return $this->mVarCache
[$index];
2381 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2382 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2385 global $wgLocaltimezone;
2386 if ( isset( $wgLocaltimezone ) ) {
2387 $oldtz = date_default_timezone_get();
2388 date_default_timezone_set( $wgLocaltimezone );
2391 $localTimestamp = date( 'YmdHis', $ts );
2392 $localMonth = date( 'm', $ts );
2393 $localMonth1 = date( 'n', $ts );
2394 $localMonthName = date( 'n', $ts );
2395 $localDay = date( 'j', $ts );
2396 $localDay2 = date( 'd', $ts );
2397 $localDayOfWeek = date( 'w', $ts );
2398 $localWeek = date( 'W', $ts );
2399 $localYear = date( 'Y', $ts );
2400 $localHour = date( 'H', $ts );
2401 if ( isset( $wgLocaltimezone ) ) {
2402 date_default_timezone_set( $oldtz );
2406 case 'currentmonth':
2407 $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2409 case 'currentmonth1':
2410 $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2412 case 'currentmonthname':
2413 $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2415 case 'currentmonthnamegen':
2416 $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2418 case 'currentmonthabbrev':
2419 $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2422 $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2425 $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2428 $value = $wgContLang->formatNum( $localMonth );
2431 $value = $wgContLang->formatNum( $localMonth1 );
2433 case 'localmonthname':
2434 $value = $wgContLang->getMonthName( $localMonthName );
2436 case 'localmonthnamegen':
2437 $value = $wgContLang->getMonthNameGen( $localMonthName );
2439 case 'localmonthabbrev':
2440 $value = $wgContLang->getMonthAbbreviation( $localMonthName );
2443 $value = $wgContLang->formatNum( $localDay );
2446 $value = $wgContLang->formatNum( $localDay2 );
2449 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2452 $value = $this->mTitle
->getPartialURL();
2454 case 'fullpagename':
2455 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2457 case 'fullpagenamee':
2458 $value = $this->mTitle
->getPrefixedURL();
2461 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2463 case 'subpagenamee':
2464 $value = $this->mTitle
->getSubpageUrlForm();
2466 case 'basepagename':
2467 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2469 case 'basepagenamee':
2470 $value = wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2472 case 'talkpagename':
2473 if( $this->mTitle
->canTalk() ) {
2474 $talkPage = $this->mTitle
->getTalkPage();
2475 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2480 case 'talkpagenamee':
2481 if( $this->mTitle
->canTalk() ) {
2482 $talkPage = $this->mTitle
->getTalkPage();
2483 $value = $talkPage->getPrefixedUrl();
2488 case 'subjectpagename':
2489 $subjPage = $this->mTitle
->getSubjectPage();
2490 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2492 case 'subjectpagenamee':
2493 $subjPage = $this->mTitle
->getSubjectPage();
2494 $value = $subjPage->getPrefixedUrl();
2497 $text = $this->mTitle
->getText();
2498 $value = $this->getPipeTrickText( $text );
2501 $text = $this->mTitle
->getText();
2502 $value = wfUrlEncode( str_replace( ' ', '_', $this->getPipeTrickText( $text ) ) );
2505 // Let the edit saving system know we should parse the page
2506 // *after* a revision ID has been assigned.
2507 $this->mOutput
->setFlag( 'vary-revision' );
2508 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2509 $value = $this->mRevisionId
;
2512 // Let the edit saving system know we should parse the page
2513 // *after* a revision ID has been assigned. This is for null edits.
2514 $this->mOutput
->setFlag( 'vary-revision' );
2515 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2516 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2518 case 'revisionday2':
2519 // Let the edit saving system know we should parse the page
2520 // *after* a revision ID has been assigned. This is for null edits.
2521 $this->mOutput
->setFlag( 'vary-revision' );
2522 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2523 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2525 case 'revisionmonth':
2526 // Let the edit saving system know we should parse the page
2527 // *after* a revision ID has been assigned. This is for null edits.
2528 $this->mOutput
->setFlag( 'vary-revision' );
2529 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2530 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2532 case 'revisionyear':
2533 // Let the edit saving system know we should parse the page
2534 // *after* a revision ID has been assigned. This is for null edits.
2535 $this->mOutput
->setFlag( 'vary-revision' );
2536 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2537 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2539 case 'revisiontimestamp':
2540 // Let the edit saving system know we should parse the page
2541 // *after* a revision ID has been assigned. This is for null edits.
2542 $this->mOutput
->setFlag( 'vary-revision' );
2543 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2544 $value = $this->getRevisionTimestamp();
2546 case 'revisionuser':
2547 // Let the edit saving system know we should parse the page
2548 // *after* a revision ID has been assigned. This is for null edits.
2549 $this->mOutput
->setFlag( 'vary-revision' );
2550 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2551 $value = $this->getRevisionUser();
2554 $value = str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2557 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2560 $value = $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2563 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2565 case 'subjectspace':
2566 $value = $this->mTitle
->getSubjectNsText();
2568 case 'subjectspacee':
2569 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2571 case 'currentdayname':
2572 $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2575 $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2578 $value = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2581 $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2584 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2585 // int to remove the padding
2586 $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2589 $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2591 case 'localdayname':
2592 $value = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2595 $value = $wgContLang->formatNum( $localYear, true );
2598 $value = $wgContLang->time( $localTimestamp, false, false );
2601 $value = $wgContLang->formatNum( $localHour, true );
2604 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2605 // int to remove the padding
2606 $value = $wgContLang->formatNum( (int)$localWeek );
2609 $value = $wgContLang->formatNum( $localDayOfWeek );
2611 case 'numberofarticles':
2612 $value = $wgContLang->formatNum( SiteStats
::articles() );
2614 case 'numberoffiles':
2615 $value = $wgContLang->formatNum( SiteStats
::images() );
2617 case 'numberofusers':
2618 $value = $wgContLang->formatNum( SiteStats
::users() );
2620 case 'numberofactiveusers':
2621 $value = $wgContLang->formatNum( SiteStats
::activeUsers() );
2623 case 'numberofpages':
2624 $value = $wgContLang->formatNum( SiteStats
::pages() );
2626 case 'numberofadmins':
2627 $value = $wgContLang->formatNum( SiteStats
::numberingroup('sysop') );
2629 case 'numberofedits':
2630 $value = $wgContLang->formatNum( SiteStats
::edits() );
2632 case 'numberofviews':
2633 $value = $wgContLang->formatNum( SiteStats
::views() );
2635 case 'currenttimestamp':
2636 $value = wfTimestamp( TS_MW
, $ts );
2638 case 'localtimestamp':
2639 $value = $localTimestamp;
2641 case 'currentversion':
2642 $value = SpecialVersion
::getVersion();
2649 return $wgServerName;
2651 return $wgScriptPath;
2653 return $wgStylePath;
2654 case 'directionmark':
2655 return $wgContLang->getDirMark();
2656 case 'contentlanguage':
2657 global $wgContLanguageCode;
2658 return $wgContLanguageCode;
2661 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) )
2668 $this->mVarCache
[$index] = $value;
2674 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2678 function initialiseVariables() {
2679 wfProfileIn( __METHOD__
);
2680 $variableIDs = MagicWord
::getVariableIDs();
2681 $substIDs = MagicWord
::getSubstIDs();
2683 $this->mVariables
= new MagicWordArray( $variableIDs );
2684 $this->mSubsts
= new MagicWordArray( $substIDs );
2685 wfProfileOut( __METHOD__
);
2689 * Preprocess some wikitext and return the document tree.
2690 * This is the ghost of replace_variables().
2692 * @param string $text The text to parse
2693 * @param integer flags Bitwise combination of:
2694 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2695 * included. Default is to assume a direct page view.
2697 * The generated DOM tree must depend only on the input text and the flags.
2698 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2700 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2701 * change in the DOM tree for a given text, must be passed through the section identifier
2702 * in the section edit link and thus back to extractSections().
2704 * The output of this function is currently only cached in process memory, but a persistent
2705 * cache may be implemented at a later date which takes further advantage of these strict
2706 * dependency requirements.
2710 function preprocessToDom ( $text, $flags = 0 ) {
2711 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2716 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2718 public static function splitWhitespace( $s ) {
2719 $ltrimmed = ltrim( $s );
2720 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2721 $trimmed = rtrim( $ltrimmed );
2722 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2724 $w2 = substr( $ltrimmed, -$diff );
2728 return array( $w1, $trimmed, $w2 );
2732 * Replace magic variables, templates, and template arguments
2733 * with the appropriate text. Templates are substituted recursively,
2734 * taking care to avoid infinite loops.
2736 * Note that the substitution depends on value of $mOutputType:
2737 * self::OT_WIKI: only {{subst:}} templates
2738 * self::OT_PREPROCESS: templates but not extension tags
2739 * self::OT_HTML: all templates and extension tags
2741 * @param string $tex The text to transform
2742 * @param PPFrame $frame Object describing the arguments passed to the template.
2743 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2744 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2745 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2748 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2749 # Is there any text? Also, Prevent too big inclusions!
2750 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2753 wfProfileIn( __METHOD__
);
2755 if ( $frame === false ) {
2756 $frame = $this->getPreprocessor()->newFrame();
2757 } elseif ( !( $frame instanceof PPFrame
) ) {
2758 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2759 $frame = $this->getPreprocessor()->newCustomFrame($frame);
2762 $dom = $this->preprocessToDom( $text );
2763 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2764 $text = $frame->expand( $dom, $flags );
2766 wfProfileOut( __METHOD__
);
2770 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2771 static function createAssocArgs( $args ) {
2772 $assocArgs = array();
2774 foreach( $args as $arg ) {
2775 $eqpos = strpos( $arg, '=' );
2776 if ( $eqpos === false ) {
2777 $assocArgs[$index++
] = $arg;
2779 $name = trim( substr( $arg, 0, $eqpos ) );
2780 $value = trim( substr( $arg, $eqpos+
1 ) );
2781 if ( $value === false ) {
2784 if ( $name !== false ) {
2785 $assocArgs[$name] = $value;
2794 * Warn the user when a parser limitation is reached
2795 * Will warn at most once the user per limitation type
2797 * @param string $limitationType, should be one of:
2798 * 'expensive-parserfunction' (corresponding messages: 'expensive-parserfunction-warning', 'expensive-parserfunction-category')
2799 * 'post-expand-template-argument' (corresponding messages: 'post-expand-template-argument-warning', 'post-expand-template-argument-category')
2800 * 'post-expand-template-inclusion' (corresponding messages: 'post-expand-template-inclusion-warning', 'post-expand-template-inclusion-category')
2801 * @params int $current, $max When an explicit limit has been
2802 * exceeded, provide the values (optional)
2804 function limitationWarn( $limitationType, $current=null, $max=null) {
2805 //does no harm if $current and $max are present but are unnecessary for the message
2806 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
2807 $this->mOutput
->addWarning( $warning );
2808 $this->addTrackingCategory( "$limitationType-category" );
2812 * Return the text of a template, after recursively
2813 * replacing any variables or templates within the template.
2815 * @param array $piece The parts of the template
2816 * $piece['title']: the title, i.e. the part before the |
2817 * $piece['parts']: the parameter array
2818 * $piece['lineStart']: whether the brace was at the start of a line
2819 * @param PPFrame The current frame, contains template arguments
2820 * @return string the text of the template
2823 function braceSubstitution( $piece, $frame ) {
2824 global $wgContLang, $wgNonincludableNamespaces;
2825 wfProfileIn( __METHOD__
);
2826 wfProfileIn( __METHOD__
.'-setup' );
2829 $found = false; # $text has been filled
2830 $nowiki = false; # wiki markup in $text should be escaped
2831 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2832 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2833 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2834 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2836 # Title object, where $text came from
2839 # $part1 is the bit before the first |, and must contain only title characters.
2840 # Various prefixes will be stripped from it later.
2841 $titleWithSpaces = $frame->expand( $piece['title'] );
2842 $part1 = trim( $titleWithSpaces );
2845 # Original title text preserved for various purposes
2846 $originalTitle = $part1;
2848 # $args is a list of argument nodes, starting from index 0, not including $part1
2849 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2850 wfProfileOut( __METHOD__
.'-setup' );
2853 wfProfileIn( __METHOD__
.'-modifiers' );
2856 $substMatch = $this->mSubsts
->matchStartAndRemove( $part1 );
2858 # Possibilities for substMatch: "subst", "safesubst" or FALSE
2859 # Whether to include depends also on whether we are in the pre-save-transform
2861 # safesubst || (subst && PST) || (false && !PST) => transclude (skip the if)
2862 # (false && PST) || (subst && !PST) => return input (handled by if)
2863 if ( $substMatch != 'safesubst' && ($substMatch == 'subst' xor $this->ot
['wiki']) ) {
2864 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2871 if ( !$found && $args->getLength() == 0 ) {
2872 $id = $this->mVariables
->matchStartToEnd( $part1 );
2873 if ( $id !== false ) {
2874 $text = $this->getVariableValue( $id, $frame );
2875 if (MagicWord
::getCacheTTL($id)>-1)
2876 $this->mOutput
->mContainsOldMagic
= true;
2881 # MSG, MSGNW and RAW
2884 $mwMsgnw = MagicWord
::get( 'msgnw' );
2885 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2888 # Remove obsolete MSG:
2889 $mwMsg = MagicWord
::get( 'msg' );
2890 $mwMsg->matchStartAndRemove( $part1 );
2894 $mwRaw = MagicWord
::get( 'raw' );
2895 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2896 $forceRawInterwiki = true;
2899 wfProfileOut( __METHOD__
.'-modifiers' );
2903 wfProfileIn( __METHOD__
. '-pfunc' );
2905 $colonPos = strpos( $part1, ':' );
2906 if ( $colonPos !== false ) {
2907 # Case sensitive functions
2908 $function = substr( $part1, 0, $colonPos );
2909 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2910 $function = $this->mFunctionSynonyms
[1][$function];
2912 # Case insensitive functions
2913 $function = $wgContLang->lc( $function );
2914 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2915 $function = $this->mFunctionSynonyms
[0][$function];
2921 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2922 $initialArgs = array( &$this );
2923 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2924 if ( $flags & SFH_OBJECT_ARGS
) {
2925 # Add a frame parameter, and pass the arguments as an array
2926 $allArgs = $initialArgs;
2927 $allArgs[] = $frame;
2928 for ( $i = 0; $i < $args->getLength(); $i++
) {
2929 $funcArgs[] = $args->item( $i );
2931 $allArgs[] = $funcArgs;
2933 # Convert arguments to plain text
2934 for ( $i = 0; $i < $args->getLength(); $i++
) {
2935 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2937 $allArgs = array_merge( $initialArgs, $funcArgs );
2940 # Workaround for PHP bug 35229 and similar
2941 if ( !is_callable( $callback ) ) {
2942 wfProfileOut( __METHOD__
. '-pfunc' );
2943 wfProfileOut( __METHOD__
);
2944 throw new MWException( "Tag hook for $function is not callable\n" );
2946 $result = call_user_func_array( $callback, $allArgs );
2949 $preprocessFlags = 0;
2951 if ( is_array( $result ) ) {
2952 if ( isset( $result[0] ) ) {
2954 unset( $result[0] );
2957 // Extract flags into the local scope
2958 // This allows callers to set flags such as nowiki, found, etc.
2964 $text = $this->preprocessToDom( $text, $preprocessFlags );
2969 wfProfileOut( __METHOD__
. '-pfunc' );
2972 # Finish mangling title and then check for loops.
2973 # Set $title to a Title object and $titleText to the PDBK
2976 # Split the title into page and subpage
2978 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2979 if ($subpage !== '') {
2980 $ns = $this->mTitle
->getNamespace();
2982 $title = Title
::newFromText( $part1, $ns );
2984 $titleText = $title->getPrefixedText();
2985 # Check for language variants if the template is not found
2986 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2987 $wgContLang->findVariantLink( $part1, $title, true );
2989 # Do recursion depth check
2990 $limit = $this->mOptions
->getMaxTemplateDepth();
2991 if ( $frame->depth
>= $limit ) {
2993 $text = '<span class="error">' . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit ) . '</span>';
2998 # Load from database
2999 if ( !$found && $title ) {
3000 wfProfileIn( __METHOD__
. '-loadtpl' );
3001 if ( !$title->isExternal() ) {
3002 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
3003 $text = SpecialPage
::capturePath( $title );
3004 if ( is_string( $text ) ) {
3007 $this->disableCache();
3009 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3010 $found = false; //access denied
3011 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3013 list( $text, $title ) = $this->getTemplateDom( $title );
3014 if ( $text !== false ) {
3020 # If the title is valid but undisplayable, make a link to it
3021 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3022 $text = "[[:$titleText]]";
3025 } elseif ( $title->isTrans() ) {
3026 // Interwiki transclusion
3027 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3028 $text = $this->interwikiTransclude( $title, 'render' );
3031 $text = $this->interwikiTransclude( $title, 'raw' );
3032 // Preprocess it like a template
3033 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3039 # Do infinite loop check
3040 # This has to be done after redirect resolution to avoid infinite loops via redirects
3041 if ( !$frame->loopCheck( $title ) ) {
3043 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3044 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3046 wfProfileOut( __METHOD__
. '-loadtpl' );
3049 # If we haven't found text to substitute by now, we're done
3050 # Recover the source wikitext and return it
3052 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3053 wfProfileOut( __METHOD__
);
3054 return array( 'object' => $text );
3057 # Expand DOM-style return values in a child frame
3058 if ( $isChildObj ) {
3059 # Clean up argument array
3060 $newFrame = $frame->newChild( $args, $title );
3063 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3064 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3065 # Expansion is eligible for the empty-frame cache
3066 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3067 $text = $this->mTplExpandCache
[$titleText];
3069 $text = $newFrame->expand( $text );
3070 $this->mTplExpandCache
[$titleText] = $text;
3073 # Uncached expansion
3074 $text = $newFrame->expand( $text );
3077 if ( $isLocalObj && $nowiki ) {
3078 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3079 $isLocalObj = false;
3082 # Replace raw HTML by a placeholder
3083 # Add a blank line preceding, to prevent it from mucking up
3084 # immediately preceding headings
3086 $text = "\n\n" . $this->insertStripItem( $text );
3088 # Escape nowiki-style return values
3089 elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3090 $text = wfEscapeWikiText( $text );
3092 # Bug 529: if the template begins with a table or block-level
3093 # element, it should be treated as beginning a new line.
3094 # This behaviour is somewhat controversial.
3095 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3096 $text = "\n" . $text;
3099 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3100 # Error, oversize inclusion
3101 $text = "[[$originalTitle]]" .
3102 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3103 $this->limitationWarn( 'post-expand-template-inclusion' );
3106 if ( $isLocalObj ) {
3107 $ret = array( 'object' => $text );
3109 $ret = array( 'text' => $text );
3112 wfProfileOut( __METHOD__
);
3117 * Get the semi-parsed DOM representation of a template with a given title,
3118 * and its redirect destination title. Cached.
3120 function getTemplateDom( $title ) {
3121 $cacheTitle = $title;
3122 $titleText = $title->getPrefixedDBkey();
3124 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3125 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3126 $title = Title
::makeTitle( $ns, $dbk );
3127 $titleText = $title->getPrefixedDBkey();
3129 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3130 return array( $this->mTplDomCache
[$titleText], $title );
3133 // Cache miss, go to the database
3134 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3136 if ( $text === false ) {
3137 $this->mTplDomCache
[$titleText] = false;
3138 return array( false, $title );
3141 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3142 $this->mTplDomCache
[ $titleText ] = $dom;
3144 if (! $title->equals($cacheTitle)) {
3145 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3146 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3149 return array( $dom, $title );
3153 * Fetch the unparsed text of a template and register a reference to it.
3155 function fetchTemplateAndTitle( $title ) {
3156 $templateCb = $this->mOptions
->getTemplateCallback();
3157 $stuff = call_user_func( $templateCb, $title, $this );
3158 $text = $stuff['text'];
3159 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3160 if ( isset( $stuff['deps'] ) ) {
3161 foreach ( $stuff['deps'] as $dep ) {
3162 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3165 return array($text,$finalTitle);
3168 function fetchTemplate( $title ) {
3169 $rv = $this->fetchTemplateAndTitle($title);
3174 * Static function to get a template
3175 * Can be overridden via ParserOptions::setTemplateCallback().
3177 static function statelessFetchTemplate( $title, $parser=false ) {
3178 $text = $skip = false;
3179 $finalTitle = $title;
3182 // Loop to fetch the article, with up to 1 redirect
3183 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3184 # Give extensions a chance to select the revision instead
3185 $id = false; // Assume current
3186 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3192 'page_id' => $title->getArticleID(),
3196 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3197 $rev_id = $rev ?
$rev->getId() : 0;
3198 // If there is no current revision, there is no page
3199 if( $id === false && !$rev ) {
3200 $linkCache = LinkCache
::singleton();
3201 $linkCache->addBadLinkObj( $title );
3206 'page_id' => $title->getArticleID(),
3207 'rev_id' => $rev_id );
3210 $text = $rev->getText();
3211 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3213 $message = $wgContLang->lcfirst( $title->getText() );
3214 $text = wfMsgForContentNoTrans( $message );
3215 if( wfEmptyMsg( $message, $text ) ) {
3222 if ( $text === false ) {
3226 $finalTitle = $title;
3227 $title = Title
::newFromRedirect( $text );
3231 'finalTitle' => $finalTitle,
3236 * Transclude an interwiki link.
3238 function interwikiTransclude( $title, $action ) {
3239 global $wgEnableScaryTranscluding;
3241 if (!$wgEnableScaryTranscluding)
3242 return wfMsg('scarytranscludedisabled');
3244 $url = $title->getFullUrl( "action=$action" );
3246 if (strlen($url) > 255)
3247 return wfMsg('scarytranscludetoolong');
3248 return $this->fetchScaryTemplateMaybeFromCache($url);
3251 function fetchScaryTemplateMaybeFromCache($url) {
3252 global $wgTranscludeCacheExpiry;
3253 $dbr = wfGetDB(DB_SLAVE
);
3254 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3255 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3256 array('tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3258 return $obj->tc_contents
;
3261 $text = Http
::get($url);
3263 return wfMsg('scarytranscludefailed', $url);
3265 $dbw = wfGetDB(DB_MASTER
);
3266 $dbw->replace('transcache', array('tc_url'), array(
3268 'tc_time' => $dbw->timestamp( time() ),
3269 'tc_contents' => $text));
3275 * Triple brace replacement -- used for template arguments
3278 function argSubstitution( $piece, $frame ) {
3279 wfProfileIn( __METHOD__
);
3282 $parts = $piece['parts'];
3283 $nameWithSpaces = $frame->expand( $piece['title'] );
3284 $argName = trim( $nameWithSpaces );
3286 $text = $frame->getArgument( $argName );
3287 if ( $text === false && $parts->getLength() > 0
3291 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3294 # No match in frame, use the supplied default
3295 $object = $parts->item( 0 )->getChildren();
3297 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3298 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3299 $this->limitationWarn( 'post-expand-template-argument' );
3302 if ( $text === false && $object === false ) {
3304 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3306 if ( $error !== false ) {
3309 if ( $object !== false ) {
3310 $ret = array( 'object' => $object );
3312 $ret = array( 'text' => $text );
3315 wfProfileOut( __METHOD__
);
3320 * Return the text to be used for a given extension tag.
3321 * This is the ghost of strip().
3323 * @param array $params Associative array of parameters:
3324 * name PPNode for the tag name
3325 * attr PPNode for unparsed text where tag attributes are thought to be
3326 * attributes Optional associative array of parsed attributes
3327 * inner Contents of extension element
3328 * noClose Original text did not have a close tag
3329 * @param PPFrame $frame
3331 function extensionSubstitution( $params, $frame ) {
3332 global $wgRawHtml, $wgContLang;
3334 $name = $frame->expand( $params['name'] );
3335 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3336 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3337 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3339 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3340 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3341 if ( $isFunctionTag ) {
3342 $markerType = 'none';
3344 $markerType = 'general';
3346 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3347 $name = strtolower( $name );
3348 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3349 if ( isset( $params['attributes'] ) ) {
3350 $attributes = $attributes +
$params['attributes'];
3353 if( isset( $this->mTagHooks
[$name] ) ) {
3354 # Workaround for PHP bug 35229 and similar
3355 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3356 throw new MWException( "Tag hook for $name is not callable\n" );
3358 $output = call_user_func_array( $this->mTagHooks
[$name],
3359 array( $content, $attributes, $this, $frame ) );
3360 } elseif( isset( $this->mFunctionTagHooks
[$name] ) ) {
3361 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3362 if( !is_callable( $callback ) )
3363 throw new MWException( "Tag hook for $name is not callable\n" );
3365 $output = call_user_func_array( $callback,
3366 array( &$this, $frame, $content, $attributes ) );
3368 $output = '<span class="error">Invalid tag extension name: ' .
3369 htmlspecialchars( $name ) . '</span>';
3372 if ( is_array( $output ) ) {
3373 // Extract flags to local scope (to override $markerType)
3375 $output = $flags[0];
3380 if ( is_null( $attrText ) ) {
3383 if ( isset( $params['attributes'] ) ) {
3384 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3385 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3386 htmlspecialchars( $attrValue ) . '"';
3389 if ( $content === null ) {
3390 $output = "<$name$attrText/>";
3392 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3393 $output = "<$name$attrText>$content$close";
3397 if( $markerType === 'none' ) {
3399 } elseif ( $markerType === 'nowiki' ) {
3400 $this->mStripState
->nowiki
->setPair( $marker, $output );
3401 } elseif ( $markerType === 'general' ) {
3402 $this->mStripState
->general
->setPair( $marker, $output );
3404 throw new MWException( __METHOD__
.': invalid marker type' );
3410 * Increment an include size counter
3412 * @param string $type The type of expansion
3413 * @param integer $size The size of the text
3414 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3416 function incrementIncludeSize( $type, $size ) {
3417 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3420 $this->mIncludeSizes
[$type] +
= $size;
3426 * Increment the expensive function count
3428 * @return boolean False if the limit has been exceeded
3430 function incrementExpensiveFunctionCount() {
3431 global $wgExpensiveParserFunctionLimit;
3432 $this->mExpensiveFunctionCount++
;
3433 if($this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit) {
3440 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3441 * Fills $this->mDoubleUnderscores, returns the modified text
3443 function doDoubleUnderscore( $text ) {
3444 wfProfileIn( __METHOD__
);
3446 // The position of __TOC__ needs to be recorded
3447 $mw = MagicWord
::get( 'toc' );
3448 if( $mw->match( $text ) ) {
3449 $this->mShowToc
= true;
3450 $this->mForceTocPosition
= true;
3452 // Set a placeholder. At the end we'll fill it in with the TOC.
3453 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3455 // Only keep the first one.
3456 $text = $mw->replace( '', $text );
3459 // Now match and remove the rest of them
3460 $mwa = MagicWord
::getDoubleUnderscoreArray();
3461 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3463 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3464 $this->mOutput
->mNoGallery
= true;
3466 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3467 $this->mShowToc
= false;
3469 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3470 $this->mOutput
->setProperty( 'hiddencat', 'y' );
3471 $this->addTrackingCategory( 'hidden-category-category' );
3473 # (bug 8068) Allow control over whether robots index a page.
3475 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3476 # is not desirable, the last one on the page should win.
3477 if( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3478 $this->mOutput
->setIndexPolicy( 'noindex' );
3479 $this->addTrackingCategory( 'noindex-category' );
3481 if( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ){
3482 $this->mOutput
->setIndexPolicy( 'index' );
3483 $this->addTrackingCategory( 'index-category' );
3486 wfProfileOut( __METHOD__
);
3491 * Add a tracking category, getting the title from a system message,
3492 * or print a debug message if the title is invalid.
3493 * @param $msg String message key
3494 * @return Bool whether the addition was successful
3496 protected function addTrackingCategory( $msg ){
3497 $cat = wfMsgForContent( $msg );
3499 # Allow tracking categories to be disabled by setting them to "-"
3500 if( $cat === '-' ) return false;
3502 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3503 if ( $containerCategory ) {
3504 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3507 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3513 * This function accomplishes several tasks:
3514 * 1) Auto-number headings if that option is enabled
3515 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3516 * 3) Add a Table of contents on the top for users who have enabled the option
3517 * 4) Auto-anchor headings
3519 * It loops through all headlines, collects the necessary data, then splits up the
3520 * string and re-inserts the newly formatted headlines.
3522 * @param string $text
3523 * @param string $origText Original, untouched wikitext
3524 * @param boolean $isMain
3527 function formatHeadings( $text, $origText, $isMain=true ) {
3528 global $wgMaxTocLevel, $wgContLang, $wgHtml5, $wgExperimentalHtmlIds;
3530 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3531 $showEditLink = $this->mOptions
->getEditSection();
3533 // Do not call quickUserCan unless necessary
3534 if( $showEditLink && !$this->mTitle
->quickUserCan( 'edit' ) ) {
3538 # Inhibit editsection links if requested in the page
3539 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ||
$this->mOptions
->getIsPrintable() ) {
3543 # Get all headlines for numbering them and adding funky stuff like [edit]
3544 # links - this is for later, but we need the number of headlines right now
3546 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3548 # if there are fewer than 4 headlines in the article, do not show TOC
3549 # unless it's been explicitly enabled.
3550 $enoughToc = $this->mShowToc
&&
3551 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3553 # Allow user to stipulate that a page should have a "new section"
3554 # link added via __NEWSECTIONLINK__
3555 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3556 $this->mOutput
->setNewSection( true );
3559 # Allow user to remove the "new section"
3560 # link via __NONEWSECTIONLINK__
3561 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3562 $this->mOutput
->hideNewSection( true );
3565 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3566 # override above conditions and always show TOC above first header
3567 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3568 $this->mShowToc
= true;
3572 # We need this to perform operations on the HTML
3573 $sk = $this->mOptions
->getSkin();
3579 # Ugh .. the TOC should have neat indentation levels which can be
3580 # passed to the skin functions. These are determined here
3584 $sublevelCount = array();
3585 $levelCount = array();
3591 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3592 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3593 $oldType = $this->mOutputType
;
3594 $this->setOutputType( self
::OT_WIKI
);
3595 $frame = $this->getPreprocessor()->newFrame();
3596 $root = $this->preprocessToDom( $origText );
3597 $node = $root->getFirstChild();
3601 foreach( $matches[3] as $headline ) {
3602 $isTemplate = false;
3604 $sectionIndex = false;
3606 $markerMatches = array();
3607 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3608 $serial = $markerMatches[1];
3609 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3610 $isTemplate = ($titleText != $baseTitleText);
3611 $headline = preg_replace("/^$markerRegex/", "", $headline);
3615 $prevlevel = $level;
3616 $prevtoclevel = $toclevel;
3618 $level = $matches[1][$headlineCount];
3620 if ( $level > $prevlevel ) {
3621 # Increase TOC level
3623 $sublevelCount[$toclevel] = 0;
3624 if( $toclevel<$wgMaxTocLevel ) {
3625 $prevtoclevel = $toclevel;
3626 $toc .= $sk->tocIndent();
3630 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3631 # Decrease TOC level, find level to jump to
3633 for ($i = $toclevel; $i > 0; $i--) {
3634 if ( $levelCount[$i] == $level ) {
3635 # Found last matching level
3639 elseif ( $levelCount[$i] < $level ) {
3640 # Found first matching level below current level
3645 if( $i == 0 ) $toclevel = 1;
3646 if( $toclevel<$wgMaxTocLevel ) {
3647 if($prevtoclevel < $wgMaxTocLevel) {
3648 # Unindent only if the previous toc level was shown :p
3649 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3650 $prevtoclevel = $toclevel;
3652 $toc .= $sk->tocLineEnd();
3657 # No change in level, end TOC line
3658 if( $toclevel<$wgMaxTocLevel ) {
3659 $toc .= $sk->tocLineEnd();
3663 $levelCount[$toclevel] = $level;
3665 # count number of headlines for each level
3666 @$sublevelCount[$toclevel]++
;
3668 for( $i = 1; $i <= $toclevel; $i++
) {
3669 if( !empty( $sublevelCount[$i] ) ) {
3673 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3678 # The safe header is a version of the header text safe to use for links
3679 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3680 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3682 # Remove link placeholders by the link text.
3683 # <!--LINK number-->
3685 # link text with suffix
3686 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3688 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3689 $tocline = preg_replace(
3690 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3694 $tocline = trim( $tocline );
3696 # For the anchor, strip out HTML-y stuff period
3697 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3698 $safeHeadline = preg_replace( '/[ _]+/', ' ', $safeHeadline );
3699 $safeHeadline = trim( $safeHeadline );
3701 # Save headline for section edit hint before it's escaped
3702 $headlineHint = $safeHeadline;
3704 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
3705 # For reverse compatibility, provide an id that's
3706 # HTML4-compatible, like we used to.
3708 # It may be worth noting, academically, that it's possible for
3709 # the legacy anchor to conflict with a non-legacy headline
3710 # anchor on the page. In this case likely the "correct" thing
3711 # would be to either drop the legacy anchors or make sure
3712 # they're numbered first. However, this would require people
3713 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3714 # manually, so let's not bother worrying about it.
3715 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
3716 array( 'noninitial', 'legacy' ) );
3717 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3719 if ( $legacyHeadline == $safeHeadline ) {
3720 # No reason to have both (in fact, we can't)
3721 $legacyHeadline = false;
3724 $legacyHeadline = false;
3725 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
3729 # HTML names must be case-insensitively unique (bug 10721). FIXME:
3730 # Does this apply to Unicode characters? Because we aren't
3731 # handling those here.
3732 $arrayKey = strtolower( $safeHeadline );
3733 if ( $legacyHeadline === false ) {
3734 $legacyArrayKey = false;
3736 $legacyArrayKey = strtolower( $legacyHeadline );
3739 # count how many in assoc. array so we can track dupes in anchors
3740 if ( isset( $refers[$arrayKey] ) ) {
3741 $refers[$arrayKey]++
;
3743 $refers[$arrayKey] = 1;
3745 if ( isset( $refers[$legacyArrayKey] ) ) {
3746 $refers[$legacyArrayKey]++
;
3748 $refers[$legacyArrayKey] = 1;
3751 # Don't number the heading if it is the only one (looks silly)
3752 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3753 # the two are different if the line contains a link
3754 $headline = $numbering . ' ' . $headline;
3757 # Create the anchor for linking from the TOC to the section
3758 $anchor = $safeHeadline;
3759 $legacyAnchor = $legacyHeadline;
3760 if ( $refers[$arrayKey] > 1 ) {
3761 $anchor .= '_' . $refers[$arrayKey];
3763 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3764 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3766 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3767 $toc .= $sk->tocLine($anchor, $tocline,
3768 $numbering, $toclevel, ($isTemplate ?
false : $sectionIndex));
3771 # Add the section to the section tree
3772 # Find the DOM node for this header
3773 while ( $node && !$isTemplate ) {
3774 if ( $node->getName() === 'h' ) {
3775 $bits = $node->splitHeading();
3776 if ( $bits['i'] == $sectionIndex )
3779 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
3780 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
3781 $node = $node->getNextSibling();
3784 'toclevel' => $toclevel,
3787 'number' => $numbering,
3788 'index' => ($isTemplate ?
'T-' : '' ) . $sectionIndex,
3789 'fromtitle' => $titleText,
3790 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
3791 'anchor' => $anchor,
3794 # give headline the correct <h#> tag
3795 if( $showEditLink && $sectionIndex !== false ) {
3797 # Put a T flag in the section identifier, to indicate to extractSections()
3798 # that sections inside <includeonly> should be counted.
3799 $editlink = $sk->doEditSectionLink(Title
::newFromText( $titleText ), "T-$sectionIndex");
3801 $editlink = $sk->doEditSectionLink($this->mTitle
, $sectionIndex, $headlineHint);
3806 $head[$headlineCount] = $sk->makeHeadline( $level,
3807 $matches['attrib'][$headlineCount], $anchor, $headline,
3808 $editlink, $legacyAnchor );
3813 $this->setOutputType( $oldType );
3815 # Never ever show TOC if no headers
3816 if( $numVisible < 1 ) {
3821 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3822 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3824 $toc = $sk->tocList( $toc );
3825 $this->mOutput
->setTOCHTML( $toc );
3829 $this->mOutput
->setSections( $tocraw );
3832 # split up and insert constructed headlines
3834 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3837 foreach( $blocks as $block ) {
3838 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3839 # This is the [edit] link that appears for the top block of text when
3840 # section editing is enabled
3842 # Disabled because it broke block formatting
3843 # For example, a bullet point in the top line
3844 # $full .= $sk->editSectionLink(0);
3847 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3848 # Top anchor now in skin
3852 if( !empty( $head[$i] ) ) {
3857 if( $this->mForceTocPosition
) {
3858 return str_replace( '<!--MWTOC-->', $toc, $full );
3865 * Merge $tree2 into $tree1 by replacing the section with index
3866 * $section in $tree1 and its descendants with the sections in $tree2.
3867 * Note that in the returned section tree, only the 'index' and
3868 * 'byteoffset' fields are guaranteed to be correct.
3869 * @param $tree1 array Section tree from ParserOutput::getSectons()
3870 * @param $tree2 array Section tree
3871 * @param $section int Section index
3872 * @param $title Title Title both section trees come from
3873 * @param $len2 int Length of the original wikitext for $tree2
3874 * @return array Merged section tree
3876 public static function mergeSectionTrees( $tree1, $tree2, $section, $title, $len2 ) {
3879 $targetLevel = false;
3883 $numbering = array( 0 );
3884 $titletext = $title->getPrefixedDBkey();
3885 foreach ( $tree1 as $s ) {
3886 if ( $targetLevel !== false ) {
3887 if ( $s['level'] <= $targetLevel )
3888 // We've skipped enough
3889 $targetLevel = false;
3893 if ( $s['index'] != $section ||
3894 $s['fromtitle'] != $titletext ) {
3895 self
::incrementNumbering( $numbering,
3896 $s['toclevel'], $lastLevel );
3898 // Rewrite index, byteoffset and number
3899 if ( $s['fromtitle'] == $titletext ) {
3900 $s['index'] = $nextIndex++
;
3902 $s['byteoffset'] +
= $len2;
3904 $s['number'] = implode( '.', array_map(
3905 array( $wgContLang, 'formatnum' ),
3907 $lastLevel = $s['toclevel'];
3910 // We're at $section
3911 // Insert sections from $tree2 here
3912 foreach ( $tree2 as $s2 ) {
3913 // Rewrite the fields in $s2
3914 // before inserting it
3915 $s2['toclevel'] +
= $s['toclevel'] - 1;
3916 $s2['level'] +
= $s['level'] - 1;
3917 $s2['index'] = $nextIndex++
;
3918 $s2['byteoffset'] +
= $s['byteoffset'];
3920 self
::incrementNumbering( $numbering,
3921 $s2['toclevel'], $lastLevel );
3922 $s2['number'] = implode( '.', array_map(
3923 array( $wgContLang, 'formatnum' ),
3925 $lastLevel = $s2['toclevel'];
3928 // Skip all descendants of $section in $tree1
3929 $targetLevel = $s['level'];
3937 * Increment a section number. Helper function for mergeSectionTrees()
3938 * @param $number array Array representing a section number
3939 * @param $level int Current TOC level (depth)
3940 * @param $lastLevel int Level of previous TOC entry
3942 private static function incrementNumbering( &$number, $level, $lastLevel ) {
3943 if ( $level > $lastLevel )
3944 $number[$level - 1] = 1;
3945 else if ( $level < $lastLevel ) {
3946 foreach ( $number as $key => $unused )
3947 if ( $key >= $level )
3948 unset( $number[$key] );
3949 $number[$level - 1]++
;
3951 $number[$level - 1]++
;
3955 * Transform wiki markup when saving a page by doing \r\n -> \n
3956 * conversion, substitting signatures, {{subst:}} templates, etc.
3958 * @param string $text the text to transform
3959 * @param Title &$title the Title object for the current article
3960 * @param User $user the User object describing the current user
3961 * @param ParserOptions $options parsing options
3962 * @param bool $clearState whether to clear the parser state first
3963 * @return string the altered wiki markup
3966 function preSaveTransform( $text, Title
$title, $user, $options, $clearState = true ) {
3967 $this->mOptions
= $options;
3968 $this->setTitle( $title );
3969 $this->setOutputType( self
::OT_WIKI
);
3971 if ( $clearState ) {
3972 $this->clearState();
3978 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3979 $text = $this->pstPass2( $text, $user );
3980 $text = $this->mStripState
->unstripBoth( $text );
3985 * Pre-save transform helper function
3988 function pstPass2( $text, $user ) {
3989 global $wgContLang, $wgLocaltimezone;
3991 /* Note: This is the timestamp saved as hardcoded wikitext to
3992 * the database, we use $wgContLang here in order to give
3993 * everyone the same signature and use the default one rather
3994 * than the one selected in each user's preferences.
3996 * (see also bug 12815)
3998 $ts = $this->mOptions
->getTimestamp();
3999 if ( isset( $wgLocaltimezone ) ) {
4000 $tz = $wgLocaltimezone;
4002 $tz = date_default_timezone_get();
4005 $unixts = wfTimestamp( TS_UNIX
, $ts );
4006 $oldtz = date_default_timezone_get();
4007 date_default_timezone_set( $tz );
4008 $ts = date( 'YmdHis', $unixts );
4009 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4011 /* Allow translation of timezones trough wiki. date() can return
4012 * whatever crap the system uses, localised or not, so we cannot
4013 * ship premade translations.
4015 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4016 $value = wfMsgForContent( $key );
4017 if ( !wfEmptyMsg( $key, $value ) ) $tzMsg = $value;
4019 date_default_timezone_set( $oldtz );
4021 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4023 # Variable replacement
4024 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4025 $text = $this->replaceVariables( $text );
4028 $sigText = $this->getUserSig( $user );
4029 $text = strtr( $text, array(
4031 '~~~~' => "$sigText $d",
4035 # Links of the form [[|<blah>]] or [[<blah>|]] perform pipe tricks
4036 # Note this only allows the # in the one position it works.
4037 global $wgLegalTitleChars;
4038 $pipeTrickRe = "/\[\[(?:(\\|)([$wgLegalTitleChars]+)|(#?[$wgLegalTitleChars]+)\\|)\]\]/";
4039 $text = preg_replace_callback( $pipeTrickRe, array( $this, 'pstPipeTrickCallback' ), $text );
4041 # Trim trailing whitespace
4042 $text = rtrim( $text );
4048 * Called from pstPass2 to perform the pipe trick on links.
4049 * Original was either [[|text]] or [[link|]]
4051 * @param Array ("|" or "", text, link) $m
4053 function pstPipeTrickCallback( $m )
4055 if( $m[1] ) { # [[|<blah>]]
4057 $link = $this->getPipeTrickLink( $text );
4058 } else { # [[<blah>|]]
4060 $text = $this->getPipeTrickText( $link );
4063 return $link === $text ?
"[[$link]]" : "[[$link|$text]]";
4067 * Fetch the user's signature text, if any, and normalize to
4068 * validated, ready-to-insert wikitext.
4069 * If you have pre-fetched the nickname or the fancySig option, you can
4070 * specify them here to save a database query.
4075 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4076 global $wgMaxSigChars;
4078 $username = $user->getName();
4080 // If not given, retrieve from the user object.
4081 if ( $nickname === false )
4082 $nickname = $user->getOption( 'nickname' );
4084 if ( is_null( $fancySig ) )
4085 $fancySig = $user->getBoolOption( 'fancysig' );
4087 $nickname = $nickname == null ?
$username : $nickname;
4089 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4090 $nickname = $username;
4091 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4092 } elseif( $fancySig !== false ) {
4093 # Sig. might contain markup; validate this
4094 if( $this->validateSig( $nickname ) !== false ) {
4095 # Validated; clean up (if needed) and return it
4096 return $this->cleanSig( $nickname, true );
4098 # Failed to validate; fall back to the default
4099 $nickname = $username;
4100 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4104 // Make sure nickname doesnt get a sig in a sig
4105 $nickname = $this->cleanSigInSig( $nickname );
4107 # If we're still here, make it a link to the user page
4108 $userText = wfEscapeWikiText( $username );
4109 $nickText = wfEscapeWikiText( $nickname );
4110 if ( $user->isAnon() ) {
4111 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4113 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4118 * Check that the user's signature contains no bad XML
4120 * @param string $text
4121 * @return mixed An expanded string, or false if invalid.
4123 function validateSig( $text ) {
4124 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4128 * Clean up signature text
4130 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4131 * 2) Substitute all transclusions
4133 * @param string $text
4134 * @param $parsing Whether we're cleaning (preferences save) or parsing
4135 * @return string Signature text
4137 function cleanSig( $text, $parsing = false ) {
4140 $this->clearState();
4141 $this->setTitle( $wgTitle );
4142 $this->mOptions
= new ParserOptions
;
4143 $this->setOutputType
= self
::OT_PREPROCESS
;
4146 # Option to disable this feature
4147 if ( !$this->mOptions
->getCleanSignatures() ) {
4151 # FIXME: regex doesn't respect extension tags or nowiki
4152 # => Move this logic to braceSubstitution()
4153 $substWord = MagicWord
::get( 'subst' );
4154 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4155 $substText = '{{' . $substWord->getSynonym( 0 );
4157 $text = preg_replace( $substRegex, $substText, $text );
4158 $text = $this->cleanSigInSig( $text );
4159 $dom = $this->preprocessToDom( $text );
4160 $frame = $this->getPreprocessor()->newFrame();
4161 $text = $frame->expand( $dom );
4164 $text = $this->mStripState
->unstripBoth( $text );
4171 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4172 * @param string $text
4173 * @return string Signature text with /~{3,5}/ removed
4175 function cleanSigInSig( $text ) {
4176 $text = preg_replace( '/~{3,5}/', '', $text );
4181 * Set up some variables which are usually set up in parse()
4182 * so that an external function can call some class members with confidence
4185 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
4186 $this->setTitle( $title );
4187 $this->mOptions
= $options;
4188 $this->setOutputType( $outputType );
4189 if ( $clearState ) {
4190 $this->clearState();
4195 * Wrapper for preprocess()
4197 * @param string $text the text to preprocess
4198 * @param ParserOptions $options options
4202 function transformMsg( $text, $options ) {
4204 static $executing = false;
4206 # Guard against infinite recursion
4212 wfProfileIn(__METHOD__
);
4213 $text = $this->preprocess( $text, $wgTitle, $options );
4216 wfProfileOut(__METHOD__
);
4221 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4222 * The callback should have the following form:
4223 * function myParserHook( $text, $params, &$parser ) { ... }
4225 * Transform and return $text. Use $parser for any required context, e.g. use
4226 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4230 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
4231 * @param mixed $callback The callback function (and object) to use for the tag
4233 * @return The old value of the mTagHooks array associated with the hook
4235 function setHook( $tag, $callback ) {
4236 $tag = strtolower( $tag );
4237 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4238 $this->mTagHooks
[$tag] = $callback;
4239 if( !in_array( $tag, $this->mStripList
) ) {
4240 $this->mStripList
[] = $tag;
4246 function setTransparentTagHook( $tag, $callback ) {
4247 $tag = strtolower( $tag );
4248 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4249 $this->mTransparentTagHooks
[$tag] = $callback;
4255 * Remove all tag hooks
4257 function clearTagHooks() {
4258 $this->mTagHooks
= array();
4259 $this->mStripList
= $this->mDefaultStripList
;
4263 * Create a function, e.g. {{sum:1|2|3}}
4264 * The callback function should have the form:
4265 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4267 * Or with SFH_OBJECT_ARGS:
4268 * function myParserFunction( $parser, $frame, $args ) { ... }
4270 * The callback may either return the text result of the function, or an array with the text
4271 * in element 0, and a number of flags in the other elements. The names of the flags are
4272 * specified in the keys. Valid flags are:
4273 * found The text returned is valid, stop processing the template. This
4275 * nowiki Wiki markup in the return value should be escaped
4276 * isHTML The returned text is HTML, armour it against wikitext transformation
4280 * @param string $id The magic word ID
4281 * @param mixed $callback The callback function (and object) to use
4282 * @param integer $flags a combination of the following flags:
4283 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4285 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4286 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4287 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4288 * the arguments, and to control the way they are expanded.
4290 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4291 * arguments, for instance:
4292 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4294 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4295 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4296 * working if/when this is changed.
4298 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4301 * Please read the documentation in includes/parser/Preprocessor.php for more information
4302 * about the methods available in PPFrame and PPNode.
4304 * @return The old callback function for this name, if any
4306 function setFunctionHook( $id, $callback, $flags = 0 ) {
4309 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4310 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4312 # Add to function cache
4313 $mw = MagicWord
::get( $id );
4315 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4317 $synonyms = $mw->getSynonyms();
4318 $sensitive = intval( $mw->isCaseSensitive() );
4320 foreach ( $synonyms as $syn ) {
4322 if ( !$sensitive ) {
4323 $syn = $wgContLang->lc( $syn );
4326 if ( !( $flags & SFH_NO_HASH
) ) {
4329 # Remove trailing colon
4330 if ( substr( $syn, -1, 1 ) === ':' ) {
4331 $syn = substr( $syn, 0, -1 );
4333 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4339 * Get all registered function hook identifiers
4343 function getFunctionHooks() {
4344 return array_keys( $this->mFunctionHooks
);
4348 * Create a tag function, e.g. <test>some stuff</test>.
4349 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4350 * Unlike parser functions, their content is not preprocessed.
4352 function setFunctionTagHook( $tag, $callback, $flags ) {
4353 $tag = strtolower( $tag );
4354 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4355 $this->mFunctionTagHooks
[$tag] : null;
4356 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4358 if( !in_array( $tag, $this->mStripList
) ) {
4359 $this->mStripList
[] = $tag;
4366 * FIXME: update documentation. makeLinkObj() is deprecated.
4367 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4368 * Placeholders created in Skin::makeLinkObj()
4369 * Returns an array of link CSS classes, indexed by PDBK.
4371 function replaceLinkHolders( &$text, $options = 0 ) {
4372 return $this->mLinkHolders
->replace( $text );
4376 * Replace <!--LINK--> link placeholders with plain text of links
4377 * (not HTML-formatted).
4378 * @param string $text
4381 function replaceLinkHoldersText( $text ) {
4382 return $this->mLinkHolders
->replaceText( $text );
4386 * Renders an image gallery from a text with one line per image.
4387 * text labels may be given by using |-style alternative text. E.g.
4388 * Image:one.jpg|The number "1"
4389 * Image:tree.jpg|A tree
4390 * given as text will return the HTML of a gallery with two images,
4391 * labeled 'The number "1"' and
4394 function renderImageGallery( $text, $params ) {
4395 $ig = new ImageGallery();
4396 $ig->setContextTitle( $this->mTitle
);
4397 $ig->setShowBytes( false );
4398 $ig->setShowFilename( false );
4399 $ig->setParser( $this );
4400 $ig->setHideBadImages();
4401 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4402 $ig->useSkin( $this->mOptions
->getSkin() );
4403 $ig->mRevisionId
= $this->mRevisionId
;
4405 if( isset( $params['caption'] ) ) {
4406 $caption = $params['caption'];
4407 $caption = htmlspecialchars( $caption );
4408 $caption = $this->replaceInternalLinks( $caption );
4409 $ig->setCaptionHtml( $caption );
4411 if( isset( $params['perrow'] ) ) {
4412 $ig->setPerRow( $params['perrow'] );
4414 if( isset( $params['widths'] ) ) {
4415 $ig->setWidths( $params['widths'] );
4417 if( isset( $params['heights'] ) ) {
4418 $ig->setHeights( $params['heights'] );
4421 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4423 $lines = StringUtils
::explode( "\n", $text );
4424 foreach ( $lines as $line ) {
4425 # match lines like these:
4426 # Image:someimage.jpg|This is some image
4428 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4430 if ( count( $matches ) == 0 ) {
4434 if ( strpos( $matches[0], '%' ) !== false )
4435 $matches[1] = urldecode( $matches[1] );
4436 $tp = Title
::newFromText( $matches[1]/*, NS_FILE*/ );
4438 if( is_null( $nt ) ) {
4439 # Bogus title. Ignore these so we don't bomb out later.
4442 if ( isset( $matches[3] ) ) {
4443 $label = $matches[3];
4448 $html = $this->recursiveTagParse( trim( $label ) );
4450 $ig->add( $nt, $html );
4452 # Only add real images (bug #5586)
4453 if ( $nt->getNamespace() == NS_FILE
) {
4454 $this->mOutput
->addImage( $nt->getDBkey() );
4457 return $ig->toHTML();
4460 function getImageParams( $handler ) {
4462 $handlerClass = get_class( $handler );
4466 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4467 // Initialise static lists
4468 static $internalParamNames = array(
4469 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4470 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4471 'bottom', 'text-bottom' ),
4472 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4473 'upright', 'border', 'link', 'alt' ),
4475 static $internalParamMap;
4476 if ( !$internalParamMap ) {
4477 $internalParamMap = array();
4478 foreach ( $internalParamNames as $type => $names ) {
4479 foreach ( $names as $name ) {
4480 $magicName = str_replace( '-', '_', "img_$name" );
4481 $internalParamMap[$magicName] = array( $type, $name );
4486 // Add handler params
4487 $paramMap = $internalParamMap;
4489 $handlerParamMap = $handler->getParamMap();
4490 foreach ( $handlerParamMap as $magic => $paramName ) {
4491 $paramMap[$magic] = array( 'handler', $paramName );
4494 $this->mImageParams
[$handlerClass] = $paramMap;
4495 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4497 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4501 * Parse image options text and use it to make an image
4502 * @param Title $title
4503 * @param string $options
4504 * @param LinkHolderArray $holders
4506 function makeImage( $title, $options, $holders = false ) {
4507 # Check if the options text is of the form "options|alt text"
4509 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4510 # * left no resizing, just left align. label is used for alt= only
4511 # * right same, but right aligned
4512 # * none same, but not aligned
4513 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4514 # * center center the image
4515 # * frame Keep original image size, no magnify-button.
4516 # * framed Same as "frame"
4517 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4518 # * upright reduce width for upright images, rounded to full __0 px
4519 # * border draw a 1px border around the image
4520 # * alt Text for HTML alt attribute (defaults to empty)
4521 # * link Set the target of the image link. Can be external, interwiki, or local
4522 # vertical-align values (no % or length right now):
4532 $parts = StringUtils
::explode( "|", $options );
4533 $sk = $this->mOptions
->getSkin();
4535 # Give extensions a chance to select the file revision for us
4536 $skip = $time = $descQuery = false;
4537 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4540 return $sk->link( $title );
4544 $imagename = $title->getDBkey();
4545 $file = wfFindFile( $title, array( 'time' => $time ) );
4547 $handler = $file ?
$file->getHandler() : false;
4549 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4551 # Process the input parameters
4553 $params = array( 'frame' => array(), 'handler' => array(),
4554 'horizAlign' => array(), 'vertAlign' => array() );
4555 foreach( $parts as $part ) {
4556 $part = trim( $part );
4557 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4559 if( isset( $paramMap[$magicName] ) ) {
4560 list( $type, $paramName ) = $paramMap[$magicName];
4562 // Special case; width and height come in one variable together
4563 if( $type === 'handler' && $paramName === 'width' ) {
4565 # (bug 13500) In both cases (width/height and width only),
4566 # permit trailing "px" for backward compatibility.
4567 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4568 $width = intval( $m[1] );
4569 $height = intval( $m[2] );
4570 if ( $handler->validateParam( 'width', $width ) ) {
4571 $params[$type]['width'] = $width;
4574 if ( $handler->validateParam( 'height', $height ) ) {
4575 $params[$type]['height'] = $height;
4578 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4579 $width = intval( $value );
4580 if ( $handler->validateParam( 'width', $width ) ) {
4581 $params[$type]['width'] = $width;
4584 } // else no validation -- bug 13436
4586 if ( $type === 'handler' ) {
4587 # Validate handler parameter
4588 $validated = $handler->validateParam( $paramName, $value );
4590 # Validate internal parameters
4591 switch( $paramName ) {
4594 // @todo Fixme: possibly check validity here for
4595 // manualthumb? downstream behavior seems odd with
4596 // missing manual thumbs.
4598 $value = $this->stripAltText( $value, $holders );
4601 $chars = self
::EXT_LINK_URL_CLASS
;
4602 $prots = $this->mUrlProtocols
;
4603 if ( $value === '' ) {
4604 $paramName = 'no-link';
4607 } elseif ( preg_match( "/^$prots/", $value ) ) {
4608 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4609 $paramName = 'link-url';
4610 $this->mOutput
->addExternalLink( $value );
4614 $linkTitle = Title
::newFromText( $value );
4616 $paramName = 'link-title';
4617 $value = $linkTitle;
4618 $this->mOutput
->addLink( $linkTitle );
4624 // Most other things appear to be empty or numeric...
4625 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4630 $params[$type][$paramName] = $value;
4634 if ( !$validated ) {
4639 # Process alignment parameters
4640 if ( $params['horizAlign'] ) {
4641 $params['frame']['align'] = key( $params['horizAlign'] );
4643 if ( $params['vertAlign'] ) {
4644 $params['frame']['valign'] = key( $params['vertAlign'] );
4647 $params['frame']['caption'] = $caption;
4649 # Will the image be presented in a frame, with the caption below?
4650 $imageIsFramed = isset( $params['frame']['frame'] ) ||
4651 isset( $params['frame']['framed'] ) ||
4652 isset( $params['frame']['thumbnail'] ) ||
4653 isset( $params['frame']['manualthumb'] );
4655 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4656 # came to also set the caption, ordinary text after the image -- which
4657 # makes no sense, because that just repeats the text multiple times in
4658 # screen readers. It *also* came to set the title attribute.
4660 # Now that we have an alt attribute, we should not set the alt text to
4661 # equal the caption: that's worse than useless, it just repeats the
4662 # text. This is the framed/thumbnail case. If there's no caption, we
4663 # use the unnamed parameter for alt text as well, just for the time be-
4664 # ing, if the unnamed param is set and the alt param is not.
4666 # For the future, we need to figure out if we want to tweak this more,
4667 # e.g., introducing a title= parameter for the title; ignoring the un-
4668 # named parameter entirely for images without a caption; adding an ex-
4669 # plicit caption= parameter and preserving the old magic unnamed para-
4671 if ( $imageIsFramed ) { # Framed image
4672 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
4673 # No caption or alt text, add the filename as the alt text so
4674 # that screen readers at least get some description of the image
4675 $params['frame']['alt'] = $title->getText();
4677 # Do not set $params['frame']['title'] because tooltips don't make sense
4679 } else { # Inline image
4680 if ( !isset( $params['frame']['alt'] ) ) {
4681 # No alt text, use the "caption" for the alt text
4682 if ( $caption !== '') {
4683 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
4685 # No caption, fall back to using the filename for the
4687 $params['frame']['alt'] = $title->getText();
4690 # Use the "caption" for the tooltip text
4691 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4694 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4696 # Linker does the rest
4697 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4699 # Give the handler a chance to modify the parser object
4701 $handler->parserTransformHook( $this, $file );
4707 protected function stripAltText( $caption, $holders ) {
4708 # Strip bad stuff out of the title (tooltip). We can't just use
4709 # replaceLinkHoldersText() here, because if this function is called
4710 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4712 $tooltip = $holders->replaceText( $caption );
4714 $tooltip = $this->replaceLinkHoldersText( $caption );
4717 # make sure there are no placeholders in thumbnail attributes
4718 # that are later expanded to html- so expand them now and
4720 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
4721 $tooltip = Sanitizer
::stripAllTags( $tooltip );
4727 * Set a flag in the output object indicating that the content is dynamic and
4728 * shouldn't be cached.
4730 function disableCache() {
4731 wfDebug( "Parser output marked as uncacheable.\n" );
4732 $this->mOutput
->mCacheTime
= -1;
4736 * Callback from the Sanitizer for expanding items found in HTML attribute
4737 * values, so they can be safely tested and escaped.
4738 * @param string $text
4739 * @param PPFrame $frame
4743 function attributeStripCallback( &$text, $frame = false ) {
4744 $text = $this->replaceVariables( $text, $frame );
4745 $text = $this->mStripState
->unstripBoth( $text );
4754 function Title( $x = null ) { return wfSetVar( $this->mTitle
, $x ); }
4755 function Options( $x = null ) { return wfSetVar( $this->mOptions
, $x ); }
4756 function OutputType( $x = null ) { return wfSetVar( $this->mOutputType
, $x ); }
4762 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4767 * Break wikitext input into sections, and either pull or replace
4768 * some particular section's text.
4770 * External callers should use the getSection and replaceSection methods.
4772 * @param string $text Page wikitext
4773 * @param string $section A section identifier string of the form:
4774 * <flag1> - <flag2> - ... - <section number>
4776 * Currently the only recognised flag is "T", which means the target section number
4777 * was derived during a template inclusion parse, in other words this is a template
4778 * section edit link. If no flags are given, it was an ordinary section edit link.
4779 * This flag is required to avoid a section numbering mismatch when a section is
4780 * enclosed by <includeonly> (bug 6563).
4782 * The section number 0 pulls the text before the first heading; other numbers will
4783 * pull the given section along with its lower-level subsections. If the section is
4784 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4786 * @param string $mode One of "get" or "replace"
4787 * @param string $newText Replacement text for section data.
4788 * @return string for "get", the extracted section text.
4789 * for "replace", the whole page with the section replaced.
4791 private function extractSections( $text, $section, $mode, $newText='' ) {
4793 $this->clearState();
4794 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4795 $this->mOptions
= new ParserOptions
;
4796 $this->setOutputType( self
::OT_WIKI
);
4798 $frame = $this->getPreprocessor()->newFrame();
4800 // Process section extraction flags
4802 $sectionParts = explode( '-', $section );
4803 $sectionIndex = array_pop( $sectionParts );
4804 foreach ( $sectionParts as $part ) {
4805 if ( $part === 'T' ) {
4806 $flags |
= self
::PTD_FOR_INCLUSION
;
4809 // Preprocess the text
4810 $root = $this->preprocessToDom( $text, $flags );
4812 // <h> nodes indicate section breaks
4813 // They can only occur at the top level, so we can find them by iterating the root's children
4814 $node = $root->getFirstChild();
4816 // Find the target section
4817 if ( $sectionIndex == 0 ) {
4818 // Section zero doesn't nest, level=big
4819 $targetLevel = 1000;
4822 if ( $node->getName() === 'h' ) {
4823 $bits = $node->splitHeading();
4824 if ( $bits['i'] == $sectionIndex ) {
4825 $targetLevel = $bits['level'];
4829 if ( $mode === 'replace' ) {
4830 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4832 $node = $node->getNextSibling();
4838 if ( $mode === 'get' ) {
4845 // Find the end of the section, including nested sections
4847 if ( $node->getName() === 'h' ) {
4848 $bits = $node->splitHeading();
4849 $curLevel = $bits['level'];
4850 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4854 if ( $mode === 'get' ) {
4855 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4857 $node = $node->getNextSibling();
4860 // Write out the remainder (in replace mode only)
4861 if ( $mode === 'replace' ) {
4862 // Output the replacement text
4863 // Add two newlines on -- trailing whitespace in $newText is conventionally
4864 // stripped by the editor, so we need both newlines to restore the paragraph gap
4865 // Only add trailing whitespace if there is newText
4866 if($newText != "") {
4867 $outText .= $newText . "\n\n";
4871 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4872 $node = $node->getNextSibling();
4876 if ( is_string( $outText ) ) {
4877 // Re-insert stripped tags
4878 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4885 * This function returns the text of a section, specified by a number ($section).
4886 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4887 * the first section before any such heading (section 0).
4889 * If a section contains subsections, these are also returned.
4891 * @param string $text text to look in
4892 * @param string $section section identifier
4893 * @param string $deftext default to return if section is not found
4894 * @return string text of the requested section
4896 public function getSection( $text, $section, $deftext='' ) {
4897 return $this->extractSections( $text, $section, "get", $deftext );
4900 public function replaceSection( $oldtext, $section, $text ) {
4901 return $this->extractSections( $oldtext, $section, "replace", $text );
4905 * Get the timestamp associated with the current revision, adjusted for
4906 * the default server-local timestamp
4908 function getRevisionTimestamp() {
4909 if ( is_null( $this->mRevisionTimestamp
) ) {
4910 wfProfileIn( __METHOD__
);
4912 $dbr = wfGetDB( DB_SLAVE
);
4913 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4914 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4916 // Normalize timestamp to internal MW format for timezone processing.
4917 // This has the added side-effect of replacing a null value with
4918 // the current time, which gives us more sensible behavior for
4920 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4922 // The cryptic '' timezone parameter tells to use the site-default
4923 // timezone offset instead of the user settings.
4925 // Since this value will be saved into the parser cache, served
4926 // to other users, and potentially even used inside links and such,
4927 // it needs to be consistent for all visitors.
4928 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4930 wfProfileOut( __METHOD__
);
4932 return $this->mRevisionTimestamp
;
4936 * Get the name of the user that edited the last revision
4938 function getRevisionUser() {
4939 // if this template is subst: the revision id will be blank,
4940 // so just use the current user's name
4941 if( $this->mRevisionId
) {
4942 $revision = Revision
::newFromId( $this->mRevisionId
);
4943 $revuser = $revision->getUserText();
4946 $revuser = $wgUser->getName();
4952 * Mutator for $mDefaultSort
4954 * @param $sort New value
4956 public function setDefaultSort( $sort ) {
4957 $this->mDefaultSort
= $sort;
4961 * Accessor for $mDefaultSort
4962 * Will use the title/prefixed title if none is set
4966 public function getDefaultSort() {
4967 global $wgCategoryPrefixedDefaultSortkey;
4968 if( $this->mDefaultSort
!== false ) {
4969 return $this->mDefaultSort
;
4970 } elseif ($this->mTitle
->getNamespace() == NS_CATEGORY ||
4971 !$wgCategoryPrefixedDefaultSortkey) {
4972 return $this->mTitle
->getText();
4974 return $this->mTitle
->getPrefixedText();
4979 * Accessor for $mDefaultSort
4980 * Unlike getDefaultSort(), will return false if none is set
4982 * @return string or false
4984 public function getCustomDefaultSort() {
4985 return $this->mDefaultSort
;
4989 * Try to guess the section anchor name based on a wikitext fragment
4990 * presumably extracted from a heading, for example "Header" from
4993 public function guessSectionNameFromWikiText( $text ) {
4994 # Strip out wikitext links(they break the anchor)
4995 $text = $this->stripSectionName( $text );
4996 $headline = Sanitizer
::decodeCharReferences( $text );
4998 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
4999 $headline = trim( $headline );
5000 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
5001 $replacearray = array(
5006 array_keys( $replacearray ),
5007 array_values( $replacearray ),
5012 * Strips a text string of wikitext for use in a section anchor
5014 * Accepts a text string and then removes all wikitext from the
5015 * string and leaves only the resultant text (i.e. the result of
5016 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5017 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5018 * to create valid section anchors by mimicing the output of the
5019 * parser when headings are parsed.
5021 * @param $text string Text string to be stripped of wikitext
5022 * for use in a Section anchor
5023 * @return Filtered text string
5025 public function stripSectionName( $text ) {
5026 # Strip internal link markup
5027 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
5028 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
5030 # Strip external link markup (FIXME: Not Tolerant to blank link text
5031 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5032 # on how many empty links there are on the page - need to figure that out.
5033 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
5035 # Parse wikitext quotes (italics & bold)
5036 $text = $this->doQuotes($text);
5039 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5043 function srvus( $text ) {
5044 return $this->testSrvus( $text, $this->mOutputType
);
5048 * strip/replaceVariables/unstrip for preprocessor regression testing
5050 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
5051 $this->clearState();
5052 if ( ! ( $title instanceof Title
) ) {
5053 $title = Title
::newFromText( $title );
5055 $this->mTitle
= $title;
5056 $this->mOptions
= $options;
5057 $this->setOutputType( $outputType );
5058 $text = $this->replaceVariables( $text );
5059 $text = $this->mStripState
->unstripBoth( $text );
5060 $text = Sanitizer
::removeHTMLtags( $text );
5064 function testPst( $text, $title, $options ) {
5066 if ( ! ( $title instanceof Title
) ) {
5067 $title = Title
::newFromText( $title );
5069 return $this->preSaveTransform( $text, $title, $wgUser, $options );
5072 function testPreprocess( $text, $title, $options ) {
5073 if ( ! ( $title instanceof Title
) ) {
5074 $title = Title
::newFromText( $title );
5076 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5079 function markerSkipCallback( $s, $callback ) {
5082 while ( $i < strlen( $s ) ) {
5083 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5084 if ( $markerStart === false ) {
5085 $out .= call_user_func( $callback, substr( $s, $i ) );
5088 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5089 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5090 if ( $markerEnd === false ) {
5091 $out .= substr( $s, $markerStart );
5094 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5095 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5103 function serialiseHalfParsedText( $text ) {
5105 $data['text'] = $text;
5107 // First, find all strip markers, and store their
5108 // data in an array.
5109 $stripState = new StripState
;
5111 while( ( $start_pos = strpos( $text, $this->mUniqPrefix
, $pos ) ) && ( $end_pos = strpos( $text, self
::MARKER_SUFFIX
, $pos ) ) ) {
5112 $end_pos +
= strlen( self
::MARKER_SUFFIX
);
5113 $marker = substr( $text, $start_pos, $end_pos-$start_pos );
5115 if ( !empty( $this->mStripState
->general
->data
[$marker] ) ) {
5116 $replaceArray = $stripState->general
;
5117 $stripText = $this->mStripState
->general
->data
[$marker];
5118 } elseif ( !empty( $this->mStripState
->nowiki
->data
[$marker] ) ) {
5119 $replaceArray = $stripState->nowiki
;
5120 $stripText = $this->mStripState
->nowiki
->data
[$marker];
5122 throw new MWException( "Hanging strip marker: '$marker'." );
5125 $replaceArray->setPair( $marker, $stripText );
5128 $data['stripstate'] = $stripState;
5130 // Now, find all of our links, and store THEIR
5131 // data in an array! :)
5132 $links = array( 'internal' => array(), 'interwiki' => array() );
5136 while( ( $start_pos = strpos( $text, '<!--LINK ', $pos ) ) ) {
5137 list( $ns, $trail ) = explode( ':', substr( $text, $start_pos +
strlen( '<!--LINK ' ) ), 2 );
5140 if (empty( $links['internal'][$ns] )) {
5141 $links['internal'][$ns] = array();
5144 $key = trim( substr( $trail, 0, strpos( $trail, '-->' ) ) );
5145 $links['internal'][$ns][] = $this->mLinkHolders
->internals
[$ns][$key];
5146 $pos = $start_pos +
strlen( "<!--LINK $ns:$key-->" );
5152 while( ( $start_pos = strpos( $text, '<!--IWLINK ', $pos ) ) ) {
5153 $data = substr( $text, $start_pos );
5154 $key = trim( substr( $data, 0, strpos( $data, '-->' ) ) );
5155 $links['interwiki'][] = $this->mLinkHolders
->interwiki
[$key];
5156 $pos = $start_pos +
strlen( "<!--IWLINK $key-->" );
5159 $data['linkholder'] = $links;
5164 function unserialiseHalfParsedText( $data, $intPrefix = null /* Unique identifying prefix */ ) {
5166 $intPrefix = $this->getRandomString();
5168 // First, extract the strip state.
5169 $stripState = $data['stripstate'];
5170 $this->mStripState
->general
->merge( $stripState->general
);
5171 $this->mStripState
->nowiki
->merge( $stripState->nowiki
);
5173 // Now, extract the text, and renumber links
5174 $text = $data['text'];
5175 $links = $data['linkholder'];
5178 foreach( $links['internal'] as $ns => $nsLinks ) {
5179 foreach( $nsLinks as $key => $entry ) {
5180 $newKey = $intPrefix . '-' . $key;
5181 $this->mLinkHolders
->internals
[$ns][$newKey] = $entry;
5183 $text = str_replace( "<!--LINK $ns:$key-->", "<!--LINK $ns:$newKey-->", $text );
5188 foreach( $links['interwiki'] as $key => $entry ) {
5189 $newKey = "$intPrefix-$key";
5190 $this->mLinkHolders
->interwikis
[$newKey] = $entry;
5192 $text = str_replace( "<!--IWLINK $key-->", "<!--IWLINK $newKey-->", $text );
5195 // Should be good to go.
5201 * @todo document, briefly.
5205 var $general, $nowiki;
5207 function __construct() {
5208 $this->general
= new ReplacementArray
;
5209 $this->nowiki
= new ReplacementArray
;
5212 function unstripGeneral( $text ) {
5213 wfProfileIn( __METHOD__
);
5216 $text = $this->general
->replace( $text );
5217 } while ( $text !== $oldText );
5218 wfProfileOut( __METHOD__
);
5222 function unstripNoWiki( $text ) {
5223 wfProfileIn( __METHOD__
);
5226 $text = $this->nowiki
->replace( $text );
5227 } while ( $text !== $oldText );
5228 wfProfileOut( __METHOD__
);
5232 function unstripBoth( $text ) {
5233 wfProfileIn( __METHOD__
);
5236 $text = $this->general
->replace( $text );
5237 $text = $this->nowiki
->replace( $text );
5238 } while ( $text !== $oldText );
5239 wfProfileOut( __METHOD__
);
5245 * @todo document, briefly.
5248 class OnlyIncludeReplacer
{
5251 function replace( $matches ) {
5252 if ( substr( $matches[1], -1 ) === "\n" ) {
5253 $this->output
.= substr( $matches[1], 0, -1 );
5255 $this->output
.= $matches[1];