3 * @defgroup Parser Parser
7 * File for Parser and related classes
12 * PHP Parser - Processes wiki markup (which uses a more user-friendly
13 * syntax, such as "[[link]]" for making links), and provides a one-way
14 * transformation of that wiki markup it into XHTML output / markup
15 * (which in turn the browser understands, and can display).
18 * There are five main entry points into the Parser class:
20 * produces HTML output
22 * produces altered wiki markup.
24 * removes HTML comments and expands templates
26 * Cleans a signature before saving it to preferences
28 * Extracts sections from an article for section editing
30 * Removes <noinclude> sections, and <includeonly> tags.
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().
83 const OT_HTML
= 1; // like parse()
84 const OT_WIKI
= 2; // like preSaveTransform()
85 const OT_PREPROCESS
= 3; // like preprocess()
87 const OT_PLAIN
= 4; // like extractSections() - portions of the original are returned unchanged.
89 // Marker Suffix needs to be accessible staticly.
90 const MARKER_SUFFIX
= "-QINU\x7f";
96 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables,
97 $mSubstWords, $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
,
255 'plain' => $ot == self
::OT_PLAIN
,
260 * Set the context title
262 function setTitle( $t ) {
263 if ( !$t ||
$t instanceof FakeTitle
) {
264 $t = Title
::newFromText( 'NO TITLE' );
267 if ( strval( $t->getFragment() ) !== '' ) {
268 # Strip the fragment to avoid various odd effects
269 $this->mTitle
= clone $t;
270 $this->mTitle
->setFragment( '' );
277 * Accessor for mUniqPrefix.
281 function uniqPrefix() {
282 if( !isset( $this->mUniqPrefix
) ) {
283 // @todo Fixme: this is probably *horribly wrong*
284 // LanguageConverter seems to want $wgParser's uniqPrefix, however
285 // if this is called for a parser cache hit, the parser may not
286 // have ever been initialized in the first place.
287 // Not really sure what the heck is supposed to be going on here.
289 //throw new MWException( "Accessing uninitialized mUniqPrefix" );
291 return $this->mUniqPrefix
;
295 * Convert wikitext to HTML
296 * Do not call this function recursively.
298 * @param $text String: text we want to parse
299 * @param $title A title object
300 * @param $options ParserOptions
301 * @param $linestart boolean
302 * @param $clearState boolean
303 * @param $revid Int: number to pass in {{REVISIONID}}
304 * @return ParserOutput a ParserOutput
306 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
308 * First pass--just handle <nowiki> sections, pass the rest off
309 * to internalParse() which does all the real work.
312 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang, $wgDisableLangConversion;
313 $fname = __METHOD__
.'-' . wfGetCaller();
314 wfProfileIn( __METHOD__
);
315 wfProfileIn( $fname );
321 $this->mOptions
= $options;
322 $this->setTitle( $title ); // Page title has to be set for the pre-processor
324 $oldRevisionId = $this->mRevisionId
;
325 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
326 if( $revid !== null ) {
327 $this->mRevisionId
= $revid;
328 $this->mRevisionTimestamp
= null;
330 $this->setOutputType( self
::OT_HTML
);
331 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
333 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
334 $text = $this->internalParse( $text );
336 $text = $this->mStripState
->unstripGeneral( $text );
338 # Clean up special characters, only run once, next-to-last before doBlockLevels
340 # french spaces, last one Guillemet-left
341 # only if there is something before the space
342 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
343 # french spaces, Guillemet-right
344 '/(\\302\\253) /' => '\\1 ',
345 '/ (!\s*important)/' => ' \\1', #Beware of CSS magic word !important, bug #11874.
347 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
349 $text = $this->doBlockLevels( $text, $linestart );
351 $this->replaceLinkHolders( $text );
353 // The position of the convert() call should not be changed. it
354 // assumes that the links are all replaced and the only thing left
355 // is the <nowiki> mark.
356 if ( !( $wgDisableLangConversion
357 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
358 ||
$this->mTitle
->isTalkPage()
359 ||
$this->mTitle
->isConversionTable() ) ) {
360 $text = $wgContLang->convert( $text );
363 // A title may have been set in a conversion rule.
364 // Note that if a user tries to set a title in a conversion
365 // rule but content conversion was not done, then the parser
366 // won't pick it up. This is probably expected behavior.
367 if ( $wgContLang->getConvRuleTitle() ) {
368 $this->mOutput
->setTitleText( $wgContLang->getConvRuleTitle() );
371 $text = $this->mStripState
->unstripNoWiki( $text );
373 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
375 //!JF Move to its own function
377 $uniq_prefix = $this->mUniqPrefix
;
379 $elements = array_keys( $this->mTransparentTagHooks
);
380 $text = self
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
382 foreach( $matches as $marker => $data ) {
383 list( $element, $content, $params, $tag ) = $data;
384 $tagName = strtolower( $element );
385 if( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
386 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName],
387 array( $content, $params, $this ) );
391 $this->mStripState
->general
->setPair( $marker, $output );
393 $text = $this->mStripState
->unstripGeneral( $text );
395 $text = Sanitizer
::normalizeCharReferences( $text );
397 if ( ( $wgUseTidy && $this->mOptions
->mTidy
) ||
$wgAlwaysUseTidy ) {
398 $text = MWTidy
::tidy( $text );
400 # attempt to sanitize at least some nesting problems
401 # (bug #2702 and quite a few others)
403 # ''Something [http://www.cool.com cool''] -->
404 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
405 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
406 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
407 # fix up an anchor inside another anchor, only
408 # at least for a single single nested link (bug 3695)
409 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
410 '\\1\\2</a>\\3</a>\\1\\4</a>',
411 # fix div inside inline elements- doBlockLevels won't wrap a line which
412 # contains a div, so fix it up here; replace
413 # div with escaped text
414 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
415 '\\1\\3<div\\5>\\6</div>\\8\\9',
416 # remove empty italic or bold tag pairs, some
417 # introduced by rules above
418 '/<([bi])><\/\\1>/' => '',
421 $text = preg_replace(
422 array_keys( $tidyregs ),
423 array_values( $tidyregs ),
426 global $wgExpensiveParserFunctionLimit;
427 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
428 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
431 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
433 # Information on include size limits, for the benefit of users who try to skirt them
434 if ( $this->mOptions
->getEnableLimitReport() ) {
435 $max = $this->mOptions
->getMaxIncludeSize();
436 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
438 "NewPP limit report\n" .
439 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
440 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
441 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
443 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
444 $text .= "\n<!-- \n$limitReport-->\n";
446 $this->mOutput
->setText( $text );
448 $this->mRevisionId
= $oldRevisionId;
449 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
450 wfProfileOut( $fname );
451 wfProfileOut( __METHOD__
);
453 return $this->mOutput
;
457 * Recursive parser entry point that can be called from an extension tag
460 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
462 * @param $text String: text extension wants to have parsed
463 * @param PPFrame $frame: The frame to use for expanding any template variables
465 function recursiveTagParse( $text, $frame=false ) {
466 wfProfileIn( __METHOD__
);
467 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
468 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
469 $text = $this->internalParse( $text, false, $frame );
470 wfProfileOut( __METHOD__
);
475 * Expand templates and variables in the text, producing valid, static wikitext.
476 * Also removes comments.
478 function preprocess( $text, $title, $options, $revid = null ) {
479 wfProfileIn( __METHOD__
);
481 $this->setOutputType( self
::OT_PREPROCESS
);
482 $this->mOptions
= $options;
483 $this->setTitle( $title );
484 if( $revid !== null ) {
485 $this->mRevisionId
= $revid;
487 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
488 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
489 $text = $this->replaceVariables( $text );
490 $text = $this->mStripState
->unstripBoth( $text );
491 wfProfileOut( __METHOD__
);
496 * Process the wikitext for the ?preload= feature. (bug 5210)
498 * <noinclude>, <includeonly> etc. are parsed as for template transclusion,
499 * comments, templates, arguments, tags hooks and parser functions are untouched.
501 public function getPreloadText( $text, $title, $options ) {
502 // Parser (re)initialisation
504 $this->setOutputType( self
::OT_PLAIN
);
505 $this->mOptions
= $options;
506 $this->setTitle( $title );
508 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
509 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
510 return $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
514 * Get a random string
519 function getRandomString() {
520 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
523 function &getTitle() { return $this->mTitle
; }
524 function getOptions() { return $this->mOptions
; }
525 function getRevisionId() { return $this->mRevisionId
; }
526 function getOutput() { return $this->mOutput
; }
527 function nextLinkID() { return $this->mLinkID++
; }
529 function getFunctionLang() {
530 global $wgLang, $wgContLang;
532 $target = $this->mOptions
->getTargetLanguage();
533 if ( $target !== null ) {
536 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
541 * Get a preprocessor object
543 function getPreprocessor() {
544 if ( !isset( $this->mPreprocessor
) ) {
545 $class = $this->mPreprocessorClass
;
546 $this->mPreprocessor
= new $class( $this );
548 return $this->mPreprocessor
;
552 * Replaces all occurrences of HTML-style comments and the given tags
553 * in the text with a random marker and returns the next text. The output
554 * parameter $matches will be an associative array filled with data in
556 * 'UNIQ-xxxxx' => array(
559 * array( 'param' => 'x' ),
560 * '<element param="x">tag content</element>' ) )
562 * @param $elements list of element names. Comments are always extracted.
563 * @param $text Source text string.
564 * @param $uniq_prefix
569 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
574 $taglist = implode( '|', $elements );
575 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
577 while ( $text != '' ) {
578 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
580 if( count( $p ) < 5 ) {
583 if( count( $p ) > 5 ) {
597 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . self
::MARKER_SUFFIX
;
598 $stripped .= $marker;
600 if ( $close === '/>' ) {
601 // Empty element tag, <tag />
606 if( $element === '!--' ) {
609 $end = "/(<\\/$element\\s*>)/i";
611 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
613 if( count( $q ) < 3 ) {
614 # No end tag -- let it run out to the end of the text.
623 $matches[$marker] = array( $element,
625 Sanitizer
::decodeTagAttributes( $attributes ),
626 "<$element$attributes$close$content$tail" );
632 * Get a list of strippable XML-like elements
634 function getStripList() {
635 return $this->mStripList
;
639 * @deprecated use replaceVariables
641 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
646 * Restores pre, math, and other extensions removed by strip()
648 * always call unstripNoWiki() after this one
650 * @deprecated use $this->mStripState->unstrip()
652 function unstrip( $text, $state ) {
653 return $state->unstripGeneral( $text );
657 * Always call this after unstrip() to preserve the order
660 * @deprecated use $this->mStripState->unstrip()
662 function unstripNoWiki( $text, $state ) {
663 return $state->unstripNoWiki( $text );
667 * @deprecated use $this->mStripState->unstripBoth()
669 function unstripForHTML( $text ) {
670 return $this->mStripState
->unstripBoth( $text );
674 * Add an item to the strip state
675 * Returns the unique tag which must be inserted into the stripped text
676 * The tag will be replaced with the original text in unstrip()
680 function insertStripItem( $text ) {
681 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
682 $this->mMarkerIndex++
;
683 $this->mStripState
->general
->setPair( $rnd, $text );
688 * Interface with html tidy
689 * @deprecated Use MWTidy::tidy()
691 public static function tidy( $text ) {
692 wfDeprecated( __METHOD__
);
693 return MWTidy
::tidy( $text );
697 * parse the wiki syntax used to render tables
701 function doTableStuff ( $text ) {
702 wfProfileIn( __METHOD__
);
704 $lines = StringUtils
::explode( "\n", $text );
706 $td_history = array (); // Is currently a td tag open?
707 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
708 $tr_history = array (); // Is currently a tr tag open?
709 $tr_attributes = array (); // history of tr attributes
710 $has_opened_tr = array(); // Did this table open a <tr> element?
711 $indent_level = 0; // indent level of the table
713 foreach ( $lines as $outLine ) {
714 $line = trim( $outLine );
716 if( $line == '' ) { // empty line, go to next line
717 $out .= $outLine."\n";
720 $first_character = $line[0];
723 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
724 // First check if we are starting a new table
725 $indent_level = strlen( $matches[1] );
727 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
728 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
730 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
731 array_push( $td_history , false );
732 array_push( $last_tag_history , '' );
733 array_push( $tr_history , false );
734 array_push( $tr_attributes , '' );
735 array_push( $has_opened_tr , false );
736 } else if ( count ( $td_history ) == 0 ) {
737 // Don't do any of the following
738 $out .= $outLine."\n";
740 } else if ( substr ( $line , 0 , 2 ) === '|}' ) {
741 // We are ending a table
742 $line = '</table>' . substr ( $line , 2 );
743 $last_tag = array_pop ( $last_tag_history );
745 if ( !array_pop ( $has_opened_tr ) ) {
746 $line = "<tr><td></td></tr>{$line}";
749 if ( array_pop ( $tr_history ) ) {
750 $line = "</tr>{$line}";
753 if ( array_pop ( $td_history ) ) {
754 $line = "</{$last_tag}>{$line}";
756 array_pop ( $tr_attributes );
757 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
758 } else if ( substr ( $line , 0 , 2 ) === '|-' ) {
759 // Now we have a table row
760 $line = preg_replace( '#^\|-+#', '', $line );
762 // Whats after the tag is now only attributes
763 $attributes = $this->mStripState
->unstripBoth( $line );
764 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
765 array_pop( $tr_attributes );
766 array_push( $tr_attributes, $attributes );
769 $last_tag = array_pop ( $last_tag_history );
770 array_pop ( $has_opened_tr );
771 array_push ( $has_opened_tr , true );
773 if ( array_pop ( $tr_history ) ) {
777 if ( array_pop ( $td_history ) ) {
778 $line = "</{$last_tag}>{$line}";
782 array_push ( $tr_history , false );
783 array_push ( $td_history , false );
784 array_push ( $last_tag_history , '' );
786 else if ( $first_character === '|' ||
$first_character === '!' ||
substr ( $line , 0 , 2 ) === '|+' ) {
787 // This might be cell elements, td, th or captions
788 if ( substr ( $line , 0 , 2 ) === '|+' ) {
789 $first_character = '+';
790 $line = substr ( $line , 1 );
793 $line = substr ( $line , 1 );
795 if ( $first_character === '!' ) {
796 $line = str_replace ( '!!' , '||' , $line );
799 // Split up multiple cells on the same line.
800 // FIXME : This can result in improper nesting of tags processed
801 // by earlier parser steps, but should avoid splitting up eg
802 // attribute values containing literal "||".
803 $cells = StringUtils
::explodeMarkup( '||' , $line );
807 // Loop through each table cell
808 foreach ( $cells as $cell )
811 if ( $first_character !== '+' )
813 $tr_after = array_pop ( $tr_attributes );
814 if ( !array_pop ( $tr_history ) ) {
815 $previous = "<tr{$tr_after}>\n";
817 array_push ( $tr_history , true );
818 array_push ( $tr_attributes , '' );
819 array_pop ( $has_opened_tr );
820 array_push ( $has_opened_tr , true );
823 $last_tag = array_pop ( $last_tag_history );
825 if ( array_pop ( $td_history ) ) {
826 $previous = "</{$last_tag}>{$previous}";
829 if ( $first_character === '|' ) {
831 } else if ( $first_character === '!' ) {
833 } else if ( $first_character === '+' ) {
834 $last_tag = 'caption';
839 array_push ( $last_tag_history , $last_tag );
841 // A cell could contain both parameters and data
842 $cell_data = explode ( '|' , $cell , 2 );
844 // Bug 553: Note that a '|' inside an invalid link should not
845 // be mistaken as delimiting cell parameters
846 if ( strpos( $cell_data[0], '[[' ) !== false ) {
847 $cell = "{$previous}<{$last_tag}>{$cell}";
848 } else if ( count ( $cell_data ) == 1 )
849 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
851 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
852 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
853 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
857 array_push ( $td_history , true );
860 $out .= $outLine . "\n";
863 // Closing open td, tr && table
864 while ( count ( $td_history ) > 0 )
866 if ( array_pop ( $td_history ) ) {
869 if ( array_pop ( $tr_history ) ) {
872 if ( !array_pop ( $has_opened_tr ) ) {
873 $out .= "<tr><td></td></tr>\n" ;
876 $out .= "</table>\n";
879 // Remove trailing line-ending (b/c)
880 if ( substr( $out, -1 ) === "\n" ) {
881 $out = substr( $out, 0, -1 );
884 // special case: don't return empty table
885 if( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
889 wfProfileOut( __METHOD__
);
895 * Helper function for parse() that transforms wiki markup into
896 * HTML. Only called for $mOutputType == self::OT_HTML.
900 function internalParse( $text, $isMain = true, $frame=false ) {
901 wfProfileIn( __METHOD__
);
905 # Hook to suspend the parser in this state
906 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
907 wfProfileOut( __METHOD__
);
911 // if $frame is provided, then use $frame for replacing any variables
913 // use frame depth to infer how include/noinclude tags should be handled
914 // depth=0 means this is the top-level document; otherwise it's an included document
918 $flag = Parser
::PTD_FOR_INCLUSION
;
919 $dom = $this->preprocessToDom( $text, $flag );
920 $text = $frame->expand( $dom );
922 // if $frame is not provided, then use old-style replaceVariables
924 $text = $this->replaceVariables( $text );
927 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
928 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
930 // Tables need to come after variable replacement for things to work
931 // properly; putting them before other transformations should keep
932 // exciting things like link expansions from showing up in surprising
934 $text = $this->doTableStuff( $text );
936 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
938 $text = $this->doDoubleUnderscore( $text );
940 $text = $this->doHeadings( $text );
941 if( $this->mOptions
->getUseDynamicDates() ) {
942 $df = DateFormatter
::getInstance();
943 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
945 $text = $this->doAllQuotes( $text );
946 $text = $this->replaceInternalLinks( $text );
947 $text = $this->replaceExternalLinks( $text );
949 # replaceInternalLinks may sometimes leave behind
950 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
951 $text = str_replace($this->mUniqPrefix
.'NOPARSE', '', $text);
953 $text = $this->doMagicLinks( $text );
954 $text = $this->formatHeadings( $text, $origText, $isMain );
956 wfProfileOut( __METHOD__
);
961 * Replace special strings like "ISBN xxx" and "RFC xxx" with
962 * magic external links.
967 function doMagicLinks( $text ) {
968 wfProfileIn( __METHOD__
);
969 $prots = $this->mUrlProtocols
;
970 $urlChar = self
::EXT_LINK_URL_CLASS
;
971 $text = preg_replace_callback(
973 (<a.*?</a>) | # m[1]: Skip link text
974 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
975 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
976 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
977 ISBN\s+(\b # m[5]: ISBN, capture number
978 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
979 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
980 [0-9Xx] # check digit
982 )!x', array( &$this, 'magicLinkCallback' ), $text );
983 wfProfileOut( __METHOD__
);
987 function magicLinkCallback( $m ) {
988 if ( isset( $m[1] ) && $m[1] !== '' ) {
991 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
994 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
996 return $this->makeFreeExternalLink( $m[0] );
997 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1000 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1003 $CssClass = 'mw-magiclink-rfc';
1005 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1007 $urlmsg = 'pubmedurl';
1008 $CssClass = 'mw-magiclink-pmid';
1011 throw new MWException( __METHOD__
.': unrecognised match type "' .
1012 substr($m[0], 0, 20 ) . '"' );
1014 $url = wfMsg( $urlmsg, $id);
1015 $sk = $this->mOptions
->getSkin();
1016 $la = $sk->getExternalLinkAttributes( "external $CssClass" );
1017 return "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1018 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1021 $num = strtr( $isbn, array(
1026 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1028 $titleObj->escapeLocalUrl() .
1029 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1036 * Make a free external link, given a user-supplied URL
1040 function makeFreeExternalLink( $url ) {
1042 wfProfileIn( __METHOD__
);
1044 $sk = $this->mOptions
->getSkin();
1047 # The characters '<' and '>' (which were escaped by
1048 # removeHTMLtags()) should not be included in
1049 # URLs, per RFC 2396.
1051 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1052 $trail = substr($url, $m2[0][1]) . $trail;
1053 $url = substr($url, 0, $m2[0][1]);
1056 # Move trailing punctuation to $trail
1058 # If there is no left bracket, then consider right brackets fair game too
1059 if ( strpos( $url, '(' ) === false ) {
1063 $numSepChars = strspn( strrev( $url ), $sep );
1064 if ( $numSepChars ) {
1065 $trail = substr( $url, -$numSepChars ) . $trail;
1066 $url = substr( $url, 0, -$numSepChars );
1069 $url = Sanitizer
::cleanUrl( $url );
1071 # Is this an external image?
1072 $text = $this->maybeMakeExternalImage( $url );
1073 if ( $text === false ) {
1074 # Not an image, make a link
1075 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1076 $this->getExternalLinkAttribs( $url ) );
1077 # Register it in the output object...
1078 # Replace unnecessary URL escape codes with their equivalent characters
1079 $pasteurized = self
::replaceUnusualEscapes( $url );
1080 $this->mOutput
->addExternalLink( $pasteurized );
1082 wfProfileOut( __METHOD__
);
1083 return $text . $trail;
1088 * Parse headers and return html
1092 function doHeadings( $text ) {
1093 wfProfileIn( __METHOD__
);
1094 for ( $i = 6; $i >= 1; --$i ) {
1095 $h = str_repeat( '=', $i );
1096 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1097 "<h$i>\\1</h$i>", $text );
1099 wfProfileOut( __METHOD__
);
1104 * Replace single quotes with HTML markup
1106 * @return string the altered text
1108 function doAllQuotes( $text ) {
1109 wfProfileIn( __METHOD__
);
1111 $lines = StringUtils
::explode( "\n", $text );
1112 foreach ( $lines as $line ) {
1113 $outtext .= $this->doQuotes( $line ) . "\n";
1115 $outtext = substr($outtext, 0,-1);
1116 wfProfileOut( __METHOD__
);
1121 * Helper function for doAllQuotes()
1123 public function doQuotes( $text ) {
1124 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1125 if ( count( $arr ) == 1 )
1129 # First, do some preliminary work. This may shift some apostrophes from
1130 # being mark-up to being text. It also counts the number of occurrences
1131 # of bold and italics mark-ups.
1135 foreach ( $arr as $r )
1137 if ( ( $i %
2 ) == 1 )
1139 # If there are ever four apostrophes, assume the first is supposed to
1140 # be text, and the remaining three constitute mark-up for bold text.
1141 if ( strlen( $arr[$i] ) == 4 )
1146 # If there are more than 5 apostrophes in a row, assume they're all
1147 # text except for the last 5.
1148 else if ( strlen( $arr[$i] ) > 5 )
1150 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1153 # Count the number of occurrences of bold and italics mark-ups.
1154 # We are not counting sequences of five apostrophes.
1155 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1156 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1157 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1162 # If there is an odd number of both bold and italics, it is likely
1163 # that one of the bold ones was meant to be an apostrophe followed
1164 # by italics. Which one we cannot know for certain, but it is more
1165 # likely to be one that has a single-letter word before it.
1166 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1169 $firstsingleletterword = -1;
1170 $firstmultiletterword = -1;
1172 foreach ( $arr as $r )
1174 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1176 $x1 = substr ($arr[$i-1], -1);
1177 $x2 = substr ($arr[$i-1], -2, 1);
1179 if ($firstspace == -1) $firstspace = $i;
1180 } else if ($x2 === ' ') {
1181 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1183 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1189 # If there is a single-letter word, use it!
1190 if ($firstsingleletterword > -1)
1192 $arr [ $firstsingleletterword ] = "''";
1193 $arr [ $firstsingleletterword-1 ] .= "'";
1195 # If not, but there's a multi-letter word, use that one.
1196 else if ($firstmultiletterword > -1)
1198 $arr [ $firstmultiletterword ] = "''";
1199 $arr [ $firstmultiletterword-1 ] .= "'";
1201 # ... otherwise use the first one that has neither.
1202 # (notice that it is possible for all three to be -1 if, for example,
1203 # there is only one pentuple-apostrophe in the line)
1204 else if ($firstspace > -1)
1206 $arr [ $firstspace ] = "''";
1207 $arr [ $firstspace-1 ] .= "'";
1211 # Now let's actually convert our apostrophic mush to HTML!
1216 foreach ($arr as $r)
1220 if ($state === 'both')
1227 if (strlen ($r) == 2)
1230 { $output .= '</i>'; $state = ''; }
1231 else if ($state === 'bi')
1232 { $output .= '</i>'; $state = 'b'; }
1233 else if ($state === 'ib')
1234 { $output .= '</b></i><b>'; $state = 'b'; }
1235 else if ($state === 'both')
1236 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1237 else # $state can be 'b' or ''
1238 { $output .= '<i>'; $state .= 'i'; }
1240 else if (strlen ($r) == 3)
1243 { $output .= '</b>'; $state = ''; }
1244 else if ($state === 'bi')
1245 { $output .= '</i></b><i>'; $state = 'i'; }
1246 else if ($state === 'ib')
1247 { $output .= '</b>'; $state = 'i'; }
1248 else if ($state === 'both')
1249 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1250 else # $state can be 'i' or ''
1251 { $output .= '<b>'; $state .= 'b'; }
1253 else if (strlen ($r) == 5)
1256 { $output .= '</b><i>'; $state = 'i'; }
1257 else if ($state === 'i')
1258 { $output .= '</i><b>'; $state = 'b'; }
1259 else if ($state === 'bi')
1260 { $output .= '</i></b>'; $state = ''; }
1261 else if ($state === 'ib')
1262 { $output .= '</b></i>'; $state = ''; }
1263 else if ($state === 'both')
1264 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1265 else # ($state == '')
1266 { $buffer = ''; $state = 'both'; }
1271 # Now close all remaining tags. Notice that the order is important.
1272 if ($state === 'b' ||
$state === 'ib')
1274 if ($state === 'i' ||
$state === 'bi' ||
$state === 'ib')
1276 if ($state === 'bi')
1278 # There might be lonely ''''', so make sure we have a buffer
1279 if ($state === 'both' && $buffer)
1280 $output .= '<b><i>'.$buffer.'</i></b>';
1286 * Replace external links (REL)
1288 * Note: this is all very hackish and the order of execution matters a lot.
1289 * Make sure to run maintenance/parserTests.php if you change this code.
1293 function replaceExternalLinks( $text ) {
1295 wfProfileIn( __METHOD__
);
1297 $sk = $this->mOptions
->getSkin();
1299 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1300 $s = array_shift( $bits );
1303 while ( $i<count( $bits ) ) {
1305 $protocol = $bits[$i++
];
1306 $text = $bits[$i++
];
1307 $trail = $bits[$i++
];
1309 # The characters '<' and '>' (which were escaped by
1310 # removeHTMLtags()) should not be included in
1311 # URLs, per RFC 2396.
1313 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1314 $text = substr($url, $m2[0][1]) . ' ' . $text;
1315 $url = substr($url, 0, $m2[0][1]);
1318 # If the link text is an image URL, replace it with an <img> tag
1319 # This happened by accident in the original parser, but some people used it extensively
1320 $img = $this->maybeMakeExternalImage( $text );
1321 if ( $img !== false ) {
1327 # Set linktype for CSS - if URL==text, link is essentially free
1328 $linktype = ($text === $url) ?
'free' : 'text';
1330 # No link text, e.g. [http://domain.tld/some.link]
1331 if ( $text == '' ) {
1332 # Autonumber if allowed. See bug #5918
1333 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1334 $langObj = $this->getFunctionLang();
1335 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1336 $linktype = 'autonumber';
1338 # Otherwise just use the URL
1339 $text = htmlspecialchars( $url );
1343 # Have link text, e.g. [http://domain.tld/some.link text]s
1345 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1348 $text = $wgContLang->markNoConversion($text);
1350 $url = Sanitizer
::cleanUrl( $url );
1352 # Use the encoded URL
1353 # This means that users can paste URLs directly into the text
1354 # Funny characters like ö aren't valid in URLs anyway
1355 # This was changed in August 2004
1356 $s .= $sk->makeExternalLink( $url, $text, false, $linktype,
1357 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1359 # Register link in the output object.
1360 # Replace unnecessary URL escape codes with the referenced character
1361 # This prevents spammers from hiding links from the filters
1362 $pasteurized = self
::replaceUnusualEscapes( $url );
1363 $this->mOutput
->addExternalLink( $pasteurized );
1366 wfProfileOut( __METHOD__
);
1371 * Get an associative array of additional HTML attributes appropriate for a
1372 * particular external link. This currently may include rel => nofollow
1373 * (depending on configuration, namespace, and the URL's domain) and/or a
1374 * target attribute (depending on configuration).
1376 * @param string $url Optional URL, to extract the domain from for rel =>
1377 * nofollow if appropriate
1378 * @return array Associative array of HTML attributes
1380 function getExternalLinkAttribs( $url = false ) {
1382 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1383 $ns = $this->mTitle
->getNamespace();
1384 if( $wgNoFollowLinks && !in_array($ns, $wgNoFollowNsExceptions) ) {
1385 $attribs['rel'] = 'nofollow';
1387 global $wgNoFollowDomainExceptions;
1388 if ( $wgNoFollowDomainExceptions ) {
1389 $bits = wfParseUrl( $url );
1390 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1391 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1392 if( substr( $bits['host'], -strlen( $domain ) )
1394 unset( $attribs['rel'] );
1401 if ( $this->mOptions
->getExternalLinkTarget() ) {
1402 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1409 * Replace unusual URL escape codes with their equivalent characters
1413 * @todo This can merge genuinely required bits in the path or query string,
1414 * breaking legit URLs. A proper fix would treat the various parts of
1415 * the URL differently; as a workaround, just use the output for
1416 * statistical records, not for actual linking/output.
1418 static function replaceUnusualEscapes( $url ) {
1419 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1420 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1424 * Callback function used in replaceUnusualEscapes().
1425 * Replaces unusual URL escape codes with their equivalent character
1429 private static function replaceUnusualEscapesCallback( $matches ) {
1430 $char = urldecode( $matches[0] );
1431 $ord = ord( $char );
1432 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1433 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1434 // No, shouldn't be escaped
1437 // Yes, leave it escaped
1443 * make an image if it's allowed, either through the global
1444 * option, through the exception, or through the on-wiki whitelist
1447 function maybeMakeExternalImage( $url ) {
1448 $sk = $this->mOptions
->getSkin();
1449 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1450 $imagesexception = !empty($imagesfrom);
1452 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1453 if( $imagesexception && is_array( $imagesfrom ) ) {
1454 $imagematch = false;
1455 foreach( $imagesfrom as $match ) {
1456 if( strpos( $url, $match ) === 0 ) {
1461 } elseif( $imagesexception ) {
1462 $imagematch = (strpos( $url, $imagesfrom ) === 0);
1464 $imagematch = false;
1466 if ( $this->mOptions
->getAllowExternalImages()
1467 ||
( $imagesexception && $imagematch ) ) {
1468 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1470 $text = $sk->makeExternalImage( $url );
1473 if( !$text && $this->mOptions
->getEnableImageWhitelist()
1474 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1475 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1476 foreach( $whitelist as $entry ) {
1477 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1478 if( strpos( $entry, '#' ) === 0 ||
$entry === '' )
1480 if( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1481 # Image matches a whitelist entry
1482 $text = $sk->makeExternalImage( $url );
1491 * Process [[ ]] wikilinks
1492 * @return processed text
1496 function replaceInternalLinks( $s ) {
1497 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1502 * Process [[ ]] wikilinks (RIL)
1503 * @return LinkHolderArray
1507 function replaceInternalLinks2( &$s ) {
1510 wfProfileIn( __METHOD__
);
1512 wfProfileIn( __METHOD__
.'-setup' );
1513 static $tc = FALSE, $e1, $e1_img;
1514 # the % is needed to support urlencoded titles as well
1516 $tc = Title
::legalChars() . '#%';
1517 # Match a link having the form [[namespace:link|alternate]]trail
1518 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1519 # Match cases where there is no "]]", which might still be images
1520 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1523 $sk = $this->mOptions
->getSkin();
1524 $holders = new LinkHolderArray( $this );
1526 #split the entire text string on occurences of [[
1527 $a = StringUtils
::explode( '[[', ' ' . $s );
1528 #get the first element (all text up to first [[), and remove the space we added
1531 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1532 $s = substr( $s, 1 );
1534 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1536 if ( $useLinkPrefixExtension ) {
1537 # Match the end of a line for a word that's not followed by whitespace,
1538 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1539 $e2 = wfMsgForContent( 'linkprefix' );
1542 if( is_null( $this->mTitle
) ) {
1543 wfProfileOut( __METHOD__
.'-setup' );
1544 wfProfileOut( __METHOD__
);
1545 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1547 $nottalk = !$this->mTitle
->isTalkPage();
1549 if ( $useLinkPrefixExtension ) {
1551 if ( preg_match( $e2, $s, $m ) ) {
1552 $first_prefix = $m[2];
1554 $first_prefix = false;
1560 if($wgContLang->hasVariants()) {
1561 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1563 $selflink = array($this->mTitle
->getPrefixedText());
1565 $useSubpages = $this->areSubpagesAllowed();
1566 wfProfileOut( __METHOD__
.'-setup' );
1568 # Loop for each link
1569 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1570 # Check for excessive memory usage
1571 if ( $holders->isBig() ) {
1573 # Do the existence check, replace the link holders and clear the array
1574 $holders->replace( $s );
1578 if ( $useLinkPrefixExtension ) {
1579 wfProfileIn( __METHOD__
.'-prefixhandling' );
1580 if ( preg_match( $e2, $s, $m ) ) {
1588 $prefix = $first_prefix;
1589 $first_prefix = false;
1591 wfProfileOut( __METHOD__
.'-prefixhandling' );
1594 $might_be_img = false;
1596 wfProfileIn( __METHOD__
."-e1" );
1597 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1599 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1600 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1601 # the real problem is with the $e1 regex
1604 # Still some problems for cases where the ] is meant to be outside punctuation,
1605 # and no image is in sight. See bug 2095.
1608 substr( $m[3], 0, 1 ) === ']' &&
1609 strpos($text, '[') !== false
1612 $text .= ']'; # so that replaceExternalLinks($text) works later
1613 $m[3] = substr( $m[3], 1 );
1615 # fix up urlencoded title texts
1616 if( strpos( $m[1], '%' ) !== false ) {
1617 # Should anchors '#' also be rejected?
1618 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1621 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1622 $might_be_img = true;
1624 if ( strpos( $m[1], '%' ) !== false ) {
1625 $m[1] = urldecode($m[1]);
1628 } else { # Invalid form; output directly
1629 $s .= $prefix . '[[' . $line ;
1630 wfProfileOut( __METHOD__
."-e1" );
1633 wfProfileOut( __METHOD__
."-e1" );
1634 wfProfileIn( __METHOD__
."-misc" );
1636 # Don't allow internal links to pages containing
1637 # PROTO: where PROTO is a valid URL protocol; these
1638 # should be external links.
1639 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1640 $s .= $prefix . '[[' . $line ;
1641 wfProfileOut( __METHOD__
."-misc" );
1645 # Make subpage if necessary
1646 if ( $useSubpages ) {
1647 $link = $this->maybeDoSubpageLink( $m[1], $text );
1652 $noforce = (substr( $m[1], 0, 1 ) !== ':');
1654 # Strip off leading ':'
1655 $link = substr( $link, 1 );
1658 wfProfileOut( __METHOD__
."-misc" );
1659 wfProfileIn( __METHOD__
."-title" );
1660 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1661 if ( $nt === null ) {
1662 $s .= $prefix . '[[' . $line;
1663 wfProfileOut( __METHOD__
."-title" );
1667 $ns = $nt->getNamespace();
1668 $iw = $nt->getInterWiki();
1669 wfProfileOut( __METHOD__
."-title" );
1671 if ( $might_be_img ) { # if this is actually an invalid link
1672 wfProfileIn( __METHOD__
."-might_be_img" );
1673 if ( $ns == NS_FILE
&& $noforce ) { #but might be an image
1676 #look at the next 'line' to see if we can close it there
1678 $next_line = $a->current();
1679 if ( $next_line === false ||
$next_line === null ) {
1682 $m = explode( ']]', $next_line, 3 );
1683 if ( count( $m ) == 3 ) {
1684 # the first ]] closes the inner link, the second the image
1686 $text .= "[[{$m[0]}]]{$m[1]}";
1689 } elseif ( count( $m ) == 2 ) {
1690 #if there's exactly one ]] that's fine, we'll keep looking
1691 $text .= "[[{$m[0]}]]{$m[1]}";
1693 #if $next_line is invalid too, we need look no further
1694 $text .= '[[' . $next_line;
1699 # we couldn't find the end of this imageLink, so output it raw
1700 #but don't ignore what might be perfectly normal links in the text we've examined
1701 $holders->merge( $this->replaceInternalLinks2( $text ) );
1702 $s .= "{$prefix}[[$link|$text";
1703 # note: no $trail, because without an end, there *is* no trail
1704 wfProfileOut( __METHOD__
."-might_be_img" );
1707 } else { #it's not an image, so output it raw
1708 $s .= "{$prefix}[[$link|$text";
1709 # note: no $trail, because without an end, there *is* no trail
1710 wfProfileOut( __METHOD__
."-might_be_img" );
1713 wfProfileOut( __METHOD__
."-might_be_img" );
1716 $wasblank = ( $text == '' );
1717 if ( $wasblank ) $text = $link;
1719 # Link not escaped by : , create the various objects
1723 wfProfileIn( __METHOD__
."-interwiki" );
1724 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1725 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1726 $s = rtrim($s . $prefix);
1727 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1728 wfProfileOut( __METHOD__
."-interwiki" );
1731 wfProfileOut( __METHOD__
."-interwiki" );
1733 if ( $ns == NS_FILE
) {
1734 wfProfileIn( __METHOD__
."-image" );
1735 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1737 # if no parameters were passed, $text
1738 # becomes something like "File:Foo.png",
1739 # which we don't want to pass on to the
1743 # recursively parse links inside the image caption
1744 # actually, this will parse them in any other parameters, too,
1745 # but it might be hard to fix that, and it doesn't matter ATM
1746 $text = $this->replaceExternalLinks($text);
1747 $holders->merge( $this->replaceInternalLinks2( $text ) );
1749 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1750 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1752 $s .= $prefix . $trail;
1754 $this->mOutput
->addImage( $nt->getDBkey() );
1755 wfProfileOut( __METHOD__
."-image" );
1760 if ( $ns == NS_CATEGORY
) {
1761 wfProfileIn( __METHOD__
."-category" );
1762 $s = rtrim($s . "\n"); # bug 87
1765 $sortkey = $this->getDefaultSort();
1769 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1770 $sortkey = str_replace( "\n", '', $sortkey );
1771 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1772 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1775 * Strip the whitespace Category links produce, see bug 87
1776 * @todo We might want to use trim($tmp, "\n") here.
1778 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1780 wfProfileOut( __METHOD__
."-category" );
1785 # Self-link checking
1786 if( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1787 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1788 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1793 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1794 # FIXME: Should do batch file existence checks, see comment below
1795 if( $ns == NS_MEDIA
) {
1796 wfProfileIn( __METHOD__
."-media" );
1797 # Give extensions a chance to select the file revision for us
1798 $skip = $time = false;
1799 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1801 $link = $sk->link( $nt );
1803 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1805 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1806 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1807 $this->mOutput
->addImage( $nt->getDBkey() );
1808 wfProfileOut( __METHOD__
."-media" );
1812 wfProfileIn( __METHOD__
."-always_known" );
1813 # Some titles, such as valid special pages or files in foreign repos, should
1814 # be shown as bluelinks even though they're not included in the page table
1816 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1817 # batch file existence checks for NS_FILE and NS_MEDIA
1818 if( $iw == '' && $nt->isAlwaysKnown() ) {
1819 $this->mOutput
->addLink( $nt );
1820 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1822 # Links will be added to the output link list after checking
1823 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1825 wfProfileOut( __METHOD__
."-always_known" );
1827 wfProfileOut( __METHOD__
);
1832 * Make a link placeholder. The text returned can be later resolved to a real link with
1833 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1834 * parsing of interwiki links, and secondly to allow all existence checks and
1835 * article length checks (for stub links) to be bundled into a single query.
1839 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1840 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1844 * Render a forced-blue link inline; protect against double expansion of
1845 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1846 * Since this little disaster has to split off the trail text to avoid
1847 * breaking URLs in the following text without breaking trails on the
1848 * wiki links, it's been made into a horrible function.
1851 * @param string $text
1852 * @param string $query
1853 * @param string $trail
1854 * @param string $prefix
1855 * @return string HTML-wikitext mix oh yuck
1857 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1858 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1859 $sk = $this->mOptions
->getSkin();
1860 // FIXME: use link() instead of deprecated makeKnownLinkObj()
1861 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1862 return $this->armorLinks( $link ) . $trail;
1866 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1867 * going to go through further parsing steps before inline URL expansion.
1869 * Not needed quite as much as it used to be since free links are a bit
1870 * more sensible these days. But bracketed links are still an issue.
1872 * @param string more-or-less HTML
1873 * @return string less-or-more HTML with NOPARSE bits
1875 function armorLinks( $text ) {
1876 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1877 "{$this->mUniqPrefix}NOPARSE$1", $text );
1881 * Return true if subpage links should be expanded on this page.
1884 function areSubpagesAllowed() {
1885 # Some namespaces don't allow subpages
1886 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
1890 * Handle link to subpage if necessary
1891 * @param string $target the source of the link
1892 * @param string &$text the link text, modified as necessary
1893 * @return string the full name of the link
1896 function maybeDoSubpageLink($target, &$text) {
1897 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
1901 * Used by doBlockLevels()
1904 /* private */ function closeParagraph() {
1906 if ( $this->mLastSection
!= '' ) {
1907 $result = '</' . $this->mLastSection
. ">\n";
1909 $this->mInPre
= false;
1910 $this->mLastSection
= '';
1913 # getCommon() returns the length of the longest common substring
1914 # of both arguments, starting at the beginning of both.
1916 /* private */ function getCommon( $st1, $st2 ) {
1917 $fl = strlen( $st1 );
1918 $shorter = strlen( $st2 );
1919 if ( $fl < $shorter ) { $shorter = $fl; }
1921 for ( $i = 0; $i < $shorter; ++
$i ) {
1922 if ( $st1{$i} != $st2{$i} ) { break; }
1926 # These next three functions open, continue, and close the list
1927 # element appropriate to the prefix character passed into them.
1929 /* private */ function openList( $char ) {
1930 $result = $this->closeParagraph();
1932 if ( '*' === $char ) { $result .= '<ul><li>'; }
1933 elseif ( '#' === $char ) { $result .= '<ol><li>'; }
1934 elseif ( ':' === $char ) { $result .= '<dl><dd>'; }
1935 elseif ( ';' === $char ) {
1936 $result .= '<dl><dt>';
1937 $this->mDTopen
= true;
1939 else { $result = '<!-- ERR 1 -->'; }
1944 /* private */ function nextItem( $char ) {
1945 if ( '*' === $char ||
'#' === $char ) { return '</li><li>'; }
1946 elseif ( ':' === $char ||
';' === $char ) {
1948 if ( $this->mDTopen
) { $close = '</dt>'; }
1949 if ( ';' === $char ) {
1950 $this->mDTopen
= true;
1951 return $close . '<dt>';
1953 $this->mDTopen
= false;
1954 return $close . '<dd>';
1957 return '<!-- ERR 2 -->';
1960 /* private */ function closeList( $char ) {
1961 if ( '*' === $char ) { $text = '</li></ul>'; }
1962 elseif ( '#' === $char ) { $text = '</li></ol>'; }
1963 elseif ( ':' === $char ) {
1964 if ( $this->mDTopen
) {
1965 $this->mDTopen
= false;
1966 $text = '</dt></dl>';
1968 $text = '</dd></dl>';
1971 else { return '<!-- ERR 3 -->'; }
1977 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
1979 * @param $linestart bool whether or not this is at the start of a line.
1981 * @return string the lists rendered as HTML
1983 function doBlockLevels( $text, $linestart ) {
1984 wfProfileIn( __METHOD__
);
1986 # Parsing through the text line by line. The main thing
1987 # happening here is handling of block-level elements p, pre,
1988 # and making lists from lines starting with * # : etc.
1990 $textLines = StringUtils
::explode( "\n", $text );
1992 $lastPrefix = $output = '';
1993 $this->mDTopen
= $inBlockElem = false;
1995 $paragraphStack = false;
1997 foreach ( $textLines as $oLine ) {
1999 if ( !$linestart ) {
2009 $lastPrefixLength = strlen( $lastPrefix );
2010 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2011 $preOpenMatch = preg_match('/<pre/i', $oLine );
2012 // If not in a <pre> element, scan for and figure out what prefixes are there.
2013 if ( !$this->mInPre
) {
2014 # Multiple prefixes may abut each other for nested lists.
2015 $prefixLength = strspn( $oLine, '*#:;' );
2016 $prefix = substr( $oLine, 0, $prefixLength );
2019 // ; and : are both from definition-lists, so they're equivalent
2020 // for the purposes of determining whether or not we need to open/close
2022 $prefix2 = str_replace( ';', ':', $prefix );
2023 $t = substr( $oLine, $prefixLength );
2024 $this->mInPre
= (bool)$preOpenMatch;
2026 # Don't interpret any other prefixes in preformatted text
2028 $prefix = $prefix2 = '';
2033 if( $prefixLength && $lastPrefix === $prefix2 ) {
2034 # Same as the last item, so no need to deal with nesting or opening stuff
2035 $output .= $this->nextItem( substr( $prefix, -1 ) );
2036 $paragraphStack = false;
2038 if ( substr( $prefix, -1 ) === ';') {
2039 # The one nasty exception: definition lists work like this:
2040 # ; title : definition text
2041 # So we check for : in the remainder text to split up the
2042 # title and definition, without b0rking links.
2044 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2046 $output .= $term . $this->nextItem( ':' );
2049 } elseif( $prefixLength ||
$lastPrefixLength ) {
2050 // We need to open or close prefixes, or both.
2052 # Either open or close a level...
2053 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2054 $paragraphStack = false;
2056 // Close all the prefixes which aren't shared.
2057 while( $commonPrefixLength < $lastPrefixLength ) {
2058 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2059 --$lastPrefixLength;
2062 // Continue the current prefix if appropriate.
2063 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2064 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2067 // Open prefixes where appropriate.
2068 while ( $prefixLength > $commonPrefixLength ) {
2069 $char = substr( $prefix, $commonPrefixLength, 1 );
2070 $output .= $this->openList( $char );
2072 if ( ';' === $char ) {
2073 # FIXME: This is dupe of code above
2074 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2076 $output .= $term . $this->nextItem( ':' );
2079 ++
$commonPrefixLength;
2081 $lastPrefix = $prefix2;
2084 // If we have no prefixes, go to paragraph mode.
2085 if( 0 == $prefixLength ) {
2086 wfProfileIn( __METHOD__
."-paragraph" );
2087 # No prefix (not in list)--go to paragraph mode
2088 // XXX: use a stack for nestable elements like span, table and div
2089 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2090 $closematch = preg_match(
2091 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2092 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2093 if ( $openmatch or $closematch ) {
2094 $paragraphStack = false;
2095 #Â TODO bug 5718: paragraph closed
2096 $output .= $this->closeParagraph();
2097 if ( $preOpenMatch and !$preCloseMatch ) {
2098 $this->mInPre
= true;
2100 if ( $closematch ) {
2101 $inBlockElem = false;
2103 $inBlockElem = true;
2105 } else if ( !$inBlockElem && !$this->mInPre
) {
2106 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' or trim($t) != '' ) ) {
2108 if ($this->mLastSection
!== 'pre') {
2109 $paragraphStack = false;
2110 $output .= $this->closeParagraph().'<pre>';
2111 $this->mLastSection
= 'pre';
2113 $t = substr( $t, 1 );
2116 if ( trim($t) == '' ) {
2117 if ( $paragraphStack ) {
2118 $output .= $paragraphStack.'<br />';
2119 $paragraphStack = false;
2120 $this->mLastSection
= 'p';
2122 if ($this->mLastSection
!== 'p' ) {
2123 $output .= $this->closeParagraph();
2124 $this->mLastSection
= '';
2125 $paragraphStack = '<p>';
2127 $paragraphStack = '</p><p>';
2131 if ( $paragraphStack ) {
2132 $output .= $paragraphStack;
2133 $paragraphStack = false;
2134 $this->mLastSection
= 'p';
2135 } else if ($this->mLastSection
!== 'p') {
2136 $output .= $this->closeParagraph().'<p>';
2137 $this->mLastSection
= 'p';
2142 wfProfileOut( __METHOD__
."-paragraph" );
2144 // somewhere above we forget to get out of pre block (bug 785)
2145 if($preCloseMatch && $this->mInPre
) {
2146 $this->mInPre
= false;
2148 if ($paragraphStack === false) {
2152 while ( $prefixLength ) {
2153 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2156 if ( $this->mLastSection
!= '' ) {
2157 $output .= '</' . $this->mLastSection
. '>';
2158 $this->mLastSection
= '';
2161 wfProfileOut( __METHOD__
);
2166 * Split up a string on ':', ignoring any occurences inside tags
2167 * to prevent illegal overlapping.
2168 * @param string $str the string to split
2169 * @param string &$before set to everything before the ':'
2170 * @param string &$after set to everything after the ':'
2171 * return string the position of the ':', or false if none found
2173 function findColonNoLinks($str, &$before, &$after) {
2174 wfProfileIn( __METHOD__
);
2176 $pos = strpos( $str, ':' );
2177 if( $pos === false ) {
2179 wfProfileOut( __METHOD__
);
2183 $lt = strpos( $str, '<' );
2184 if( $lt === false ||
$lt > $pos ) {
2185 // Easy; no tag nesting to worry about
2186 $before = substr( $str, 0, $pos );
2187 $after = substr( $str, $pos+
1 );
2188 wfProfileOut( __METHOD__
);
2192 // Ugly state machine to walk through avoiding tags.
2193 $state = self
::COLON_STATE_TEXT
;
2195 $len = strlen( $str );
2196 for( $i = 0; $i < $len; $i++
) {
2200 // (Using the number is a performance hack for common cases)
2201 case 0: // self::COLON_STATE_TEXT:
2204 // Could be either a <start> tag or an </end> tag
2205 $state = self
::COLON_STATE_TAGSTART
;
2210 $before = substr( $str, 0, $i );
2211 $after = substr( $str, $i +
1 );
2212 wfProfileOut( __METHOD__
);
2215 // Embedded in a tag; don't break it.
2218 // Skip ahead looking for something interesting
2219 $colon = strpos( $str, ':', $i );
2220 if( $colon === false ) {
2221 // Nothing else interesting
2222 wfProfileOut( __METHOD__
);
2225 $lt = strpos( $str, '<', $i );
2226 if( $stack === 0 ) {
2227 if( $lt === false ||
$colon < $lt ) {
2229 $before = substr( $str, 0, $colon );
2230 $after = substr( $str, $colon +
1 );
2231 wfProfileOut( __METHOD__
);
2235 if( $lt === false ) {
2236 // Nothing else interesting to find; abort!
2237 // We're nested, but there's no close tags left. Abort!
2240 // Skip ahead to next tag start
2242 $state = self
::COLON_STATE_TAGSTART
;
2245 case 1: // self::COLON_STATE_TAG:
2250 $state = self
::COLON_STATE_TEXT
;
2253 // Slash may be followed by >?
2254 $state = self
::COLON_STATE_TAGSLASH
;
2260 case 2: // self::COLON_STATE_TAGSTART:
2263 $state = self
::COLON_STATE_CLOSETAG
;
2266 $state = self
::COLON_STATE_COMMENT
;
2269 // Illegal early close? This shouldn't happen D:
2270 $state = self
::COLON_STATE_TEXT
;
2273 $state = self
::COLON_STATE_TAG
;
2276 case 3: // self::COLON_STATE_CLOSETAG:
2281 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2282 wfProfileOut( __METHOD__
);
2285 $state = self
::COLON_STATE_TEXT
;
2288 case self
::COLON_STATE_TAGSLASH
:
2290 // Yes, a self-closed tag <blah/>
2291 $state = self
::COLON_STATE_TEXT
;
2293 // Probably we're jumping the gun, and this is an attribute
2294 $state = self
::COLON_STATE_TAG
;
2297 case 5: // self::COLON_STATE_COMMENT:
2299 $state = self
::COLON_STATE_COMMENTDASH
;
2302 case self
::COLON_STATE_COMMENTDASH
:
2304 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2306 $state = self
::COLON_STATE_COMMENT
;
2309 case self
::COLON_STATE_COMMENTDASHDASH
:
2311 $state = self
::COLON_STATE_TEXT
;
2313 $state = self
::COLON_STATE_COMMENT
;
2317 throw new MWException( "State machine error in " . __METHOD__
);
2321 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2324 wfProfileOut( __METHOD__
);
2329 * Return value of a magic variable (like PAGENAME)
2333 function getVariableValue( $index, $frame=false ) {
2334 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2335 global $wgScriptPath, $wgStylePath;
2338 * Some of these require message or data lookups and can be
2339 * expensive to check many times.
2341 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2342 if ( isset( $this->mVarCache
[$index] ) ) {
2343 return $this->mVarCache
[$index];
2347 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2348 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2351 global $wgLocaltimezone;
2352 if ( isset( $wgLocaltimezone ) ) {
2353 $oldtz = date_default_timezone_get();
2354 date_default_timezone_set( $wgLocaltimezone );
2357 $localTimestamp = date( 'YmdHis', $ts );
2358 $localMonth = date( 'm', $ts );
2359 $localMonth1 = date( 'n', $ts );
2360 $localMonthName = date( 'n', $ts );
2361 $localDay = date( 'j', $ts );
2362 $localDay2 = date( 'd', $ts );
2363 $localDayOfWeek = date( 'w', $ts );
2364 $localWeek = date( 'W', $ts );
2365 $localYear = date( 'Y', $ts );
2366 $localHour = date( 'H', $ts );
2367 if ( isset( $wgLocaltimezone ) ) {
2368 date_default_timezone_set( $oldtz );
2372 case 'currentmonth':
2373 $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2375 case 'currentmonth1':
2376 $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2378 case 'currentmonthname':
2379 $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2381 case 'currentmonthnamegen':
2382 $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2384 case 'currentmonthabbrev':
2385 $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2388 $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2391 $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2394 $value = $wgContLang->formatNum( $localMonth );
2397 $value = $wgContLang->formatNum( $localMonth1 );
2399 case 'localmonthname':
2400 $value = $wgContLang->getMonthName( $localMonthName );
2402 case 'localmonthnamegen':
2403 $value = $wgContLang->getMonthNameGen( $localMonthName );
2405 case 'localmonthabbrev':
2406 $value = $wgContLang->getMonthAbbreviation( $localMonthName );
2409 $value = $wgContLang->formatNum( $localDay );
2412 $value = $wgContLang->formatNum( $localDay2 );
2415 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2418 $value = $this->mTitle
->getPartialURL();
2420 case 'fullpagename':
2421 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2423 case 'fullpagenamee':
2424 $value = $this->mTitle
->getPrefixedURL();
2427 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2429 case 'subpagenamee':
2430 $value = $this->mTitle
->getSubpageUrlForm();
2432 case 'basepagename':
2433 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2435 case 'basepagenamee':
2436 $value = wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2438 case 'talkpagename':
2439 if( $this->mTitle
->canTalk() ) {
2440 $talkPage = $this->mTitle
->getTalkPage();
2441 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2446 case 'talkpagenamee':
2447 if( $this->mTitle
->canTalk() ) {
2448 $talkPage = $this->mTitle
->getTalkPage();
2449 $value = $talkPage->getPrefixedUrl();
2454 case 'subjectpagename':
2455 $subjPage = $this->mTitle
->getSubjectPage();
2456 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2458 case 'subjectpagenamee':
2459 $subjPage = $this->mTitle
->getSubjectPage();
2460 $value = $subjPage->getPrefixedUrl();
2463 // Let the edit saving system know we should parse the page
2464 // *after* a revision ID has been assigned.
2465 $this->mOutput
->setFlag( 'vary-revision' );
2466 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2467 $value = $this->mRevisionId
;
2470 // Let the edit saving system know we should parse the page
2471 // *after* a revision ID has been assigned. This is for null edits.
2472 $this->mOutput
->setFlag( 'vary-revision' );
2473 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2474 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2476 case 'revisionday2':
2477 // Let the edit saving system know we should parse the page
2478 // *after* a revision ID has been assigned. This is for null edits.
2479 $this->mOutput
->setFlag( 'vary-revision' );
2480 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2481 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2483 case 'revisionmonth':
2484 // Let the edit saving system know we should parse the page
2485 // *after* a revision ID has been assigned. This is for null edits.
2486 $this->mOutput
->setFlag( 'vary-revision' );
2487 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2488 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2490 case 'revisionyear':
2491 // Let the edit saving system know we should parse the page
2492 // *after* a revision ID has been assigned. This is for null edits.
2493 $this->mOutput
->setFlag( 'vary-revision' );
2494 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2495 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2497 case 'revisiontimestamp':
2498 // Let the edit saving system know we should parse the page
2499 // *after* a revision ID has been assigned. This is for null edits.
2500 $this->mOutput
->setFlag( 'vary-revision' );
2501 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2502 $value = $this->getRevisionTimestamp();
2504 case 'revisionuser':
2505 // Let the edit saving system know we should parse the page
2506 // *after* a revision ID has been assigned. This is for null edits.
2507 $this->mOutput
->setFlag( 'vary-revision' );
2508 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2509 $value = $this->getRevisionUser();
2512 $value = str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2515 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2518 $value = $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2521 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2523 case 'subjectspace':
2524 $value = $this->mTitle
->getSubjectNsText();
2526 case 'subjectspacee':
2527 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2529 case 'currentdayname':
2530 $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2533 $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2536 $value = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2539 $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2542 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2543 // int to remove the padding
2544 $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2547 $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2549 case 'localdayname':
2550 $value = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2553 $value = $wgContLang->formatNum( $localYear, true );
2556 $value = $wgContLang->time( $localTimestamp, false, false );
2559 $value = $wgContLang->formatNum( $localHour, true );
2562 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2563 // int to remove the padding
2564 $value = $wgContLang->formatNum( (int)$localWeek );
2567 $value = $wgContLang->formatNum( $localDayOfWeek );
2569 case 'numberofarticles':
2570 $value = $wgContLang->formatNum( SiteStats
::articles() );
2572 case 'numberoffiles':
2573 $value = $wgContLang->formatNum( SiteStats
::images() );
2575 case 'numberofusers':
2576 $value = $wgContLang->formatNum( SiteStats
::users() );
2578 case 'numberofactiveusers':
2579 $value = $wgContLang->formatNum( SiteStats
::activeUsers() );
2581 case 'numberofpages':
2582 $value = $wgContLang->formatNum( SiteStats
::pages() );
2584 case 'numberofadmins':
2585 $value = $wgContLang->formatNum( SiteStats
::numberingroup('sysop') );
2587 case 'numberofedits':
2588 $value = $wgContLang->formatNum( SiteStats
::edits() );
2590 case 'numberofviews':
2591 $value = $wgContLang->formatNum( SiteStats
::views() );
2593 case 'currenttimestamp':
2594 $value = wfTimestamp( TS_MW
, $ts );
2596 case 'localtimestamp':
2597 $value = $localTimestamp;
2599 case 'currentversion':
2600 $value = SpecialVersion
::getVersion();
2607 return $wgServerName;
2609 return $wgScriptPath;
2611 return $wgStylePath;
2612 case 'directionmark':
2613 return $wgContLang->getDirMark();
2614 case 'contentlanguage':
2615 global $wgContLanguageCode;
2616 return $wgContLanguageCode;
2619 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) )
2626 $this->mVarCache
[$index] = $value;
2632 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2636 function initialiseVariables() {
2637 wfProfileIn( __METHOD__
);
2638 $variableIDs = MagicWord
::getVariableIDs();
2639 $substIDs = MagicWord
::getSubstIDs();
2641 $this->mVariables
= new MagicWordArray( $variableIDs );
2642 $this->mSubstWords
= new MagicWordArray( $substIDs );
2643 wfProfileOut( __METHOD__
);
2647 * Preprocess some wikitext and return the document tree.
2648 * This is the ghost of replace_variables().
2650 * @param string $text The text to parse
2651 * @param integer flags Bitwise combination of:
2652 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2653 * included. Default is to assume a direct page view.
2655 * The generated DOM tree must depend only on the input text and the flags.
2656 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2658 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2659 * change in the DOM tree for a given text, must be passed through the section identifier
2660 * in the section edit link and thus back to extractSections().
2662 * The output of this function is currently only cached in process memory, but a persistent
2663 * cache may be implemented at a later date which takes further advantage of these strict
2664 * dependency requirements.
2668 function preprocessToDom ( $text, $flags = 0 ) {
2669 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2674 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2676 public static function splitWhitespace( $s ) {
2677 $ltrimmed = ltrim( $s );
2678 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2679 $trimmed = rtrim( $ltrimmed );
2680 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2682 $w2 = substr( $ltrimmed, -$diff );
2686 return array( $w1, $trimmed, $w2 );
2690 * Replace magic variables, templates, and template arguments
2691 * with the appropriate text. Templates are substituted recursively,
2692 * taking care to avoid infinite loops.
2694 * Note that the substitution depends on value of $mOutputType:
2695 * self::OT_WIKI: only {{subst:}} templates
2696 * self::OT_PREPROCESS: templates but not extension tags
2697 * self::OT_HTML: all templates and extension tags
2699 * @param string $tex The text to transform
2700 * @param PPFrame $frame Object describing the arguments passed to the template.
2701 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2702 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2703 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2706 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2707 # Is there any text? Also, Prevent too big inclusions!
2708 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2711 wfProfileIn( __METHOD__
);
2713 if ( $frame === false ) {
2714 $frame = $this->getPreprocessor()->newFrame();
2715 } elseif ( !( $frame instanceof PPFrame
) ) {
2716 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2717 $frame = $this->getPreprocessor()->newCustomFrame($frame);
2720 $dom = $this->preprocessToDom( $text );
2721 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2722 $text = $frame->expand( $dom, $flags );
2724 wfProfileOut( __METHOD__
);
2728 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2729 static function createAssocArgs( $args ) {
2730 $assocArgs = array();
2732 foreach( $args as $arg ) {
2733 $eqpos = strpos( $arg, '=' );
2734 if ( $eqpos === false ) {
2735 $assocArgs[$index++
] = $arg;
2737 $name = trim( substr( $arg, 0, $eqpos ) );
2738 $value = trim( substr( $arg, $eqpos+
1 ) );
2739 if ( $value === false ) {
2742 if ( $name !== false ) {
2743 $assocArgs[$name] = $value;
2752 * Warn the user when a parser limitation is reached
2753 * Will warn at most once the user per limitation type
2755 * @param string $limitationType, should be one of:
2756 * 'expensive-parserfunction' (corresponding messages: 'expensive-parserfunction-warning', 'expensive-parserfunction-category')
2757 * 'post-expand-template-argument' (corresponding messages: 'post-expand-template-argument-warning', 'post-expand-template-argument-category')
2758 * 'post-expand-template-inclusion' (corresponding messages: 'post-expand-template-inclusion-warning', 'post-expand-template-inclusion-category')
2759 * @params int $current, $max When an explicit limit has been
2760 * exceeded, provide the values (optional)
2762 function limitationWarn( $limitationType, $current=null, $max=null) {
2763 //does no harm if $current and $max are present but are unnecessary for the message
2764 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
2765 $this->mOutput
->addWarning( $warning );
2766 $this->addTrackingCategory( "$limitationType-category" );
2770 * Return the text of a template, after recursively
2771 * replacing any variables or templates within the template.
2773 * @param array $piece The parts of the template
2774 * $piece['title']: the title, i.e. the part before the |
2775 * $piece['parts']: the parameter array
2776 * $piece['lineStart']: whether the brace was at the start of a line
2777 * @param PPFrame The current frame, contains template arguments
2778 * @return string the text of the template
2781 function braceSubstitution( $piece, $frame ) {
2782 global $wgContLang, $wgNonincludableNamespaces;
2783 wfProfileIn( __METHOD__
);
2784 wfProfileIn( __METHOD__
.'-setup' );
2787 $found = false; # $text has been filled
2788 $nowiki = false; # wiki markup in $text should be escaped
2789 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2790 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2791 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2792 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2794 # Title object, where $text came from
2797 # $part1 is the bit before the first |, and must contain only title characters.
2798 # Various prefixes will be stripped from it later.
2799 $titleWithSpaces = $frame->expand( $piece['title'] );
2800 $part1 = trim( $titleWithSpaces );
2803 # Original title text preserved for various purposes
2804 $originalTitle = $part1;
2806 # $args is a list of argument nodes, starting from index 0, not including $part1
2807 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2808 wfProfileOut( __METHOD__
.'-setup' );
2811 wfProfileIn( __METHOD__
.'-modifiers' );
2814 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
2816 # Possibilities for substMatch: "subst", "safesubst" or FALSE
2817 # Decide whether to expand template or keep wikitext as-is.
2818 if ( $this->ot
['wiki'] ) {
2819 if ( $substMatch === false ) {
2820 $literal = true; # literal when in PST with no prefix
2822 $literal = false; # expand when in PST with subst: or safesubst:
2825 if ( $substMatch == 'subst' ) {
2826 $literal = true; # literal when not in PST with plain subst:
2828 $literal = false; # expand when not in PST with safesubst: or no prefix
2832 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2839 if ( !$found && $args->getLength() == 0 ) {
2840 $id = $this->mVariables
->matchStartToEnd( $part1 );
2841 if ( $id !== false ) {
2842 $text = $this->getVariableValue( $id, $frame );
2843 if (MagicWord
::getCacheTTL($id)>-1)
2844 $this->mOutput
->mContainsOldMagic
= true;
2849 # MSG, MSGNW and RAW
2852 $mwMsgnw = MagicWord
::get( 'msgnw' );
2853 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2856 # Remove obsolete MSG:
2857 $mwMsg = MagicWord
::get( 'msg' );
2858 $mwMsg->matchStartAndRemove( $part1 );
2862 $mwRaw = MagicWord
::get( 'raw' );
2863 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2864 $forceRawInterwiki = true;
2867 wfProfileOut( __METHOD__
.'-modifiers' );
2871 wfProfileIn( __METHOD__
. '-pfunc' );
2873 $colonPos = strpos( $part1, ':' );
2874 if ( $colonPos !== false ) {
2875 # Case sensitive functions
2876 $function = substr( $part1, 0, $colonPos );
2877 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2878 $function = $this->mFunctionSynonyms
[1][$function];
2880 # Case insensitive functions
2881 $function = $wgContLang->lc( $function );
2882 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2883 $function = $this->mFunctionSynonyms
[0][$function];
2889 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2890 $initialArgs = array( &$this );
2891 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2892 if ( $flags & SFH_OBJECT_ARGS
) {
2893 # Add a frame parameter, and pass the arguments as an array
2894 $allArgs = $initialArgs;
2895 $allArgs[] = $frame;
2896 for ( $i = 0; $i < $args->getLength(); $i++
) {
2897 $funcArgs[] = $args->item( $i );
2899 $allArgs[] = $funcArgs;
2901 # Convert arguments to plain text
2902 for ( $i = 0; $i < $args->getLength(); $i++
) {
2903 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2905 $allArgs = array_merge( $initialArgs, $funcArgs );
2908 # Workaround for PHP bug 35229 and similar
2909 if ( !is_callable( $callback ) ) {
2910 wfProfileOut( __METHOD__
. '-pfunc' );
2911 wfProfileOut( __METHOD__
);
2912 throw new MWException( "Tag hook for $function is not callable\n" );
2914 $result = call_user_func_array( $callback, $allArgs );
2917 $preprocessFlags = 0;
2919 if ( is_array( $result ) ) {
2920 if ( isset( $result[0] ) ) {
2922 unset( $result[0] );
2925 // Extract flags into the local scope
2926 // This allows callers to set flags such as nowiki, found, etc.
2932 $text = $this->preprocessToDom( $text, $preprocessFlags );
2937 wfProfileOut( __METHOD__
. '-pfunc' );
2940 # Finish mangling title and then check for loops.
2941 # Set $title to a Title object and $titleText to the PDBK
2944 # Split the title into page and subpage
2946 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2947 if ($subpage !== '') {
2948 $ns = $this->mTitle
->getNamespace();
2950 $title = Title
::newFromText( $part1, $ns );
2952 $titleText = $title->getPrefixedText();
2953 # Check for language variants if the template is not found
2954 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2955 $wgContLang->findVariantLink( $part1, $title, true );
2957 # Do recursion depth check
2958 $limit = $this->mOptions
->getMaxTemplateDepth();
2959 if ( $frame->depth
>= $limit ) {
2961 $text = '<span class="error">' . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit ) . '</span>';
2966 # Load from database
2967 if ( !$found && $title ) {
2968 wfProfileIn( __METHOD__
. '-loadtpl' );
2969 if ( !$title->isExternal() ) {
2970 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2971 $text = SpecialPage
::capturePath( $title );
2972 if ( is_string( $text ) ) {
2975 $this->disableCache();
2977 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2978 $found = false; //access denied
2979 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
2981 list( $text, $title ) = $this->getTemplateDom( $title );
2982 if ( $text !== false ) {
2988 # If the title is valid but undisplayable, make a link to it
2989 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2990 $text = "[[:$titleText]]";
2993 } elseif ( $title->isTrans() ) {
2994 // Interwiki transclusion
2995 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
2996 $text = $this->interwikiTransclude( $title, 'render' );
2999 $text = $this->interwikiTransclude( $title, 'raw' );
3000 // Preprocess it like a template
3001 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3007 # Do infinite loop check
3008 # This has to be done after redirect resolution to avoid infinite loops via redirects
3009 if ( !$frame->loopCheck( $title ) ) {
3011 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3012 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3014 wfProfileOut( __METHOD__
. '-loadtpl' );
3017 # If we haven't found text to substitute by now, we're done
3018 # Recover the source wikitext and return it
3020 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3021 wfProfileOut( __METHOD__
);
3022 return array( 'object' => $text );
3025 # Expand DOM-style return values in a child frame
3026 if ( $isChildObj ) {
3027 # Clean up argument array
3028 $newFrame = $frame->newChild( $args, $title );
3031 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3032 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3033 # Expansion is eligible for the empty-frame cache
3034 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3035 $text = $this->mTplExpandCache
[$titleText];
3037 $text = $newFrame->expand( $text );
3038 $this->mTplExpandCache
[$titleText] = $text;
3041 # Uncached expansion
3042 $text = $newFrame->expand( $text );
3045 if ( $isLocalObj && $nowiki ) {
3046 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3047 $isLocalObj = false;
3050 # Replace raw HTML by a placeholder
3051 # Add a blank line preceding, to prevent it from mucking up
3052 # immediately preceding headings
3054 $text = "\n\n" . $this->insertStripItem( $text );
3056 # Escape nowiki-style return values
3057 elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3058 $text = wfEscapeWikiText( $text );
3060 # Bug 529: if the template begins with a table or block-level
3061 # element, it should be treated as beginning a new line.
3062 # This behaviour is somewhat controversial.
3063 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3064 $text = "\n" . $text;
3067 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3068 # Error, oversize inclusion
3069 $text = "[[$originalTitle]]" .
3070 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3071 $this->limitationWarn( 'post-expand-template-inclusion' );
3074 if ( $isLocalObj ) {
3075 $ret = array( 'object' => $text );
3077 $ret = array( 'text' => $text );
3080 wfProfileOut( __METHOD__
);
3085 * Get the semi-parsed DOM representation of a template with a given title,
3086 * and its redirect destination title. Cached.
3088 function getTemplateDom( $title ) {
3089 $cacheTitle = $title;
3090 $titleText = $title->getPrefixedDBkey();
3092 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3093 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3094 $title = Title
::makeTitle( $ns, $dbk );
3095 $titleText = $title->getPrefixedDBkey();
3097 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3098 return array( $this->mTplDomCache
[$titleText], $title );
3101 // Cache miss, go to the database
3102 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3104 if ( $text === false ) {
3105 $this->mTplDomCache
[$titleText] = false;
3106 return array( false, $title );
3109 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3110 $this->mTplDomCache
[ $titleText ] = $dom;
3112 if (! $title->equals($cacheTitle)) {
3113 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3114 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3117 return array( $dom, $title );
3121 * Fetch the unparsed text of a template and register a reference to it.
3123 function fetchTemplateAndTitle( $title ) {
3124 $templateCb = $this->mOptions
->getTemplateCallback();
3125 $stuff = call_user_func( $templateCb, $title, $this );
3126 $text = $stuff['text'];
3127 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3128 if ( isset( $stuff['deps'] ) ) {
3129 foreach ( $stuff['deps'] as $dep ) {
3130 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3133 return array($text,$finalTitle);
3136 function fetchTemplate( $title ) {
3137 $rv = $this->fetchTemplateAndTitle($title);
3142 * Static function to get a template
3143 * Can be overridden via ParserOptions::setTemplateCallback().
3145 static function statelessFetchTemplate( $title, $parser=false ) {
3146 $text = $skip = false;
3147 $finalTitle = $title;
3150 // Loop to fetch the article, with up to 1 redirect
3151 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3152 # Give extensions a chance to select the revision instead
3153 $id = false; // Assume current
3154 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3160 'page_id' => $title->getArticleID(),
3164 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3165 $rev_id = $rev ?
$rev->getId() : 0;
3166 // If there is no current revision, there is no page
3167 if( $id === false && !$rev ) {
3168 $linkCache = LinkCache
::singleton();
3169 $linkCache->addBadLinkObj( $title );
3174 'page_id' => $title->getArticleID(),
3175 'rev_id' => $rev_id );
3178 $text = $rev->getText();
3179 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3181 $message = $wgContLang->lcfirst( $title->getText() );
3182 $text = wfMsgForContentNoTrans( $message );
3183 if( wfEmptyMsg( $message, $text ) ) {
3190 if ( $text === false ) {
3194 $finalTitle = $title;
3195 $title = Title
::newFromRedirect( $text );
3199 'finalTitle' => $finalTitle,
3204 * Transclude an interwiki link.
3206 function interwikiTransclude( $title, $action ) {
3207 global $wgEnableScaryTranscluding;
3209 if (!$wgEnableScaryTranscluding)
3210 return wfMsg('scarytranscludedisabled');
3212 $url = $title->getFullUrl( "action=$action" );
3214 if (strlen($url) > 255)
3215 return wfMsg('scarytranscludetoolong');
3216 return $this->fetchScaryTemplateMaybeFromCache($url);
3219 function fetchScaryTemplateMaybeFromCache($url) {
3220 global $wgTranscludeCacheExpiry;
3221 $dbr = wfGetDB(DB_SLAVE
);
3222 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3223 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3224 array('tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3226 return $obj->tc_contents
;
3229 $text = Http
::get($url);
3231 return wfMsg('scarytranscludefailed', $url);
3233 $dbw = wfGetDB(DB_MASTER
);
3234 $dbw->replace('transcache', array('tc_url'), array(
3236 'tc_time' => $dbw->timestamp( time() ),
3237 'tc_contents' => $text));
3243 * Triple brace replacement -- used for template arguments
3246 function argSubstitution( $piece, $frame ) {
3247 wfProfileIn( __METHOD__
);
3250 $parts = $piece['parts'];
3251 $nameWithSpaces = $frame->expand( $piece['title'] );
3252 $argName = trim( $nameWithSpaces );
3254 $text = $frame->getArgument( $argName );
3255 if ( $text === false && $parts->getLength() > 0
3259 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3262 # No match in frame, use the supplied default
3263 $object = $parts->item( 0 )->getChildren();
3265 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3266 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3267 $this->limitationWarn( 'post-expand-template-argument' );
3270 if ( $text === false && $object === false ) {
3272 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3274 if ( $error !== false ) {
3277 if ( $object !== false ) {
3278 $ret = array( 'object' => $object );
3280 $ret = array( 'text' => $text );
3283 wfProfileOut( __METHOD__
);
3288 * Return the text to be used for a given extension tag.
3289 * This is the ghost of strip().
3291 * @param array $params Associative array of parameters:
3292 * name PPNode for the tag name
3293 * attr PPNode for unparsed text where tag attributes are thought to be
3294 * attributes Optional associative array of parsed attributes
3295 * inner Contents of extension element
3296 * noClose Original text did not have a close tag
3297 * @param PPFrame $frame
3299 function extensionSubstitution( $params, $frame ) {
3300 global $wgRawHtml, $wgContLang;
3302 $name = $frame->expand( $params['name'] );
3303 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3304 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3305 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3307 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3308 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3309 if ( $isFunctionTag ) {
3310 $markerType = 'none';
3312 $markerType = 'general';
3314 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3315 $name = strtolower( $name );
3316 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3317 if ( isset( $params['attributes'] ) ) {
3318 $attributes = $attributes +
$params['attributes'];
3321 if( isset( $this->mTagHooks
[$name] ) ) {
3322 # Workaround for PHP bug 35229 and similar
3323 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3324 throw new MWException( "Tag hook for $name is not callable\n" );
3326 $output = call_user_func_array( $this->mTagHooks
[$name],
3327 array( $content, $attributes, $this, $frame ) );
3328 } elseif( isset( $this->mFunctionTagHooks
[$name] ) ) {
3329 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3330 if( !is_callable( $callback ) )
3331 throw new MWException( "Tag hook for $name is not callable\n" );
3333 $output = call_user_func_array( $callback,
3334 array( &$this, $frame, $content, $attributes ) );
3336 $output = '<span class="error">Invalid tag extension name: ' .
3337 htmlspecialchars( $name ) . '</span>';
3340 if ( is_array( $output ) ) {
3341 // Extract flags to local scope (to override $markerType)
3343 $output = $flags[0];
3348 if ( is_null( $attrText ) ) {
3351 if ( isset( $params['attributes'] ) ) {
3352 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3353 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3354 htmlspecialchars( $attrValue ) . '"';
3357 if ( $content === null ) {
3358 $output = "<$name$attrText/>";
3360 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3361 $output = "<$name$attrText>$content$close";
3365 if( $markerType === 'none' ) {
3367 } elseif ( $markerType === 'nowiki' ) {
3368 $this->mStripState
->nowiki
->setPair( $marker, $output );
3369 } elseif ( $markerType === 'general' ) {
3370 $this->mStripState
->general
->setPair( $marker, $output );
3372 throw new MWException( __METHOD__
.': invalid marker type' );
3378 * Increment an include size counter
3380 * @param string $type The type of expansion
3381 * @param integer $size The size of the text
3382 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3384 function incrementIncludeSize( $type, $size ) {
3385 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3388 $this->mIncludeSizes
[$type] +
= $size;
3394 * Increment the expensive function count
3396 * @return boolean False if the limit has been exceeded
3398 function incrementExpensiveFunctionCount() {
3399 global $wgExpensiveParserFunctionLimit;
3400 $this->mExpensiveFunctionCount++
;
3401 if($this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit) {
3408 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3409 * Fills $this->mDoubleUnderscores, returns the modified text
3411 function doDoubleUnderscore( $text ) {
3412 wfProfileIn( __METHOD__
);
3414 // The position of __TOC__ needs to be recorded
3415 $mw = MagicWord
::get( 'toc' );
3416 if( $mw->match( $text ) ) {
3417 $this->mShowToc
= true;
3418 $this->mForceTocPosition
= true;
3420 // Set a placeholder. At the end we'll fill it in with the TOC.
3421 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3423 // Only keep the first one.
3424 $text = $mw->replace( '', $text );
3427 // Now match and remove the rest of them
3428 $mwa = MagicWord
::getDoubleUnderscoreArray();
3429 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3431 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3432 $this->mOutput
->mNoGallery
= true;
3434 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3435 $this->mShowToc
= false;
3437 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3438 $this->mOutput
->setProperty( 'hiddencat', 'y' );
3439 $this->addTrackingCategory( 'hidden-category-category' );
3441 # (bug 8068) Allow control over whether robots index a page.
3443 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3444 # is not desirable, the last one on the page should win.
3445 if( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3446 $this->mOutput
->setIndexPolicy( 'noindex' );
3447 $this->addTrackingCategory( 'noindex-category' );
3449 if( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ){
3450 $this->mOutput
->setIndexPolicy( 'index' );
3451 $this->addTrackingCategory( 'index-category' );
3454 wfProfileOut( __METHOD__
);
3459 * Add a tracking category, getting the title from a system message,
3460 * or print a debug message if the title is invalid.
3461 * @param $msg String message key
3462 * @return Bool whether the addition was successful
3464 protected function addTrackingCategory( $msg ){
3465 $cat = wfMsgForContent( $msg );
3467 # Allow tracking categories to be disabled by setting them to "-"
3468 if( $cat === '-' ) return false;
3470 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3471 if ( $containerCategory ) {
3472 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3475 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3481 * This function accomplishes several tasks:
3482 * 1) Auto-number headings if that option is enabled
3483 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3484 * 3) Add a Table of contents on the top for users who have enabled the option
3485 * 4) Auto-anchor headings
3487 * It loops through all headlines, collects the necessary data, then splits up the
3488 * string and re-inserts the newly formatted headlines.
3490 * @param string $text
3491 * @param string $origText Original, untouched wikitext
3492 * @param boolean $isMain
3495 function formatHeadings( $text, $origText, $isMain=true ) {
3496 global $wgMaxTocLevel, $wgContLang, $wgHtml5, $wgExperimentalHtmlIds;
3498 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3499 $showEditLink = $this->mOptions
->getEditSection();
3501 // Do not call quickUserCan unless necessary
3502 if( $showEditLink && !$this->mTitle
->quickUserCan( 'edit' ) ) {
3506 # Inhibit editsection links if requested in the page
3507 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ||
$this->mOptions
->getIsPrintable() ) {
3511 # Get all headlines for numbering them and adding funky stuff like [edit]
3512 # links - this is for later, but we need the number of headlines right now
3514 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3516 # if there are fewer than 4 headlines in the article, do not show TOC
3517 # unless it's been explicitly enabled.
3518 $enoughToc = $this->mShowToc
&&
3519 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3521 # Allow user to stipulate that a page should have a "new section"
3522 # link added via __NEWSECTIONLINK__
3523 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3524 $this->mOutput
->setNewSection( true );
3527 # Allow user to remove the "new section"
3528 # link via __NONEWSECTIONLINK__
3529 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3530 $this->mOutput
->hideNewSection( true );
3533 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3534 # override above conditions and always show TOC above first header
3535 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3536 $this->mShowToc
= true;
3540 # We need this to perform operations on the HTML
3541 $sk = $this->mOptions
->getSkin();
3547 # Ugh .. the TOC should have neat indentation levels which can be
3548 # passed to the skin functions. These are determined here
3552 $sublevelCount = array();
3553 $levelCount = array();
3559 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3560 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3561 $oldType = $this->mOutputType
;
3562 $this->setOutputType( self
::OT_WIKI
);
3563 $frame = $this->getPreprocessor()->newFrame();
3564 $root = $this->preprocessToDom( $origText );
3565 $node = $root->getFirstChild();
3569 foreach( $matches[3] as $headline ) {
3570 $isTemplate = false;
3572 $sectionIndex = false;
3574 $markerMatches = array();
3575 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3576 $serial = $markerMatches[1];
3577 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3578 $isTemplate = ($titleText != $baseTitleText);
3579 $headline = preg_replace("/^$markerRegex/", "", $headline);
3583 $prevlevel = $level;
3584 $prevtoclevel = $toclevel;
3586 $level = $matches[1][$headlineCount];
3588 if ( $level > $prevlevel ) {
3589 # Increase TOC level
3591 $sublevelCount[$toclevel] = 0;
3592 if( $toclevel<$wgMaxTocLevel ) {
3593 $prevtoclevel = $toclevel;
3594 $toc .= $sk->tocIndent();
3598 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3599 # Decrease TOC level, find level to jump to
3601 for ($i = $toclevel; $i > 0; $i--) {
3602 if ( $levelCount[$i] == $level ) {
3603 # Found last matching level
3607 elseif ( $levelCount[$i] < $level ) {
3608 # Found first matching level below current level
3613 if( $i == 0 ) $toclevel = 1;
3614 if( $toclevel<$wgMaxTocLevel ) {
3615 if($prevtoclevel < $wgMaxTocLevel) {
3616 # Unindent only if the previous toc level was shown :p
3617 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3618 $prevtoclevel = $toclevel;
3620 $toc .= $sk->tocLineEnd();
3625 # No change in level, end TOC line
3626 if( $toclevel<$wgMaxTocLevel ) {
3627 $toc .= $sk->tocLineEnd();
3631 $levelCount[$toclevel] = $level;
3633 # count number of headlines for each level
3634 @$sublevelCount[$toclevel]++
;
3636 for( $i = 1; $i <= $toclevel; $i++
) {
3637 if( !empty( $sublevelCount[$i] ) ) {
3641 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3646 # The safe header is a version of the header text safe to use for links
3647 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3648 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3650 # Remove link placeholders by the link text.
3651 # <!--LINK number-->
3653 # link text with suffix
3654 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3656 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3657 $tocline = preg_replace(
3658 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3662 $tocline = trim( $tocline );
3664 # For the anchor, strip out HTML-y stuff period
3665 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3666 $safeHeadline = preg_replace( '/[ _]+/', ' ', $safeHeadline );
3667 $safeHeadline = trim( $safeHeadline );
3669 # Save headline for section edit hint before it's escaped
3670 $headlineHint = $safeHeadline;
3672 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
3673 # For reverse compatibility, provide an id that's
3674 # HTML4-compatible, like we used to.
3676 # It may be worth noting, academically, that it's possible for
3677 # the legacy anchor to conflict with a non-legacy headline
3678 # anchor on the page. In this case likely the "correct" thing
3679 # would be to either drop the legacy anchors or make sure
3680 # they're numbered first. However, this would require people
3681 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3682 # manually, so let's not bother worrying about it.
3683 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
3684 array( 'noninitial', 'legacy' ) );
3685 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3687 if ( $legacyHeadline == $safeHeadline ) {
3688 # No reason to have both (in fact, we can't)
3689 $legacyHeadline = false;
3692 $legacyHeadline = false;
3693 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
3697 # HTML names must be case-insensitively unique (bug 10721). FIXME:
3698 # Does this apply to Unicode characters? Because we aren't
3699 # handling those here.
3700 $arrayKey = strtolower( $safeHeadline );
3701 if ( $legacyHeadline === false ) {
3702 $legacyArrayKey = false;
3704 $legacyArrayKey = strtolower( $legacyHeadline );
3707 # count how many in assoc. array so we can track dupes in anchors
3708 if ( isset( $refers[$arrayKey] ) ) {
3709 $refers[$arrayKey]++
;
3711 $refers[$arrayKey] = 1;
3713 if ( isset( $refers[$legacyArrayKey] ) ) {
3714 $refers[$legacyArrayKey]++
;
3716 $refers[$legacyArrayKey] = 1;
3719 # Don't number the heading if it is the only one (looks silly)
3720 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3721 # the two are different if the line contains a link
3722 $headline = $numbering . ' ' . $headline;
3725 # Create the anchor for linking from the TOC to the section
3726 $anchor = $safeHeadline;
3727 $legacyAnchor = $legacyHeadline;
3728 if ( $refers[$arrayKey] > 1 ) {
3729 $anchor .= '_' . $refers[$arrayKey];
3731 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3732 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3734 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3735 $toc .= $sk->tocLine($anchor, $tocline,
3736 $numbering, $toclevel, ($isTemplate ?
false : $sectionIndex));
3739 # Add the section to the section tree
3740 # Find the DOM node for this header
3741 while ( $node && !$isTemplate ) {
3742 if ( $node->getName() === 'h' ) {
3743 $bits = $node->splitHeading();
3744 if ( $bits['i'] == $sectionIndex )
3747 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
3748 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
3749 $node = $node->getNextSibling();
3752 'toclevel' => $toclevel,
3755 'number' => $numbering,
3756 'index' => ($isTemplate ?
'T-' : '' ) . $sectionIndex,
3757 'fromtitle' => $titleText,
3758 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
3759 'anchor' => $anchor,
3762 # give headline the correct <h#> tag
3763 if( $showEditLink && $sectionIndex !== false ) {
3765 # Put a T flag in the section identifier, to indicate to extractSections()
3766 # that sections inside <includeonly> should be counted.
3767 $editlink = $sk->doEditSectionLink(Title
::newFromText( $titleText ), "T-$sectionIndex");
3769 $editlink = $sk->doEditSectionLink($this->mTitle
, $sectionIndex, $headlineHint);
3774 $head[$headlineCount] = $sk->makeHeadline( $level,
3775 $matches['attrib'][$headlineCount], $anchor, $headline,
3776 $editlink, $legacyAnchor );
3781 $this->setOutputType( $oldType );
3783 # Never ever show TOC if no headers
3784 if( $numVisible < 1 ) {
3789 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3790 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3792 $toc = $sk->tocList( $toc );
3793 $this->mOutput
->setTOCHTML( $toc );
3797 $this->mOutput
->setSections( $tocraw );
3800 # split up and insert constructed headlines
3802 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3805 foreach( $blocks as $block ) {
3806 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3807 # This is the [edit] link that appears for the top block of text when
3808 # section editing is enabled
3810 # Disabled because it broke block formatting
3811 # For example, a bullet point in the top line
3812 # $full .= $sk->editSectionLink(0);
3815 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3816 # Top anchor now in skin
3820 if( !empty( $head[$i] ) ) {
3825 if( $this->mForceTocPosition
) {
3826 return str_replace( '<!--MWTOC-->', $toc, $full );
3833 * Merge $tree2 into $tree1 by replacing the section with index
3834 * $section in $tree1 and its descendants with the sections in $tree2.
3835 * Note that in the returned section tree, only the 'index' and
3836 * 'byteoffset' fields are guaranteed to be correct.
3837 * @param $tree1 array Section tree from ParserOutput::getSectons()
3838 * @param $tree2 array Section tree
3839 * @param $section int Section index
3840 * @param $title Title Title both section trees come from
3841 * @param $len2 int Length of the original wikitext for $tree2
3842 * @return array Merged section tree
3844 public static function mergeSectionTrees( $tree1, $tree2, $section, $title, $len2 ) {
3847 $targetLevel = false;
3851 $numbering = array( 0 );
3852 $titletext = $title->getPrefixedDBkey();
3853 foreach ( $tree1 as $s ) {
3854 if ( $targetLevel !== false ) {
3855 if ( $s['level'] <= $targetLevel )
3856 // We've skipped enough
3857 $targetLevel = false;
3861 if ( $s['index'] != $section ||
3862 $s['fromtitle'] != $titletext ) {
3863 self
::incrementNumbering( $numbering,
3864 $s['toclevel'], $lastLevel );
3866 // Rewrite index, byteoffset and number
3867 if ( $s['fromtitle'] == $titletext ) {
3868 $s['index'] = $nextIndex++
;
3870 $s['byteoffset'] +
= $len2;
3872 $s['number'] = implode( '.', array_map(
3873 array( $wgContLang, 'formatnum' ),
3875 $lastLevel = $s['toclevel'];
3878 // We're at $section
3879 // Insert sections from $tree2 here
3880 foreach ( $tree2 as $s2 ) {
3881 // Rewrite the fields in $s2
3882 // before inserting it
3883 $s2['toclevel'] +
= $s['toclevel'] - 1;
3884 $s2['level'] +
= $s['level'] - 1;
3885 $s2['index'] = $nextIndex++
;
3886 $s2['byteoffset'] +
= $s['byteoffset'];
3888 self
::incrementNumbering( $numbering,
3889 $s2['toclevel'], $lastLevel );
3890 $s2['number'] = implode( '.', array_map(
3891 array( $wgContLang, 'formatnum' ),
3893 $lastLevel = $s2['toclevel'];
3896 // Skip all descendants of $section in $tree1
3897 $targetLevel = $s['level'];
3905 * Increment a section number. Helper function for mergeSectionTrees()
3906 * @param $number array Array representing a section number
3907 * @param $level int Current TOC level (depth)
3908 * @param $lastLevel int Level of previous TOC entry
3910 private static function incrementNumbering( &$number, $level, $lastLevel ) {
3911 if ( $level > $lastLevel )
3912 $number[$level - 1] = 1;
3913 else if ( $level < $lastLevel ) {
3914 foreach ( $number as $key => $unused )
3915 if ( $key >= $level )
3916 unset( $number[$key] );
3917 $number[$level - 1]++
;
3919 $number[$level - 1]++
;
3923 * Transform wiki markup when saving a page by doing \r\n -> \n
3924 * conversion, substitting signatures, {{subst:}} templates, etc.
3926 * @param string $text the text to transform
3927 * @param Title &$title the Title object for the current article
3928 * @param User $user the User object describing the current user
3929 * @param ParserOptions $options parsing options
3930 * @param bool $clearState whether to clear the parser state first
3931 * @return string the altered wiki markup
3934 function preSaveTransform( $text, Title
$title, $user, $options, $clearState = true ) {
3935 $this->mOptions
= $options;
3936 $this->setTitle( $title );
3937 $this->setOutputType( self
::OT_WIKI
);
3939 if ( $clearState ) {
3940 $this->clearState();
3946 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3947 $text = $this->pstPass2( $text, $user );
3948 $text = $this->mStripState
->unstripBoth( $text );
3953 * Pre-save transform helper function
3956 function pstPass2( $text, $user ) {
3957 global $wgContLang, $wgLocaltimezone;
3959 /* Note: This is the timestamp saved as hardcoded wikitext to
3960 * the database, we use $wgContLang here in order to give
3961 * everyone the same signature and use the default one rather
3962 * than the one selected in each user's preferences.
3964 * (see also bug 12815)
3966 $ts = $this->mOptions
->getTimestamp();
3967 if ( isset( $wgLocaltimezone ) ) {
3968 $tz = $wgLocaltimezone;
3970 $tz = date_default_timezone_get();
3973 $unixts = wfTimestamp( TS_UNIX
, $ts );
3974 $oldtz = date_default_timezone_get();
3975 date_default_timezone_set( $tz );
3976 $ts = date( 'YmdHis', $unixts );
3977 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
3979 /* Allow translation of timezones trough wiki. date() can return
3980 * whatever crap the system uses, localised or not, so we cannot
3981 * ship premade translations.
3983 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
3984 $value = wfMsgForContent( $key );
3985 if ( !wfEmptyMsg( $key, $value ) ) $tzMsg = $value;
3987 date_default_timezone_set( $oldtz );
3989 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
3991 # Variable replacement
3992 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3993 $text = $this->replaceVariables( $text );
3996 $sigText = $this->getUserSig( $user );
3997 $text = strtr( $text, array(
3999 '~~~~' => "$sigText $d",
4003 # Context links: [[|name]] and [[name (context)|]]
4005 global $wgLegalTitleChars;
4006 $tc = "[$wgLegalTitleChars]";
4007 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4009 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4010 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
4011 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4012 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4014 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4015 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4016 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4017 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4019 $t = $this->mTitle
->getText();
4021 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4022 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4023 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4024 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4026 # if there's no context, don't bother duplicating the title
4027 $text = preg_replace( $p2, '[[\\1]]', $text );
4030 # Trim trailing whitespace
4031 $text = rtrim( $text );
4037 * Fetch the user's signature text, if any, and normalize to
4038 * validated, ready-to-insert wikitext.
4039 * If you have pre-fetched the nickname or the fancySig option, you can
4040 * specify them here to save a database query.
4045 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4046 global $wgMaxSigChars;
4048 $username = $user->getName();
4050 // If not given, retrieve from the user object.
4051 if ( $nickname === false )
4052 $nickname = $user->getOption( 'nickname' );
4054 if ( is_null( $fancySig ) )
4055 $fancySig = $user->getBoolOption( 'fancysig' );
4057 $nickname = $nickname == null ?
$username : $nickname;
4059 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4060 $nickname = $username;
4061 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4062 } elseif( $fancySig !== false ) {
4063 # Sig. might contain markup; validate this
4064 if( $this->validateSig( $nickname ) !== false ) {
4065 # Validated; clean up (if needed) and return it
4066 return $this->cleanSig( $nickname, true );
4068 # Failed to validate; fall back to the default
4069 $nickname = $username;
4070 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4074 // Make sure nickname doesnt get a sig in a sig
4075 $nickname = $this->cleanSigInSig( $nickname );
4077 # If we're still here, make it a link to the user page
4078 $userText = wfEscapeWikiText( $username );
4079 $nickText = wfEscapeWikiText( $nickname );
4080 if ( $user->isAnon() ) {
4081 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4083 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4088 * Check that the user's signature contains no bad XML
4090 * @param string $text
4091 * @return mixed An expanded string, or false if invalid.
4093 function validateSig( $text ) {
4094 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4098 * Clean up signature text
4100 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4101 * 2) Substitute all transclusions
4103 * @param string $text
4104 * @param $parsing Whether we're cleaning (preferences save) or parsing
4105 * @return string Signature text
4107 function cleanSig( $text, $parsing = false ) {
4110 $this->clearState();
4111 $this->setTitle( $wgTitle );
4112 $this->mOptions
= new ParserOptions
;
4113 $this->setOutputType
= self
::OT_PREPROCESS
;
4116 # Option to disable this feature
4117 if ( !$this->mOptions
->getCleanSignatures() ) {
4121 # FIXME: regex doesn't respect extension tags or nowiki
4122 # => Move this logic to braceSubstitution()
4123 $substWord = MagicWord
::get( 'subst' );
4124 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4125 $substText = '{{' . $substWord->getSynonym( 0 );
4127 $text = preg_replace( $substRegex, $substText, $text );
4128 $text = $this->cleanSigInSig( $text );
4129 $dom = $this->preprocessToDom( $text );
4130 $frame = $this->getPreprocessor()->newFrame();
4131 $text = $frame->expand( $dom );
4134 $text = $this->mStripState
->unstripBoth( $text );
4141 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4142 * @param string $text
4143 * @return string Signature text with /~{3,5}/ removed
4145 function cleanSigInSig( $text ) {
4146 $text = preg_replace( '/~{3,5}/', '', $text );
4151 * Set up some variables which are usually set up in parse()
4152 * so that an external function can call some class members with confidence
4155 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
4156 $this->setTitle( $title );
4157 $this->mOptions
= $options;
4158 $this->setOutputType( $outputType );
4159 if ( $clearState ) {
4160 $this->clearState();
4165 * Wrapper for preprocess()
4167 * @param string $text the text to preprocess
4168 * @param ParserOptions $options options
4172 function transformMsg( $text, $options ) {
4174 static $executing = false;
4176 # Guard against infinite recursion
4182 wfProfileIn(__METHOD__
);
4183 $text = $this->preprocess( $text, $wgTitle, $options );
4186 wfProfileOut(__METHOD__
);
4191 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4192 * The callback should have the following form:
4193 * function myParserHook( $text, $params, &$parser ) { ... }
4195 * Transform and return $text. Use $parser for any required context, e.g. use
4196 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4200 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
4201 * @param mixed $callback The callback function (and object) to use for the tag
4203 * @return The old value of the mTagHooks array associated with the hook
4205 function setHook( $tag, $callback ) {
4206 $tag = strtolower( $tag );
4207 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4208 $this->mTagHooks
[$tag] = $callback;
4209 if( !in_array( $tag, $this->mStripList
) ) {
4210 $this->mStripList
[] = $tag;
4216 function setTransparentTagHook( $tag, $callback ) {
4217 $tag = strtolower( $tag );
4218 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4219 $this->mTransparentTagHooks
[$tag] = $callback;
4225 * Remove all tag hooks
4227 function clearTagHooks() {
4228 $this->mTagHooks
= array();
4229 $this->mStripList
= $this->mDefaultStripList
;
4233 * Create a function, e.g. {{sum:1|2|3}}
4234 * The callback function should have the form:
4235 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4237 * Or with SFH_OBJECT_ARGS:
4238 * function myParserFunction( $parser, $frame, $args ) { ... }
4240 * The callback may either return the text result of the function, or an array with the text
4241 * in element 0, and a number of flags in the other elements. The names of the flags are
4242 * specified in the keys. Valid flags are:
4243 * found The text returned is valid, stop processing the template. This
4245 * nowiki Wiki markup in the return value should be escaped
4246 * isHTML The returned text is HTML, armour it against wikitext transformation
4250 * @param string $id The magic word ID
4251 * @param mixed $callback The callback function (and object) to use
4252 * @param integer $flags a combination of the following flags:
4253 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4255 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4256 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4257 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4258 * the arguments, and to control the way they are expanded.
4260 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4261 * arguments, for instance:
4262 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4264 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4265 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4266 * working if/when this is changed.
4268 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4271 * Please read the documentation in includes/parser/Preprocessor.php for more information
4272 * about the methods available in PPFrame and PPNode.
4274 * @return The old callback function for this name, if any
4276 function setFunctionHook( $id, $callback, $flags = 0 ) {
4279 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4280 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4282 # Add to function cache
4283 $mw = MagicWord
::get( $id );
4285 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4287 $synonyms = $mw->getSynonyms();
4288 $sensitive = intval( $mw->isCaseSensitive() );
4290 foreach ( $synonyms as $syn ) {
4292 if ( !$sensitive ) {
4293 $syn = $wgContLang->lc( $syn );
4296 if ( !( $flags & SFH_NO_HASH
) ) {
4299 # Remove trailing colon
4300 if ( substr( $syn, -1, 1 ) === ':' ) {
4301 $syn = substr( $syn, 0, -1 );
4303 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4309 * Get all registered function hook identifiers
4313 function getFunctionHooks() {
4314 return array_keys( $this->mFunctionHooks
);
4318 * Create a tag function, e.g. <test>some stuff</test>.
4319 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4320 * Unlike parser functions, their content is not preprocessed.
4322 function setFunctionTagHook( $tag, $callback, $flags ) {
4323 $tag = strtolower( $tag );
4324 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4325 $this->mFunctionTagHooks
[$tag] : null;
4326 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4328 if( !in_array( $tag, $this->mStripList
) ) {
4329 $this->mStripList
[] = $tag;
4336 * FIXME: update documentation. makeLinkObj() is deprecated.
4337 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4338 * Placeholders created in Skin::makeLinkObj()
4339 * Returns an array of link CSS classes, indexed by PDBK.
4341 function replaceLinkHolders( &$text, $options = 0 ) {
4342 return $this->mLinkHolders
->replace( $text );
4346 * Replace <!--LINK--> link placeholders with plain text of links
4347 * (not HTML-formatted).
4348 * @param string $text
4351 function replaceLinkHoldersText( $text ) {
4352 return $this->mLinkHolders
->replaceText( $text );
4356 * Renders an image gallery from a text with one line per image.
4357 * text labels may be given by using |-style alternative text. E.g.
4358 * Image:one.jpg|The number "1"
4359 * Image:tree.jpg|A tree
4360 * given as text will return the HTML of a gallery with two images,
4361 * labeled 'The number "1"' and
4364 function renderImageGallery( $text, $params ) {
4365 $ig = new ImageGallery();
4366 $ig->setContextTitle( $this->mTitle
);
4367 $ig->setShowBytes( false );
4368 $ig->setShowFilename( false );
4369 $ig->setParser( $this );
4370 $ig->setHideBadImages();
4371 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4372 $ig->useSkin( $this->mOptions
->getSkin() );
4373 $ig->mRevisionId
= $this->mRevisionId
;
4375 if( isset( $params['showfilename'] ) ) {
4376 $ig->setShowFilename( true );
4378 $ig->setShowFilename( false );
4380 if( isset( $params['caption'] ) ) {
4381 $caption = $params['caption'];
4382 $caption = htmlspecialchars( $caption );
4383 $caption = $this->replaceInternalLinks( $caption );
4384 $ig->setCaptionHtml( $caption );
4386 if( isset( $params['perrow'] ) ) {
4387 $ig->setPerRow( $params['perrow'] );
4389 if( isset( $params['widths'] ) ) {
4390 $ig->setWidths( $params['widths'] );
4392 if( isset( $params['heights'] ) ) {
4393 $ig->setHeights( $params['heights'] );
4396 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4398 $lines = StringUtils
::explode( "\n", $text );
4399 foreach ( $lines as $line ) {
4400 # match lines like these:
4401 # Image:someimage.jpg|This is some image
4403 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4405 if ( count( $matches ) == 0 ) {
4409 if ( strpos( $matches[0], '%' ) !== false )
4410 $matches[1] = urldecode( $matches[1] );
4411 $tp = Title
::newFromText( $matches[1]/*, NS_FILE*/ );
4413 if( is_null( $nt ) ) {
4414 # Bogus title. Ignore these so we don't bomb out later.
4417 if ( isset( $matches[3] ) ) {
4418 $label = $matches[3];
4423 $html = $this->recursiveTagParse( trim( $label ) );
4425 $ig->add( $nt, $html );
4427 # Only add real images (bug #5586)
4428 if ( $nt->getNamespace() == NS_FILE
) {
4429 $this->mOutput
->addImage( $nt->getDBkey() );
4432 return $ig->toHTML();
4435 function getImageParams( $handler ) {
4437 $handlerClass = get_class( $handler );
4441 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4442 // Initialise static lists
4443 static $internalParamNames = array(
4444 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4445 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4446 'bottom', 'text-bottom' ),
4447 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4448 'upright', 'border', 'link', 'alt' ),
4450 static $internalParamMap;
4451 if ( !$internalParamMap ) {
4452 $internalParamMap = array();
4453 foreach ( $internalParamNames as $type => $names ) {
4454 foreach ( $names as $name ) {
4455 $magicName = str_replace( '-', '_', "img_$name" );
4456 $internalParamMap[$magicName] = array( $type, $name );
4461 // Add handler params
4462 $paramMap = $internalParamMap;
4464 $handlerParamMap = $handler->getParamMap();
4465 foreach ( $handlerParamMap as $magic => $paramName ) {
4466 $paramMap[$magic] = array( 'handler', $paramName );
4469 $this->mImageParams
[$handlerClass] = $paramMap;
4470 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4472 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4476 * Parse image options text and use it to make an image
4477 * @param Title $title
4478 * @param string $options
4479 * @param LinkHolderArray $holders
4481 function makeImage( $title, $options, $holders = false ) {
4482 # Check if the options text is of the form "options|alt text"
4484 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4485 # * left no resizing, just left align. label is used for alt= only
4486 # * right same, but right aligned
4487 # * none same, but not aligned
4488 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4489 # * center center the image
4490 # * frame Keep original image size, no magnify-button.
4491 # * framed Same as "frame"
4492 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4493 # * upright reduce width for upright images, rounded to full __0 px
4494 # * border draw a 1px border around the image
4495 # * alt Text for HTML alt attribute (defaults to empty)
4496 # * link Set the target of the image link. Can be external, interwiki, or local
4497 # vertical-align values (no % or length right now):
4507 $parts = StringUtils
::explode( "|", $options );
4508 $sk = $this->mOptions
->getSkin();
4510 # Give extensions a chance to select the file revision for us
4511 $skip = $time = $descQuery = false;
4512 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4515 return $sk->link( $title );
4519 $imagename = $title->getDBkey();
4520 $file = wfFindFile( $title, array( 'time' => $time ) );
4522 $handler = $file ?
$file->getHandler() : false;
4524 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4526 # Process the input parameters
4528 $params = array( 'frame' => array(), 'handler' => array(),
4529 'horizAlign' => array(), 'vertAlign' => array() );
4530 foreach( $parts as $part ) {
4531 $part = trim( $part );
4532 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4534 if( isset( $paramMap[$magicName] ) ) {
4535 list( $type, $paramName ) = $paramMap[$magicName];
4537 // Special case; width and height come in one variable together
4538 if( $type === 'handler' && $paramName === 'width' ) {
4540 # (bug 13500) In both cases (width/height and width only),
4541 # permit trailing "px" for backward compatibility.
4542 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4543 $width = intval( $m[1] );
4544 $height = intval( $m[2] );
4545 if ( $handler->validateParam( 'width', $width ) ) {
4546 $params[$type]['width'] = $width;
4549 if ( $handler->validateParam( 'height', $height ) ) {
4550 $params[$type]['height'] = $height;
4553 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4554 $width = intval( $value );
4555 if ( $handler->validateParam( 'width', $width ) ) {
4556 $params[$type]['width'] = $width;
4559 } // else no validation -- bug 13436
4561 if ( $type === 'handler' ) {
4562 # Validate handler parameter
4563 $validated = $handler->validateParam( $paramName, $value );
4565 # Validate internal parameters
4566 switch( $paramName ) {
4569 // @todo Fixme: possibly check validity here for
4570 // manualthumb? downstream behavior seems odd with
4571 // missing manual thumbs.
4573 $value = $this->stripAltText( $value, $holders );
4576 $chars = self
::EXT_LINK_URL_CLASS
;
4577 $prots = $this->mUrlProtocols
;
4578 if ( $value === '' ) {
4579 $paramName = 'no-link';
4582 } elseif ( preg_match( "/^$prots/", $value ) ) {
4583 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4584 $paramName = 'link-url';
4585 $this->mOutput
->addExternalLink( $value );
4589 $linkTitle = Title
::newFromText( $value );
4591 $paramName = 'link-title';
4592 $value = $linkTitle;
4593 $this->mOutput
->addLink( $linkTitle );
4599 // Most other things appear to be empty or numeric...
4600 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4605 $params[$type][$paramName] = $value;
4609 if ( !$validated ) {
4614 # Process alignment parameters
4615 if ( $params['horizAlign'] ) {
4616 $params['frame']['align'] = key( $params['horizAlign'] );
4618 if ( $params['vertAlign'] ) {
4619 $params['frame']['valign'] = key( $params['vertAlign'] );
4622 $params['frame']['caption'] = $caption;
4624 # Will the image be presented in a frame, with the caption below?
4625 $imageIsFramed = isset( $params['frame']['frame'] ) ||
4626 isset( $params['frame']['framed'] ) ||
4627 isset( $params['frame']['thumbnail'] ) ||
4628 isset( $params['frame']['manualthumb'] );
4630 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4631 # came to also set the caption, ordinary text after the image -- which
4632 # makes no sense, because that just repeats the text multiple times in
4633 # screen readers. It *also* came to set the title attribute.
4635 # Now that we have an alt attribute, we should not set the alt text to
4636 # equal the caption: that's worse than useless, it just repeats the
4637 # text. This is the framed/thumbnail case. If there's no caption, we
4638 # use the unnamed parameter for alt text as well, just for the time be-
4639 # ing, if the unnamed param is set and the alt param is not.
4641 # For the future, we need to figure out if we want to tweak this more,
4642 # e.g., introducing a title= parameter for the title; ignoring the un-
4643 # named parameter entirely for images without a caption; adding an ex-
4644 # plicit caption= parameter and preserving the old magic unnamed para-
4646 if ( $imageIsFramed ) { # Framed image
4647 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
4648 # No caption or alt text, add the filename as the alt text so
4649 # that screen readers at least get some description of the image
4650 $params['frame']['alt'] = $title->getText();
4652 # Do not set $params['frame']['title'] because tooltips don't make sense
4654 } else { # Inline image
4655 if ( !isset( $params['frame']['alt'] ) ) {
4656 # No alt text, use the "caption" for the alt text
4657 if ( $caption !== '') {
4658 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
4660 # No caption, fall back to using the filename for the
4662 $params['frame']['alt'] = $title->getText();
4665 # Use the "caption" for the tooltip text
4666 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4669 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4671 # Linker does the rest
4672 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4674 # Give the handler a chance to modify the parser object
4676 $handler->parserTransformHook( $this, $file );
4682 protected function stripAltText( $caption, $holders ) {
4683 # Strip bad stuff out of the title (tooltip). We can't just use
4684 # replaceLinkHoldersText() here, because if this function is called
4685 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4687 $tooltip = $holders->replaceText( $caption );
4689 $tooltip = $this->replaceLinkHoldersText( $caption );
4692 # make sure there are no placeholders in thumbnail attributes
4693 # that are later expanded to html- so expand them now and
4695 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
4696 $tooltip = Sanitizer
::stripAllTags( $tooltip );
4702 * Set a flag in the output object indicating that the content is dynamic and
4703 * shouldn't be cached.
4705 function disableCache() {
4706 wfDebug( "Parser output marked as uncacheable.\n" );
4707 $this->mOutput
->mCacheTime
= -1;
4711 * Callback from the Sanitizer for expanding items found in HTML attribute
4712 * values, so they can be safely tested and escaped.
4713 * @param string $text
4714 * @param PPFrame $frame
4718 function attributeStripCallback( &$text, $frame = false ) {
4719 $text = $this->replaceVariables( $text, $frame );
4720 $text = $this->mStripState
->unstripBoth( $text );
4729 function Title( $x = null ) { return wfSetVar( $this->mTitle
, $x ); }
4730 function Options( $x = null ) { return wfSetVar( $this->mOptions
, $x ); }
4731 function OutputType( $x = null ) { return wfSetVar( $this->mOutputType
, $x ); }
4737 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4742 * Break wikitext input into sections, and either pull or replace
4743 * some particular section's text.
4745 * External callers should use the getSection and replaceSection methods.
4747 * @param string $text Page wikitext
4748 * @param string $section A section identifier string of the form:
4749 * <flag1> - <flag2> - ... - <section number>
4751 * Currently the only recognised flag is "T", which means the target section number
4752 * was derived during a template inclusion parse, in other words this is a template
4753 * section edit link. If no flags are given, it was an ordinary section edit link.
4754 * This flag is required to avoid a section numbering mismatch when a section is
4755 * enclosed by <includeonly> (bug 6563).
4757 * The section number 0 pulls the text before the first heading; other numbers will
4758 * pull the given section along with its lower-level subsections. If the section is
4759 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4761 * @param string $mode One of "get" or "replace"
4762 * @param string $newText Replacement text for section data.
4763 * @return string for "get", the extracted section text.
4764 * for "replace", the whole page with the section replaced.
4766 private function extractSections( $text, $section, $mode, $newText='' ) {
4768 $this->clearState();
4769 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4770 $this->mOptions
= new ParserOptions
;
4771 $this->setOutputType( self
::OT_PLAIN
);
4773 $frame = $this->getPreprocessor()->newFrame();
4775 // Process section extraction flags
4777 $sectionParts = explode( '-', $section );
4778 $sectionIndex = array_pop( $sectionParts );
4779 foreach ( $sectionParts as $part ) {
4780 if ( $part === 'T' ) {
4781 $flags |
= self
::PTD_FOR_INCLUSION
;
4784 // Preprocess the text
4785 $root = $this->preprocessToDom( $text, $flags );
4787 // <h> nodes indicate section breaks
4788 // They can only occur at the top level, so we can find them by iterating the root's children
4789 $node = $root->getFirstChild();
4791 // Find the target section
4792 if ( $sectionIndex == 0 ) {
4793 // Section zero doesn't nest, level=big
4794 $targetLevel = 1000;
4797 if ( $node->getName() === 'h' ) {
4798 $bits = $node->splitHeading();
4799 if ( $bits['i'] == $sectionIndex ) {
4800 $targetLevel = $bits['level'];
4804 if ( $mode === 'replace' ) {
4805 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4807 $node = $node->getNextSibling();
4813 if ( $mode === 'get' ) {
4820 // Find the end of the section, including nested sections
4822 if ( $node->getName() === 'h' ) {
4823 $bits = $node->splitHeading();
4824 $curLevel = $bits['level'];
4825 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4829 if ( $mode === 'get' ) {
4830 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4832 $node = $node->getNextSibling();
4835 // Write out the remainder (in replace mode only)
4836 if ( $mode === 'replace' ) {
4837 // Output the replacement text
4838 // Add two newlines on -- trailing whitespace in $newText is conventionally
4839 // stripped by the editor, so we need both newlines to restore the paragraph gap
4840 // Only add trailing whitespace if there is newText
4841 if($newText != "") {
4842 $outText .= $newText . "\n\n";
4846 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4847 $node = $node->getNextSibling();
4851 if ( is_string( $outText ) ) {
4852 // Re-insert stripped tags
4853 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4860 * This function returns the text of a section, specified by a number ($section).
4861 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4862 * the first section before any such heading (section 0).
4864 * If a section contains subsections, these are also returned.
4866 * @param string $text text to look in
4867 * @param string $section section identifier
4868 * @param string $deftext default to return if section is not found
4869 * @return string text of the requested section
4871 public function getSection( $text, $section, $deftext='' ) {
4872 return $this->extractSections( $text, $section, "get", $deftext );
4875 public function replaceSection( $oldtext, $section, $text ) {
4876 return $this->extractSections( $oldtext, $section, "replace", $text );
4880 * Get the timestamp associated with the current revision, adjusted for
4881 * the default server-local timestamp
4883 function getRevisionTimestamp() {
4884 if ( is_null( $this->mRevisionTimestamp
) ) {
4885 wfProfileIn( __METHOD__
);
4887 $dbr = wfGetDB( DB_SLAVE
);
4888 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4889 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4891 // Normalize timestamp to internal MW format for timezone processing.
4892 // This has the added side-effect of replacing a null value with
4893 // the current time, which gives us more sensible behavior for
4895 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4897 // The cryptic '' timezone parameter tells to use the site-default
4898 // timezone offset instead of the user settings.
4900 // Since this value will be saved into the parser cache, served
4901 // to other users, and potentially even used inside links and such,
4902 // it needs to be consistent for all visitors.
4903 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4905 wfProfileOut( __METHOD__
);
4907 return $this->mRevisionTimestamp
;
4911 * Get the name of the user that edited the last revision
4913 function getRevisionUser() {
4914 // if this template is subst: the revision id will be blank,
4915 // so just use the current user's name
4916 if( $this->mRevisionId
) {
4917 $revision = Revision
::newFromId( $this->mRevisionId
);
4918 $revuser = $revision->getUserText();
4921 $revuser = $wgUser->getName();
4927 * Mutator for $mDefaultSort
4929 * @param $sort New value
4931 public function setDefaultSort( $sort ) {
4932 $this->mDefaultSort
= $sort;
4936 * Accessor for $mDefaultSort
4937 * Will use the title/prefixed title if none is set
4941 public function getDefaultSort() {
4942 global $wgCategoryPrefixedDefaultSortkey;
4943 if( $this->mDefaultSort
!== false ) {
4944 return $this->mDefaultSort
;
4945 } elseif ($this->mTitle
->getNamespace() == NS_CATEGORY ||
4946 !$wgCategoryPrefixedDefaultSortkey) {
4947 return $this->mTitle
->getText();
4949 return $this->mTitle
->getPrefixedText();
4954 * Accessor for $mDefaultSort
4955 * Unlike getDefaultSort(), will return false if none is set
4957 * @return string or false
4959 public function getCustomDefaultSort() {
4960 return $this->mDefaultSort
;
4964 * Try to guess the section anchor name based on a wikitext fragment
4965 * presumably extracted from a heading, for example "Header" from
4968 public function guessSectionNameFromWikiText( $text ) {
4969 # Strip out wikitext links(they break the anchor)
4970 $text = $this->stripSectionName( $text );
4971 $headline = Sanitizer
::decodeCharReferences( $text );
4973 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
4974 $headline = trim( $headline );
4975 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4976 $replacearray = array(
4981 array_keys( $replacearray ),
4982 array_values( $replacearray ),
4987 * Strips a text string of wikitext for use in a section anchor
4989 * Accepts a text string and then removes all wikitext from the
4990 * string and leaves only the resultant text (i.e. the result of
4991 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4992 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4993 * to create valid section anchors by mimicing the output of the
4994 * parser when headings are parsed.
4996 * @param $text string Text string to be stripped of wikitext
4997 * for use in a Section anchor
4998 * @return Filtered text string
5000 public function stripSectionName( $text ) {
5001 # Strip internal link markup
5002 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
5003 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
5005 # Strip external link markup (FIXME: Not Tolerant to blank link text
5006 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5007 # on how many empty links there are on the page - need to figure that out.
5008 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
5010 # Parse wikitext quotes (italics & bold)
5011 $text = $this->doQuotes($text);
5014 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5018 function srvus( $text ) {
5019 return $this->testSrvus( $text, $this->mOutputType
);
5023 * strip/replaceVariables/unstrip for preprocessor regression testing
5025 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
5026 $this->clearState();
5027 if ( ! ( $title instanceof Title
) ) {
5028 $title = Title
::newFromText( $title );
5030 $this->mTitle
= $title;
5031 $this->mOptions
= $options;
5032 $this->setOutputType( $outputType );
5033 $text = $this->replaceVariables( $text );
5034 $text = $this->mStripState
->unstripBoth( $text );
5035 $text = Sanitizer
::removeHTMLtags( $text );
5039 function testPst( $text, $title, $options ) {
5041 if ( ! ( $title instanceof Title
) ) {
5042 $title = Title
::newFromText( $title );
5044 return $this->preSaveTransform( $text, $title, $wgUser, $options );
5047 function testPreprocess( $text, $title, $options ) {
5048 if ( ! ( $title instanceof Title
) ) {
5049 $title = Title
::newFromText( $title );
5051 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5054 function markerSkipCallback( $s, $callback ) {
5057 while ( $i < strlen( $s ) ) {
5058 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5059 if ( $markerStart === false ) {
5060 $out .= call_user_func( $callback, substr( $s, $i ) );
5063 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5064 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5065 if ( $markerEnd === false ) {
5066 $out .= substr( $s, $markerStart );
5069 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5070 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5078 function serialiseHalfParsedText( $text ) {
5080 $data['text'] = $text;
5082 // First, find all strip markers, and store their
5083 // data in an array.
5084 $stripState = new StripState
;
5086 while( ( $start_pos = strpos( $text, $this->mUniqPrefix
, $pos ) ) && ( $end_pos = strpos( $text, self
::MARKER_SUFFIX
, $pos ) ) ) {
5087 $end_pos +
= strlen( self
::MARKER_SUFFIX
);
5088 $marker = substr( $text, $start_pos, $end_pos-$start_pos );
5090 if ( !empty( $this->mStripState
->general
->data
[$marker] ) ) {
5091 $replaceArray = $stripState->general
;
5092 $stripText = $this->mStripState
->general
->data
[$marker];
5093 } elseif ( !empty( $this->mStripState
->nowiki
->data
[$marker] ) ) {
5094 $replaceArray = $stripState->nowiki
;
5095 $stripText = $this->mStripState
->nowiki
->data
[$marker];
5097 throw new MWException( "Hanging strip marker: '$marker'." );
5100 $replaceArray->setPair( $marker, $stripText );
5103 $data['stripstate'] = $stripState;
5105 // Now, find all of our links, and store THEIR
5106 // data in an array! :)
5107 $links = array( 'internal' => array(), 'interwiki' => array() );
5111 while( ( $start_pos = strpos( $text, '<!--LINK ', $pos ) ) ) {
5112 list( $ns, $trail ) = explode( ':', substr( $text, $start_pos +
strlen( '<!--LINK ' ) ), 2 );
5115 if (empty( $links['internal'][$ns] )) {
5116 $links['internal'][$ns] = array();
5119 $key = trim( substr( $trail, 0, strpos( $trail, '-->' ) ) );
5120 $links['internal'][$ns][] = $this->mLinkHolders
->internals
[$ns][$key];
5121 $pos = $start_pos +
strlen( "<!--LINK $ns:$key-->" );
5127 while( ( $start_pos = strpos( $text, '<!--IWLINK ', $pos ) ) ) {
5128 $data = substr( $text, $start_pos );
5129 $key = trim( substr( $data, 0, strpos( $data, '-->' ) ) );
5130 $links['interwiki'][] = $this->mLinkHolders
->interwiki
[$key];
5131 $pos = $start_pos +
strlen( "<!--IWLINK $key-->" );
5134 $data['linkholder'] = $links;
5139 function unserialiseHalfParsedText( $data, $intPrefix = null /* Unique identifying prefix */ ) {
5141 $intPrefix = $this->getRandomString();
5143 // First, extract the strip state.
5144 $stripState = $data['stripstate'];
5145 $this->mStripState
->general
->merge( $stripState->general
);
5146 $this->mStripState
->nowiki
->merge( $stripState->nowiki
);
5148 // Now, extract the text, and renumber links
5149 $text = $data['text'];
5150 $links = $data['linkholder'];
5153 foreach( $links['internal'] as $ns => $nsLinks ) {
5154 foreach( $nsLinks as $key => $entry ) {
5155 $newKey = $intPrefix . '-' . $key;
5156 $this->mLinkHolders
->internals
[$ns][$newKey] = $entry;
5158 $text = str_replace( "<!--LINK $ns:$key-->", "<!--LINK $ns:$newKey-->", $text );
5163 foreach( $links['interwiki'] as $key => $entry ) {
5164 $newKey = "$intPrefix-$key";
5165 $this->mLinkHolders
->interwikis
[$newKey] = $entry;
5167 $text = str_replace( "<!--IWLINK $key-->", "<!--IWLINK $newKey-->", $text );
5170 // Should be good to go.
5176 * @todo document, briefly.
5180 var $general, $nowiki;
5182 function __construct() {
5183 $this->general
= new ReplacementArray
;
5184 $this->nowiki
= new ReplacementArray
;
5187 function unstripGeneral( $text ) {
5188 wfProfileIn( __METHOD__
);
5191 $text = $this->general
->replace( $text );
5192 } while ( $text !== $oldText );
5193 wfProfileOut( __METHOD__
);
5197 function unstripNoWiki( $text ) {
5198 wfProfileIn( __METHOD__
);
5201 $text = $this->nowiki
->replace( $text );
5202 } while ( $text !== $oldText );
5203 wfProfileOut( __METHOD__
);
5207 function unstripBoth( $text ) {
5208 wfProfileIn( __METHOD__
);
5211 $text = $this->general
->replace( $text );
5212 $text = $this->nowiki
->replace( $text );
5213 } while ( $text !== $oldText );
5214 wfProfileOut( __METHOD__
);
5220 * @todo document, briefly.
5223 class OnlyIncludeReplacer
{
5226 function replace( $matches ) {
5227 if ( substr( $matches[1], -1 ) === "\n" ) {
5228 $this->output
.= substr( $matches[1], 0, -1 );
5230 $this->output
.= $matches[1];