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
31 * objects: $wgLang, $wgContLang
33 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
36 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
37 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
38 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
41 * * only within ParserOptions
49 * Update this version number when the ParserOutput format
50 * changes in an incompatible way, so the parser cache
51 * can automatically discard old data.
53 const VERSION
= '1.6.4';
55 # Flags for Parser::setFunctionHook
56 # Also available as global constants from Defines.php
57 const SFH_NO_HASH
= 1;
58 const SFH_OBJECT_ARGS
= 2;
60 # Constants needed for external link processing
61 # Everything except bracket, space, or control characters
62 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F]';
63 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
64 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
66 // State constants for the definition list colon extraction
67 const COLON_STATE_TEXT
= 0;
68 const COLON_STATE_TAG
= 1;
69 const COLON_STATE_TAGSTART
= 2;
70 const COLON_STATE_CLOSETAG
= 3;
71 const COLON_STATE_TAGSLASH
= 4;
72 const COLON_STATE_COMMENT
= 5;
73 const COLON_STATE_COMMENTDASH
= 6;
74 const COLON_STATE_COMMENTDASHDASH
= 7;
76 // Flags for preprocessToDom
77 const PTD_FOR_INCLUSION
= 1;
79 // Allowed values for $this->mOutputType
80 // Parameter to startExternalParse().
83 const OT_PREPROCESS
= 3;
86 // Marker Suffix needs to be accessible staticly.
87 const MARKER_SUFFIX
= "-QINU\x7f";
93 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables,
94 $mImageParams, $mImageParamsMagicArray, $mStripList, $mMarkerIndex, $mPreprocessor,
95 $mExtLinkBracketedRegex, $mUrlProtocols, $mDefaultStripList, $mVarCache, $mConf;
98 # Cleared with clearState():
99 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
100 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
101 var $mLinkHolders, $mLinkID;
102 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
103 var $mTplExpandCache; // empty-frame expansion cache
104 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
105 var $mExpensiveFunctionCount; // number of expensive parser function calls
109 # These are variables reset at least once per parse regardless of $clearState
110 var $mOptions, // ParserOptions object
111 $mTitle, // Title context, used for self-link rendering and similar things
112 $mOutputType, // Output type, one of the OT_xxx constants
113 $ot, // Shortcut alias, see setOutputType()
114 $mRevisionId, // ID to display in {{REVISIONID}} tags
115 $mRevisionTimestamp, // The timestamp of the specified revision ID
116 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
125 function __construct( $conf = array() ) {
126 $this->mConf
= $conf;
127 $this->mTagHooks
= array();
128 $this->mTransparentTagHooks
= array();
129 $this->mFunctionHooks
= array();
130 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
131 $this->mDefaultStripList
= $this->mStripList
= array( 'nowiki', 'gallery' );
132 $this->mUrlProtocols
= wfUrlProtocols();
133 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
134 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
135 $this->mVarCache
= array();
136 if ( isset( $conf['preprocessorClass'] ) ) {
137 $this->mPreprocessorClass
= $conf['preprocessorClass'];
138 } elseif ( extension_loaded( 'domxml' ) ) {
139 // PECL extension that conflicts with the core DOM extension (bug 13770)
140 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
141 $this->mPreprocessorClass
= 'Preprocessor_Hash';
142 } elseif ( extension_loaded( 'dom' ) ) {
143 $this->mPreprocessorClass
= 'Preprocessor_DOM';
145 $this->mPreprocessorClass
= 'Preprocessor_Hash';
147 $this->mMarkerIndex
= 0;
148 $this->mFirstCall
= true;
152 * Reduce memory usage to reduce the impact of circular references
154 function __destruct() {
155 if ( isset( $this->mLinkHolders
) ) {
156 $this->mLinkHolders
->__destruct();
158 foreach ( $this as $name => $value ) {
159 unset( $this->$name );
164 * Do various kinds of initialisation on the first call of the parser
166 function firstCallInit() {
167 if ( !$this->mFirstCall
) {
170 $this->mFirstCall
= false;
172 wfProfileIn( __METHOD__
);
174 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
175 CoreParserFunctions
::register( $this );
176 $this->initialiseVariables();
178 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
179 wfProfileOut( __METHOD__
);
187 function clearState() {
188 wfProfileIn( __METHOD__
);
189 if ( $this->mFirstCall
) {
190 $this->firstCallInit();
192 $this->mOutput
= new ParserOutput
;
193 $this->mAutonumber
= 0;
194 $this->mLastSection
= '';
195 $this->mDTopen
= false;
196 $this->mIncludeCount
= array();
197 $this->mStripState
= new StripState
;
198 $this->mArgStack
= false;
199 $this->mInPre
= false;
200 $this->mLinkHolders
= new LinkHolderArray( $this );
202 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
205 * Prefix for temporary replacement strings for the multipass parser.
206 * \x07 should never appear in input as it's disallowed in XML.
207 * Using it at the front also gives us a little extra robustness
208 * since it shouldn't match when butted up against identifier-like
211 * Must not consist of all title characters, or else it will change
212 * the behaviour of <nowiki> in a link.
214 #$this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
215 # Changed to \x7f to allow XML double-parsing -- TS
216 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
219 # Clear these on every parse, bug 4549
220 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
222 $this->mShowToc
= true;
223 $this->mForceTocPosition
= false;
224 $this->mIncludeSizes
= array(
228 $this->mPPNodeCount
= 0;
229 $this->mDefaultSort
= false;
230 $this->mHeadings
= array();
231 $this->mDoubleUnderscores
= array();
232 $this->mExpensiveFunctionCount
= 0;
233 $this->mFileCache
= array();
236 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
237 $this->mPreprocessor
= null;
240 wfRunHooks( 'ParserClearState', array( &$this ) );
241 wfProfileOut( __METHOD__
);
244 function setOutputType( $ot ) {
245 $this->mOutputType
= $ot;
248 'html' => $ot == self
::OT_HTML
,
249 'wiki' => $ot == self
::OT_WIKI
,
250 'pre' => $ot == self
::OT_PREPROCESS
,
255 * Set the context title
257 function setTitle( $t ) {
258 if ( !$t ||
$t instanceof FakeTitle
) {
259 $t = Title
::newFromText( 'NO TITLE' );
261 if ( strval( $t->getFragment() ) !== '' ) {
262 # Strip the fragment to avoid various odd effects
263 $this->mTitle
= clone $t;
264 $this->mTitle
->setFragment( '' );
271 * Accessor for mUniqPrefix.
275 function uniqPrefix() {
276 if( !isset( $this->mUniqPrefix
) ) {
277 // @fixme this is probably *horribly wrong*
278 // LanguageConverter seems to want $wgParser's uniqPrefix, however
279 // if this is called for a parser cache hit, the parser may not
280 // have ever been initialized in the first place.
281 // Not really sure what the heck is supposed to be going on here.
283 //throw new MWException( "Accessing uninitialized mUniqPrefix" );
285 return $this->mUniqPrefix
;
289 * Convert wikitext to HTML
290 * Do not call this function recursively.
292 * @param $text String: text we want to parse
293 * @param $title A title object
294 * @param $options ParserOptions
295 * @param $linestart boolean
296 * @param $clearState boolean
297 * @param $revid Int: number to pass in {{REVISIONID}}
298 * @return ParserOutput a ParserOutput
300 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
302 * First pass--just handle <nowiki> sections, pass the rest off
303 * to internalParse() which does all the real work.
306 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
307 $fname = __METHOD__
.'-' . wfGetCaller();
308 wfProfileIn( __METHOD__
);
309 wfProfileIn( $fname );
315 $this->mOptions
= $options;
316 $this->setTitle( $title );
317 $oldRevisionId = $this->mRevisionId
;
318 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
319 if( $revid !== null ) {
320 $this->mRevisionId
= $revid;
321 $this->mRevisionTimestamp
= null;
323 $this->setOutputType( self
::OT_HTML
);
324 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
326 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
327 $text = $this->internalParse( $text );
328 $text = $this->mStripState
->unstripGeneral( $text );
330 # Clean up special characters, only run once, next-to-last before doBlockLevels
332 # french spaces, last one Guillemet-left
333 # only if there is something before the space
334 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
335 # french spaces, Guillemet-right
336 '/(\\302\\253) /' => '\\1 ',
337 '/ (!\s*important)/' => ' \\1', #Beware of CSS magic word !important, bug #11874.
339 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
341 $text = $this->doBlockLevels( $text, $linestart );
343 $this->replaceLinkHolders( $text );
345 # the position of the parserConvert() call should not be changed. it
346 # assumes that the links are all replaced and the only thing left
347 # is the <nowiki> mark.
348 # Side-effects: this calls $this->mOutput->setTitleText()
349 $text = $wgContLang->parserConvert( $text, $this );
351 $text = $this->mStripState
->unstripNoWiki( $text );
353 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
355 //!JF Move to its own function
357 $uniq_prefix = $this->mUniqPrefix
;
359 $elements = array_keys( $this->mTransparentTagHooks
);
360 $text = self
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
362 foreach( $matches as $marker => $data ) {
363 list( $element, $content, $params, $tag ) = $data;
364 $tagName = strtolower( $element );
365 if( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
366 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName],
367 array( $content, $params, $this ) );
371 $this->mStripState
->general
->setPair( $marker, $output );
373 $text = $this->mStripState
->unstripGeneral( $text );
375 $text = Sanitizer
::normalizeCharReferences( $text );
377 if ( ( $wgUseTidy && $this->mOptions
->mTidy
) ||
$wgAlwaysUseTidy ) {
378 $text = MWTidy
::tidy( $text );
380 # attempt to sanitize at least some nesting problems
381 # (bug #2702 and quite a few others)
383 # ''Something [http://www.cool.com cool''] -->
384 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
385 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
386 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
387 # fix up an anchor inside another anchor, only
388 # at least for a single single nested link (bug 3695)
389 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
390 '\\1\\2</a>\\3</a>\\1\\4</a>',
391 # fix div inside inline elements- doBlockLevels won't wrap a line which
392 # contains a div, so fix it up here; replace
393 # div with escaped text
394 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
395 '\\1\\3<div\\5>\\6</div>\\8\\9',
396 # remove empty italic or bold tag pairs, some
397 # introduced by rules above
398 '/<([bi])><\/\\1>/' => '',
401 $text = preg_replace(
402 array_keys( $tidyregs ),
403 array_values( $tidyregs ),
406 global $wgExpensiveParserFunctionLimit;
407 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
408 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
411 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
413 # Information on include size limits, for the benefit of users who try to skirt them
414 if ( $this->mOptions
->getEnableLimitReport() ) {
415 global $wgExpensiveParserFunctionLimit;
416 $max = $this->mOptions
->getMaxIncludeSize();
417 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
419 "NewPP limit report\n" .
420 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
421 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
422 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
424 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
425 $text .= "\n<!-- \n$limitReport-->\n";
427 $this->mOutput
->setText( $text );
428 $this->mRevisionId
= $oldRevisionId;
429 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
430 wfProfileOut( $fname );
431 wfProfileOut( __METHOD__
);
433 return $this->mOutput
;
437 * Recursive parser entry point that can be called from an extension tag
440 function recursiveTagParse( $text ) {
441 wfProfileIn( __METHOD__
);
442 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
443 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
444 $text = $this->internalParse( $text, false );
445 wfProfileOut( __METHOD__
);
450 * Expand templates and variables in the text, producing valid, static wikitext.
451 * Also removes comments.
453 function preprocess( $text, $title, $options, $revid = null ) {
454 wfProfileIn( __METHOD__
);
456 $this->setOutputType( self
::OT_PREPROCESS
);
457 $this->mOptions
= $options;
458 $this->setTitle( $title );
459 if( $revid !== null ) {
460 $this->mRevisionId
= $revid;
462 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
463 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
464 $text = $this->replaceVariables( $text );
465 $text = $this->mStripState
->unstripBoth( $text );
466 wfProfileOut( __METHOD__
);
471 * Get a random string
476 function getRandomString() {
477 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
480 function &getTitle() { return $this->mTitle
; }
481 function getOptions() { return $this->mOptions
; }
482 function getRevisionId() { return $this->mRevisionId
; }
483 function getOutput() { return $this->mOutput
; }
484 function nextLinkID() { return $this->mLinkID++
; }
486 function getFunctionLang() {
487 global $wgLang, $wgContLang;
489 $target = $this->mOptions
->getTargetLanguage();
490 if ( $target !== null ) {
493 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
498 * Get a preprocessor object
500 function getPreprocessor() {
501 if ( !isset( $this->mPreprocessor
) ) {
502 $class = $this->mPreprocessorClass
;
503 $this->mPreprocessor
= new $class( $this );
505 return $this->mPreprocessor
;
509 * Replaces all occurrences of HTML-style comments and the given tags
510 * in the text with a random marker and returns the next text. The output
511 * parameter $matches will be an associative array filled with data in
513 * 'UNIQ-xxxxx' => array(
516 * array( 'param' => 'x' ),
517 * '<element param="x">tag content</element>' ) )
519 * @param $elements list of element names. Comments are always extracted.
520 * @param $text Source text string.
521 * @param $uniq_prefix
526 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
531 $taglist = implode( '|', $elements );
532 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
534 while ( '' != $text ) {
535 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
537 if( count( $p ) < 5 ) {
540 if( count( $p ) > 5 ) {
554 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . self
::MARKER_SUFFIX
;
555 $stripped .= $marker;
557 if ( $close === '/>' ) {
558 // Empty element tag, <tag />
563 if( $element === '!--' ) {
566 $end = "/(<\\/$element\\s*>)/i";
568 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
570 if( count( $q ) < 3 ) {
571 # No end tag -- let it run out to the end of the text.
580 $matches[$marker] = array( $element,
582 Sanitizer
::decodeTagAttributes( $attributes ),
583 "<$element$attributes$close$content$tail" );
589 * Get a list of strippable XML-like elements
591 function getStripList() {
593 $elements = $this->mStripList
;
595 $elements[] = 'html';
597 if( $this->mOptions
->getUseTeX() ) {
598 $elements[] = 'math';
604 * @deprecated use replaceVariables
606 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
611 * Restores pre, math, and other extensions removed by strip()
613 * always call unstripNoWiki() after this one
615 * @deprecated use $this->mStripState->unstrip()
617 function unstrip( $text, $state ) {
618 return $state->unstripGeneral( $text );
622 * Always call this after unstrip() to preserve the order
625 * @deprecated use $this->mStripState->unstrip()
627 function unstripNoWiki( $text, $state ) {
628 return $state->unstripNoWiki( $text );
632 * @deprecated use $this->mStripState->unstripBoth()
634 function unstripForHTML( $text ) {
635 return $this->mStripState
->unstripBoth( $text );
639 * Add an item to the strip state
640 * Returns the unique tag which must be inserted into the stripped text
641 * The tag will be replaced with the original text in unstrip()
645 function insertStripItem( $text ) {
646 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
647 $this->mMarkerIndex++
;
648 $this->mStripState
->general
->setPair( $rnd, $text );
653 * Interface with html tidy
654 * @deprecated Use MWTidy::tidy()
656 public static function tidy( $text ) {
657 wfDeprecated( __METHOD__
);
658 return MWTidy
::tidy( $text );
662 * parse the wiki syntax used to render tables
666 function doTableStuff ( $text ) {
667 wfProfileIn( __METHOD__
);
669 $lines = StringUtils
::explode( "\n", $text );
671 $td_history = array (); // Is currently a td tag open?
672 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
673 $tr_history = array (); // Is currently a tr tag open?
674 $tr_attributes = array (); // history of tr attributes
675 $has_opened_tr = array(); // Did this table open a <tr> element?
676 $indent_level = 0; // indent level of the table
678 foreach ( $lines as $outLine ) {
679 $line = trim( $outLine );
681 if( $line == '' ) { // empty line, go to next line
682 $out .= $outLine."\n";
685 $first_character = $line[0];
688 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
689 // First check if we are starting a new table
690 $indent_level = strlen( $matches[1] );
692 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
693 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
695 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
696 array_push ( $td_history , false );
697 array_push ( $last_tag_history , '' );
698 array_push ( $tr_history , false );
699 array_push ( $tr_attributes , '' );
700 array_push ( $has_opened_tr , false );
701 } else if ( count ( $td_history ) == 0 ) {
702 // Don't do any of the following
703 $out .= $outLine."\n";
705 } else if ( substr ( $line , 0 , 2 ) === '|}' ) {
706 // We are ending a table
707 $line = '</table>' . substr ( $line , 2 );
708 $last_tag = array_pop ( $last_tag_history );
710 if ( !array_pop ( $has_opened_tr ) ) {
711 $line = "<tr><td></td></tr>{$line}";
714 if ( array_pop ( $tr_history ) ) {
715 $line = "</tr>{$line}";
718 if ( array_pop ( $td_history ) ) {
719 $line = "</{$last_tag}>{$line}";
721 array_pop ( $tr_attributes );
722 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
723 } else if ( substr ( $line , 0 , 2 ) === '|-' ) {
724 // Now we have a table row
725 $line = preg_replace( '#^\|-+#', '', $line );
727 // Whats after the tag is now only attributes
728 $attributes = $this->mStripState
->unstripBoth( $line );
729 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
730 array_pop ( $tr_attributes );
731 array_push ( $tr_attributes , $attributes );
734 $last_tag = array_pop ( $last_tag_history );
735 array_pop ( $has_opened_tr );
736 array_push ( $has_opened_tr , true );
738 if ( array_pop ( $tr_history ) ) {
742 if ( array_pop ( $td_history ) ) {
743 $line = "</{$last_tag}>{$line}";
747 array_push ( $tr_history , false );
748 array_push ( $td_history , false );
749 array_push ( $last_tag_history , '' );
751 else if ( $first_character === '|' ||
$first_character === '!' ||
substr ( $line , 0 , 2 ) === '|+' ) {
752 // This might be cell elements, td, th or captions
753 if ( substr ( $line , 0 , 2 ) === '|+' ) {
754 $first_character = '+';
755 $line = substr ( $line , 1 );
758 $line = substr ( $line , 1 );
760 if ( $first_character === '!' ) {
761 $line = str_replace ( '!!' , '||' , $line );
764 // Split up multiple cells on the same line.
765 // FIXME : This can result in improper nesting of tags processed
766 // by earlier parser steps, but should avoid splitting up eg
767 // attribute values containing literal "||".
768 $cells = StringUtils
::explodeMarkup( '||' , $line );
772 // Loop through each table cell
773 foreach ( $cells as $cell )
776 if ( $first_character !== '+' )
778 $tr_after = array_pop ( $tr_attributes );
779 if ( !array_pop ( $tr_history ) ) {
780 $previous = "<tr{$tr_after}>\n";
782 array_push ( $tr_history , true );
783 array_push ( $tr_attributes , '' );
784 array_pop ( $has_opened_tr );
785 array_push ( $has_opened_tr , true );
788 $last_tag = array_pop ( $last_tag_history );
790 if ( array_pop ( $td_history ) ) {
791 $previous = "</{$last_tag}>{$previous}";
794 if ( $first_character === '|' ) {
796 } else if ( $first_character === '!' ) {
798 } else if ( $first_character === '+' ) {
799 $last_tag = 'caption';
804 array_push ( $last_tag_history , $last_tag );
806 // A cell could contain both parameters and data
807 $cell_data = explode ( '|' , $cell , 2 );
809 // Bug 553: Note that a '|' inside an invalid link should not
810 // be mistaken as delimiting cell parameters
811 if ( strpos( $cell_data[0], '[[' ) !== false ) {
812 $cell = "{$previous}<{$last_tag}>{$cell}";
813 } else if ( count ( $cell_data ) == 1 )
814 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
816 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
817 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
818 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
822 array_push ( $td_history , true );
825 $out .= $outLine . "\n";
828 // Closing open td, tr && table
829 while ( count ( $td_history ) > 0 )
831 if ( array_pop ( $td_history ) ) {
834 if ( array_pop ( $tr_history ) ) {
837 if ( !array_pop ( $has_opened_tr ) ) {
838 $out .= "<tr><td></td></tr>\n" ;
841 $out .= "</table>\n";
844 // Remove trailing line-ending (b/c)
845 if ( substr( $out, -1 ) === "\n" ) {
846 $out = substr( $out, 0, -1 );
849 // special case: don't return empty table
850 if( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
854 wfProfileOut( __METHOD__
);
860 * Helper function for parse() that transforms wiki markup into
861 * HTML. Only called for $mOutputType == self::OT_HTML.
865 function internalParse( $text, $isMain = true ) {
866 wfProfileIn( __METHOD__
);
870 # Hook to suspend the parser in this state
871 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
872 wfProfileOut( __METHOD__
);
876 $text = $this->replaceVariables( $text );
877 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
878 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
880 // Tables need to come after variable replacement for things to work
881 // properly; putting them before other transformations should keep
882 // exciting things like link expansions from showing up in surprising
884 $text = $this->doTableStuff( $text );
886 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
888 $text = $this->doDoubleUnderscore( $text );
889 $text = $this->doHeadings( $text );
890 if( $this->mOptions
->getUseDynamicDates() ) {
891 $df = DateFormatter
::getInstance();
892 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
894 $text = $this->doAllQuotes( $text );
895 $text = $this->replaceInternalLinks( $text );
896 $text = $this->replaceExternalLinks( $text );
898 # replaceInternalLinks may sometimes leave behind
899 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
900 $text = str_replace($this->mUniqPrefix
.'NOPARSE', '', $text);
902 $text = $this->doMagicLinks( $text );
903 $text = $this->formatHeadings( $text, $origText, $isMain );
905 wfProfileOut( __METHOD__
);
910 * Replace special strings like "ISBN xxx" and "RFC xxx" with
911 * magic external links.
916 function doMagicLinks( $text ) {
917 wfProfileIn( __METHOD__
);
918 $prots = $this->mUrlProtocols
;
919 $urlChar = self
::EXT_LINK_URL_CLASS
;
920 $text = preg_replace_callback(
922 (<a.*?</a>) | # m[1]: Skip link text
923 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
924 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
925 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
926 ISBN\s+(\b # m[5]: ISBN, capture number
927 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
928 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
929 [0-9Xx] # check digit
931 )!x', array( &$this, 'magicLinkCallback' ), $text );
932 wfProfileOut( __METHOD__
);
936 function magicLinkCallback( $m ) {
937 if ( isset( $m[1] ) && $m[1] !== '' ) {
940 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
943 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
945 return $this->makeFreeExternalLink( $m[0] );
946 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
948 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
952 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
954 $urlmsg = 'pubmedurl';
957 throw new MWException( __METHOD__
.': unrecognised match type "' .
958 substr($m[0], 0, 20 ) . '"' );
960 $url = wfMsg( $urlmsg, $id);
961 $sk = $this->mOptions
->getSkin();
962 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
963 return "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
964 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
967 $num = strtr( $isbn, array(
972 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
974 $titleObj->escapeLocalUrl() .
975 "\" class=\"internal\">ISBN $isbn</a>";
982 * Make a free external link, given a user-supplied URL
986 function makeFreeExternalLink( $url ) {
988 wfProfileIn( __METHOD__
);
990 $sk = $this->mOptions
->getSkin();
993 # The characters '<' and '>' (which were escaped by
994 # removeHTMLtags()) should not be included in
995 # URLs, per RFC 2396.
997 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
998 $trail = substr($url, $m2[0][1]) . $trail;
999 $url = substr($url, 0, $m2[0][1]);
1002 # Move trailing punctuation to $trail
1004 # If there is no left bracket, then consider right brackets fair game too
1005 if ( strpos( $url, '(' ) === false ) {
1009 $numSepChars = strspn( strrev( $url ), $sep );
1010 if ( $numSepChars ) {
1011 $trail = substr( $url, -$numSepChars ) . $trail;
1012 $url = substr( $url, 0, -$numSepChars );
1015 $url = Sanitizer
::cleanUrl( $url );
1017 # Is this an external image?
1018 $text = $this->maybeMakeExternalImage( $url );
1019 if ( $text === false ) {
1020 # Not an image, make a link
1021 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1022 $this->getExternalLinkAttribs( $url ) );
1023 # Register it in the output object...
1024 # Replace unnecessary URL escape codes with their equivalent characters
1025 $pasteurized = self
::replaceUnusualEscapes( $url );
1026 $this->mOutput
->addExternalLink( $pasteurized );
1028 wfProfileOut( __METHOD__
);
1029 return $text . $trail;
1034 * Parse headers and return html
1038 function doHeadings( $text ) {
1039 wfProfileIn( __METHOD__
);
1040 for ( $i = 6; $i >= 1; --$i ) {
1041 $h = str_repeat( '=', $i );
1042 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1043 "<h$i>\\1</h$i>", $text );
1045 wfProfileOut( __METHOD__
);
1050 * Replace single quotes with HTML markup
1052 * @return string the altered text
1054 function doAllQuotes( $text ) {
1055 wfProfileIn( __METHOD__
);
1057 $lines = StringUtils
::explode( "\n", $text );
1058 foreach ( $lines as $line ) {
1059 $outtext .= $this->doQuotes( $line ) . "\n";
1061 $outtext = substr($outtext, 0,-1);
1062 wfProfileOut( __METHOD__
);
1067 * Helper function for doAllQuotes()
1069 public function doQuotes( $text ) {
1070 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1071 if ( count( $arr ) == 1 )
1075 # First, do some preliminary work. This may shift some apostrophes from
1076 # being mark-up to being text. It also counts the number of occurrences
1077 # of bold and italics mark-ups.
1081 foreach ( $arr as $r )
1083 if ( ( $i %
2 ) == 1 )
1085 # If there are ever four apostrophes, assume the first is supposed to
1086 # be text, and the remaining three constitute mark-up for bold text.
1087 if ( strlen( $arr[$i] ) == 4 )
1092 # If there are more than 5 apostrophes in a row, assume they're all
1093 # text except for the last 5.
1094 else if ( strlen( $arr[$i] ) > 5 )
1096 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1099 # Count the number of occurrences of bold and italics mark-ups.
1100 # We are not counting sequences of five apostrophes.
1101 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1102 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1103 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1108 # If there is an odd number of both bold and italics, it is likely
1109 # that one of the bold ones was meant to be an apostrophe followed
1110 # by italics. Which one we cannot know for certain, but it is more
1111 # likely to be one that has a single-letter word before it.
1112 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1115 $firstsingleletterword = -1;
1116 $firstmultiletterword = -1;
1118 foreach ( $arr as $r )
1120 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1122 $x1 = substr ($arr[$i-1], -1);
1123 $x2 = substr ($arr[$i-1], -2, 1);
1125 if ($firstspace == -1) $firstspace = $i;
1126 } else if ($x2 === ' ') {
1127 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1129 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1135 # If there is a single-letter word, use it!
1136 if ($firstsingleletterword > -1)
1138 $arr [ $firstsingleletterword ] = "''";
1139 $arr [ $firstsingleletterword-1 ] .= "'";
1141 # If not, but there's a multi-letter word, use that one.
1142 else if ($firstmultiletterword > -1)
1144 $arr [ $firstmultiletterword ] = "''";
1145 $arr [ $firstmultiletterword-1 ] .= "'";
1147 # ... otherwise use the first one that has neither.
1148 # (notice that it is possible for all three to be -1 if, for example,
1149 # there is only one pentuple-apostrophe in the line)
1150 else if ($firstspace > -1)
1152 $arr [ $firstspace ] = "''";
1153 $arr [ $firstspace-1 ] .= "'";
1157 # Now let's actually convert our apostrophic mush to HTML!
1162 foreach ($arr as $r)
1166 if ($state === 'both')
1173 if (strlen ($r) == 2)
1176 { $output .= '</i>'; $state = ''; }
1177 else if ($state === 'bi')
1178 { $output .= '</i>'; $state = 'b'; }
1179 else if ($state === 'ib')
1180 { $output .= '</b></i><b>'; $state = 'b'; }
1181 else if ($state === 'both')
1182 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1183 else # $state can be 'b' or ''
1184 { $output .= '<i>'; $state .= 'i'; }
1186 else if (strlen ($r) == 3)
1189 { $output .= '</b>'; $state = ''; }
1190 else if ($state === 'bi')
1191 { $output .= '</i></b><i>'; $state = 'i'; }
1192 else if ($state === 'ib')
1193 { $output .= '</b>'; $state = 'i'; }
1194 else if ($state === 'both')
1195 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1196 else # $state can be 'i' or ''
1197 { $output .= '<b>'; $state .= 'b'; }
1199 else if (strlen ($r) == 5)
1202 { $output .= '</b><i>'; $state = 'i'; }
1203 else if ($state === 'i')
1204 { $output .= '</i><b>'; $state = 'b'; }
1205 else if ($state === 'bi')
1206 { $output .= '</i></b>'; $state = ''; }
1207 else if ($state === 'ib')
1208 { $output .= '</b></i>'; $state = ''; }
1209 else if ($state === 'both')
1210 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1211 else # ($state == '')
1212 { $buffer = ''; $state = 'both'; }
1217 # Now close all remaining tags. Notice that the order is important.
1218 if ($state === 'b' ||
$state === 'ib')
1220 if ($state === 'i' ||
$state === 'bi' ||
$state === 'ib')
1222 if ($state === 'bi')
1224 # There might be lonely ''''', so make sure we have a buffer
1225 if ($state === 'both' && $buffer)
1226 $output .= '<b><i>'.$buffer.'</i></b>';
1232 * Replace external links (REL)
1234 * Note: this is all very hackish and the order of execution matters a lot.
1235 * Make sure to run maintenance/parserTests.php if you change this code.
1239 function replaceExternalLinks( $text ) {
1241 wfProfileIn( __METHOD__
);
1243 $sk = $this->mOptions
->getSkin();
1245 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1246 $s = array_shift( $bits );
1249 while ( $i<count( $bits ) ) {
1251 $protocol = $bits[$i++
];
1252 $text = $bits[$i++
];
1253 $trail = $bits[$i++
];
1255 # The characters '<' and '>' (which were escaped by
1256 # removeHTMLtags()) should not be included in
1257 # URLs, per RFC 2396.
1259 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1260 $text = substr($url, $m2[0][1]) . ' ' . $text;
1261 $url = substr($url, 0, $m2[0][1]);
1264 # If the link text is an image URL, replace it with an <img> tag
1265 # This happened by accident in the original parser, but some people used it extensively
1266 $img = $this->maybeMakeExternalImage( $text );
1267 if ( $img !== false ) {
1273 # Set linktype for CSS - if URL==text, link is essentially free
1274 $linktype = ($text === $url) ?
'free' : 'text';
1276 # No link text, e.g. [http://domain.tld/some.link]
1277 if ( $text == '' ) {
1278 # Autonumber if allowed. See bug #5918
1279 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1280 $langObj = $this->getFunctionLang();
1281 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1282 $linktype = 'autonumber';
1284 # Otherwise just use the URL
1285 $text = htmlspecialchars( $url );
1289 # Have link text, e.g. [http://domain.tld/some.link text]s
1291 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1294 $text = $wgContLang->markNoConversion($text);
1296 $url = Sanitizer
::cleanUrl( $url );
1298 # Use the encoded URL
1299 # This means that users can paste URLs directly into the text
1300 # Funny characters like ö aren't valid in URLs anyway
1301 # This was changed in August 2004
1302 $s .= $sk->makeExternalLink( $url, $text, false, $linktype,
1303 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1305 # Register link in the output object.
1306 # Replace unnecessary URL escape codes with the referenced character
1307 # This prevents spammers from hiding links from the filters
1308 $pasteurized = self
::replaceUnusualEscapes( $url );
1309 $this->mOutput
->addExternalLink( $pasteurized );
1312 wfProfileOut( __METHOD__
);
1317 * Get an associative array of additional HTML attributes appropriate for a
1318 * particular external link. This currently may include rel => nofollow
1319 * (depending on configuration, namespace, and the URL's domain) and/or a
1320 * target attribute (depending on configuration).
1322 * @param string $url Optional URL, to extract the domain from for rel =>
1323 * nofollow if appropriate
1324 * @return array Associative array of HTML attributes
1326 function getExternalLinkAttribs( $url = false ) {
1328 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1329 $ns = $this->mTitle
->getNamespace();
1330 if( $wgNoFollowLinks && !in_array($ns, $wgNoFollowNsExceptions) ) {
1331 $attribs['rel'] = 'nofollow';
1333 global $wgNoFollowDomainExceptions;
1334 if ( $wgNoFollowDomainExceptions ) {
1335 $bits = wfParseUrl( $url );
1336 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1337 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1338 if( substr( $bits['host'], -strlen( $domain ) )
1340 unset( $attribs['rel'] );
1347 if ( $this->mOptions
->getExternalLinkTarget() ) {
1348 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1355 * Replace unusual URL escape codes with their equivalent characters
1359 * @todo This can merge genuinely required bits in the path or query string,
1360 * breaking legit URLs. A proper fix would treat the various parts of
1361 * the URL differently; as a workaround, just use the output for
1362 * statistical records, not for actual linking/output.
1364 static function replaceUnusualEscapes( $url ) {
1365 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1366 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1370 * Callback function used in replaceUnusualEscapes().
1371 * Replaces unusual URL escape codes with their equivalent character
1375 private static function replaceUnusualEscapesCallback( $matches ) {
1376 $char = urldecode( $matches[0] );
1377 $ord = ord( $char );
1378 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1379 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1380 // No, shouldn't be escaped
1383 // Yes, leave it escaped
1389 * make an image if it's allowed, either through the global
1390 * option, through the exception, or through the on-wiki whitelist
1393 function maybeMakeExternalImage( $url ) {
1394 $sk = $this->mOptions
->getSkin();
1395 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1396 $imagesexception = !empty($imagesfrom);
1398 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1399 if( $imagesexception && is_array( $imagesfrom ) ) {
1400 $imagematch = false;
1401 foreach( $imagesfrom as $match ) {
1402 if( strpos( $url, $match ) === 0 ) {
1407 } elseif( $imagesexception ) {
1408 $imagematch = (strpos( $url, $imagesfrom ) === 0);
1410 $imagematch = false;
1412 if ( $this->mOptions
->getAllowExternalImages()
1413 ||
( $imagesexception && $imagematch ) ) {
1414 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1416 $text = $sk->makeExternalImage( $url );
1419 if( !$text && $this->mOptions
->getEnableImageWhitelist()
1420 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1421 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1422 foreach( $whitelist as $entry ) {
1423 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1424 if( strpos( $entry, '#' ) === 0 ||
$entry === '' )
1426 if( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1427 # Image matches a whitelist entry
1428 $text = $sk->makeExternalImage( $url );
1437 * Process [[ ]] wikilinks
1438 * @return processed text
1442 function replaceInternalLinks( $s ) {
1443 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1448 * Process [[ ]] wikilinks (RIL)
1449 * @return LinkHolderArray
1453 function replaceInternalLinks2( &$s ) {
1456 wfProfileIn( __METHOD__
);
1458 wfProfileIn( __METHOD__
.'-setup' );
1459 static $tc = FALSE, $e1, $e1_img;
1460 # the % is needed to support urlencoded titles as well
1462 $tc = Title
::legalChars() . '#%';
1463 # Match a link having the form [[namespace:link|alternate]]trail
1464 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1465 # Match cases where there is no "]]", which might still be images
1466 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1469 $sk = $this->mOptions
->getSkin();
1470 $holders = new LinkHolderArray( $this );
1472 #split the entire text string on occurences of [[
1473 $a = StringUtils
::explode( '[[', ' ' . $s );
1474 #get the first element (all text up to first [[), and remove the space we added
1477 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1478 $s = substr( $s, 1 );
1480 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1482 if ( $useLinkPrefixExtension ) {
1483 # Match the end of a line for a word that's not followed by whitespace,
1484 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1485 $e2 = wfMsgForContent( 'linkprefix' );
1488 if( is_null( $this->mTitle
) ) {
1489 wfProfileOut( __METHOD__
.'-setup' );
1490 wfProfileOut( __METHOD__
);
1491 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1493 $nottalk = !$this->mTitle
->isTalkPage();
1495 if ( $useLinkPrefixExtension ) {
1497 if ( preg_match( $e2, $s, $m ) ) {
1498 $first_prefix = $m[2];
1500 $first_prefix = false;
1506 if($wgContLang->hasVariants()) {
1507 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1509 $selflink = array($this->mTitle
->getPrefixedText());
1511 $useSubpages = $this->areSubpagesAllowed();
1512 wfProfileOut( __METHOD__
.'-setup' );
1514 # Loop for each link
1515 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1516 # Check for excessive memory usage
1517 if ( $holders->isBig() ) {
1519 # Do the existence check, replace the link holders and clear the array
1520 $holders->replace( $s );
1524 if ( $useLinkPrefixExtension ) {
1525 wfProfileIn( __METHOD__
.'-prefixhandling' );
1526 if ( preg_match( $e2, $s, $m ) ) {
1534 $prefix = $first_prefix;
1535 $first_prefix = false;
1537 wfProfileOut( __METHOD__
.'-prefixhandling' );
1540 $might_be_img = false;
1542 wfProfileIn( __METHOD__
."-e1" );
1543 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1545 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1546 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1547 # the real problem is with the $e1 regex
1550 # Still some problems for cases where the ] is meant to be outside punctuation,
1551 # and no image is in sight. See bug 2095.
1554 substr( $m[3], 0, 1 ) === ']' &&
1555 strpos($text, '[') !== false
1558 $text .= ']'; # so that replaceExternalLinks($text) works later
1559 $m[3] = substr( $m[3], 1 );
1561 # fix up urlencoded title texts
1562 if( strpos( $m[1], '%' ) !== false ) {
1563 # Should anchors '#' also be rejected?
1564 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1567 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1568 $might_be_img = true;
1570 if ( strpos( $m[1], '%' ) !== false ) {
1571 $m[1] = urldecode($m[1]);
1574 } else { # Invalid form; output directly
1575 $s .= $prefix . '[[' . $line ;
1576 wfProfileOut( __METHOD__
."-e1" );
1579 wfProfileOut( __METHOD__
."-e1" );
1580 wfProfileIn( __METHOD__
."-misc" );
1582 # Don't allow internal links to pages containing
1583 # PROTO: where PROTO is a valid URL protocol; these
1584 # should be external links.
1585 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1586 $s .= $prefix . '[[' . $line ;
1587 wfProfileOut( __METHOD__
."-misc" );
1591 # Make subpage if necessary
1592 if( $useSubpages ) {
1593 $link = $this->maybeDoSubpageLink( $m[1], $text );
1598 $noforce = (substr($m[1], 0, 1) !== ':');
1600 # Strip off leading ':'
1601 $link = substr($link, 1);
1604 wfProfileOut( __METHOD__
."-misc" );
1605 wfProfileIn( __METHOD__
."-title" );
1606 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1607 if( $nt === NULL ) {
1608 $s .= $prefix . '[[' . $line;
1609 wfProfileOut( __METHOD__
."-title" );
1613 $ns = $nt->getNamespace();
1614 $iw = $nt->getInterWiki();
1615 wfProfileOut( __METHOD__
."-title" );
1617 if ($might_be_img) { # if this is actually an invalid link
1618 wfProfileIn( __METHOD__
."-might_be_img" );
1619 if ($ns == NS_FILE
&& $noforce) { #but might be an image
1622 #look at the next 'line' to see if we can close it there
1624 $next_line = $a->current();
1625 if ( $next_line === false ||
$next_line === null ) {
1628 $m = explode( ']]', $next_line, 3 );
1629 if ( count( $m ) == 3 ) {
1630 # the first ]] closes the inner link, the second the image
1632 $text .= "[[{$m[0]}]]{$m[1]}";
1635 } elseif ( count( $m ) == 2 ) {
1636 #if there's exactly one ]] that's fine, we'll keep looking
1637 $text .= "[[{$m[0]}]]{$m[1]}";
1639 #if $next_line is invalid too, we need look no further
1640 $text .= '[[' . $next_line;
1645 # we couldn't find the end of this imageLink, so output it raw
1646 #but don't ignore what might be perfectly normal links in the text we've examined
1647 $holders->merge( $this->replaceInternalLinks2( $text ) );
1648 $s .= "{$prefix}[[$link|$text";
1649 # note: no $trail, because without an end, there *is* no trail
1650 wfProfileOut( __METHOD__
."-might_be_img" );
1653 } else { #it's not an image, so output it raw
1654 $s .= "{$prefix}[[$link|$text";
1655 # note: no $trail, because without an end, there *is* no trail
1656 wfProfileOut( __METHOD__
."-might_be_img" );
1659 wfProfileOut( __METHOD__
."-might_be_img" );
1662 $wasblank = ( '' == $text );
1663 if( $wasblank ) $text = $link;
1665 # Link not escaped by : , create the various objects
1669 wfProfileIn( __METHOD__
."-interwiki" );
1670 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1671 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1672 $s = rtrim($s . $prefix);
1673 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1674 wfProfileOut( __METHOD__
."-interwiki" );
1677 wfProfileOut( __METHOD__
."-interwiki" );
1679 if ( $ns == NS_FILE
) {
1680 wfProfileIn( __METHOD__
."-image" );
1681 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1682 # recursively parse links inside the image caption
1683 # actually, this will parse them in any other parameters, too,
1684 # but it might be hard to fix that, and it doesn't matter ATM
1685 $text = $this->replaceExternalLinks($text);
1686 $holders->merge( $this->replaceInternalLinks2( $text ) );
1688 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1689 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1691 $this->mOutput
->addImage( $nt->getDBkey() );
1692 wfProfileOut( __METHOD__
."-image" );
1697 if ( $ns == NS_CATEGORY
) {
1698 wfProfileIn( __METHOD__
."-category" );
1699 $s = rtrim($s . "\n"); # bug 87
1702 $sortkey = $this->getDefaultSort();
1706 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1707 $sortkey = str_replace( "\n", '', $sortkey );
1708 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1709 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1712 * Strip the whitespace Category links produce, see bug 87
1713 * @todo We might want to use trim($tmp, "\n") here.
1715 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1717 wfProfileOut( __METHOD__
."-category" );
1722 # Self-link checking
1723 if( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1724 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1725 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1730 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1731 # FIXME: Should do batch file existence checks, see comment below
1732 if( $ns == NS_MEDIA
) {
1733 wfProfileIn( __METHOD__
."-media" );
1734 # Give extensions a chance to select the file revision for us
1735 $skip = $time = false;
1736 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1738 $link = $sk->link( $nt );
1740 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1742 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1743 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1744 $this->mOutput
->addImage( $nt->getDBkey() );
1745 wfProfileOut( __METHOD__
."-media" );
1749 wfProfileIn( __METHOD__
."-always_known" );
1750 # Some titles, such as valid special pages or files in foreign repos, should
1751 # be shown as bluelinks even though they're not included in the page table
1753 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1754 # batch file existence checks for NS_FILE and NS_MEDIA
1755 if( $iw == '' && $nt->isAlwaysKnown() ) {
1756 $this->mOutput
->addLink( $nt );
1757 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1759 # Links will be added to the output link list after checking
1760 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1762 wfProfileOut( __METHOD__
."-always_known" );
1764 wfProfileOut( __METHOD__
);
1769 * Make a link placeholder. The text returned can be later resolved to a real link with
1770 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1771 * parsing of interwiki links, and secondly to allow all existence checks and
1772 * article length checks (for stub links) to be bundled into a single query.
1776 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1777 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1781 * Render a forced-blue link inline; protect against double expansion of
1782 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1783 * Since this little disaster has to split off the trail text to avoid
1784 * breaking URLs in the following text without breaking trails on the
1785 * wiki links, it's been made into a horrible function.
1788 * @param string $text
1789 * @param string $query
1790 * @param string $trail
1791 * @param string $prefix
1792 * @return string HTML-wikitext mix oh yuck
1794 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1795 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1796 $sk = $this->mOptions
->getSkin();
1797 // FIXME: use link() instead of deprecated makeKnownLinkObj()
1798 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1799 return $this->armorLinks( $link ) . $trail;
1803 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1804 * going to go through further parsing steps before inline URL expansion.
1806 * Not needed quite as much as it used to be since free links are a bit
1807 * more sensible these days. But bracketed links are still an issue.
1809 * @param string more-or-less HTML
1810 * @return string less-or-more HTML with NOPARSE bits
1812 function armorLinks( $text ) {
1813 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1814 "{$this->mUniqPrefix}NOPARSE$1", $text );
1818 * Return true if subpage links should be expanded on this page.
1821 function areSubpagesAllowed() {
1822 # Some namespaces don't allow subpages
1823 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
1827 * Handle link to subpage if necessary
1828 * @param string $target the source of the link
1829 * @param string &$text the link text, modified as necessary
1830 * @return string the full name of the link
1833 function maybeDoSubpageLink($target, &$text) {
1836 # :Foobar -- override special treatment of prefix (images, language links)
1837 # /Foobar -- convert to CurrentPage/Foobar
1838 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1839 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1840 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1842 wfProfileIn( __METHOD__
);
1843 $ret = $target; # default return value is no change
1845 # Some namespaces don't allow subpages,
1846 # so only perform processing if subpages are allowed
1847 if( $this->areSubpagesAllowed() ) {
1848 $hash = strpos( $target, '#' );
1849 if( $hash !== false ) {
1850 $suffix = substr( $target, $hash );
1851 $target = substr( $target, 0, $hash );
1856 $target = trim( $target );
1857 # Look at the first character
1858 if( $target != '' && $target{0} === '/' ) {
1859 # / at end means we don't want the slash to be shown
1861 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1862 if( $trailingSlashes ) {
1863 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1865 $noslash = substr( $target, 1 );
1868 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash) . $suffix;
1869 if( '' === $text ) {
1870 $text = $target . $suffix;
1871 } # this might be changed for ugliness reasons
1873 # check for .. subpage backlinks
1875 $nodotdot = $target;
1876 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1878 $nodotdot = substr( $nodotdot, 3 );
1880 if($dotdotcount > 0) {
1881 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1882 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1883 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1884 # / at the end means don't show full path
1885 if( substr( $nodotdot, -1, 1 ) === '/' ) {
1886 $nodotdot = substr( $nodotdot, 0, -1 );
1887 if( '' === $text ) {
1888 $text = $nodotdot . $suffix;
1891 $nodotdot = trim( $nodotdot );
1892 if( $nodotdot != '' ) {
1893 $ret .= '/' . $nodotdot;
1901 wfProfileOut( __METHOD__
);
1906 * Used by doBlockLevels()
1909 /* private */ function closeParagraph() {
1911 if ( '' != $this->mLastSection
) {
1912 $result = '</' . $this->mLastSection
. ">\n";
1914 $this->mInPre
= false;
1915 $this->mLastSection
= '';
1918 # getCommon() returns the length of the longest common substring
1919 # of both arguments, starting at the beginning of both.
1921 /* private */ function getCommon( $st1, $st2 ) {
1922 $fl = strlen( $st1 );
1923 $shorter = strlen( $st2 );
1924 if ( $fl < $shorter ) { $shorter = $fl; }
1926 for ( $i = 0; $i < $shorter; ++
$i ) {
1927 if ( $st1{$i} != $st2{$i} ) { break; }
1931 # These next three functions open, continue, and close the list
1932 # element appropriate to the prefix character passed into them.
1934 /* private */ function openList( $char ) {
1935 $result = $this->closeParagraph();
1937 if ( '*' === $char ) { $result .= '<ul><li>'; }
1938 elseif ( '#' === $char ) { $result .= '<ol><li>'; }
1939 elseif ( ':' === $char ) { $result .= '<dl><dd>'; }
1940 elseif ( ';' === $char ) {
1941 $result .= '<dl><dt>';
1942 $this->mDTopen
= true;
1944 else { $result = '<!-- ERR 1 -->'; }
1949 /* private */ function nextItem( $char ) {
1950 if ( '*' === $char ||
'#' === $char ) { return '</li><li>'; }
1951 elseif ( ':' === $char ||
';' === $char ) {
1953 if ( $this->mDTopen
) { $close = '</dt>'; }
1954 if ( ';' === $char ) {
1955 $this->mDTopen
= true;
1956 return $close . '<dt>';
1958 $this->mDTopen
= false;
1959 return $close . '<dd>';
1962 return '<!-- ERR 2 -->';
1965 /* private */ function closeList( $char ) {
1966 if ( '*' === $char ) { $text = '</li></ul>'; }
1967 elseif ( '#' === $char ) { $text = '</li></ol>'; }
1968 elseif ( ':' === $char ) {
1969 if ( $this->mDTopen
) {
1970 $this->mDTopen
= false;
1971 $text = '</dt></dl>';
1973 $text = '</dd></dl>';
1976 else { return '<!-- ERR 3 -->'; }
1982 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
1984 * @param $linestart bool whether or not this is at the start of a line.
1986 * @return string the lists rendered as HTML
1988 function doBlockLevels( $text, $linestart ) {
1989 wfProfileIn( __METHOD__
);
1991 # Parsing through the text line by line. The main thing
1992 # happening here is handling of block-level elements p, pre,
1993 # and making lists from lines starting with * # : etc.
1995 $textLines = StringUtils
::explode( "\n", $text );
1997 $lastPrefix = $output = '';
1998 $this->mDTopen
= $inBlockElem = false;
2000 $paragraphStack = false;
2002 foreach ( $textLines as $oLine ) {
2004 if ( !$linestart ) {
2014 $lastPrefixLength = strlen( $lastPrefix );
2015 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2016 $preOpenMatch = preg_match('/<pre/i', $oLine );
2017 // If not in a <pre> element, scan for and figure out what prefixes are there.
2018 if ( !$this->mInPre
) {
2019 # Multiple prefixes may abut each other for nested lists.
2020 $prefixLength = strspn( $oLine, '*#:;' );
2021 $prefix = substr( $oLine, 0, $prefixLength );
2024 // ; and : are both from definition-lists, so they're equivalent
2025 // for the purposes of determining whether or not we need to open/close
2027 $prefix2 = str_replace( ';', ':', $prefix );
2028 $t = substr( $oLine, $prefixLength );
2029 $this->mInPre
= (bool)$preOpenMatch;
2031 # Don't interpret any other prefixes in preformatted text
2033 $prefix = $prefix2 = '';
2038 if( $prefixLength && $lastPrefix === $prefix2 ) {
2039 # Same as the last item, so no need to deal with nesting or opening stuff
2040 $output .= $this->nextItem( substr( $prefix, -1 ) );
2041 $paragraphStack = false;
2043 if ( substr( $prefix, -1 ) === ';') {
2044 # The one nasty exception: definition lists work like this:
2045 # ; title : definition text
2046 # So we check for : in the remainder text to split up the
2047 # title and definition, without b0rking links.
2049 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2051 $output .= $term . $this->nextItem( ':' );
2054 } elseif( $prefixLength ||
$lastPrefixLength ) {
2055 // We need to open or close prefixes, or both.
2057 # Either open or close a level...
2058 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2059 $paragraphStack = false;
2061 // Close all the prefixes which aren't shared.
2062 while( $commonPrefixLength < $lastPrefixLength ) {
2063 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2064 --$lastPrefixLength;
2067 // Continue the current prefix if appropriate.
2068 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2069 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2072 // Open prefixes where appropriate.
2073 while ( $prefixLength > $commonPrefixLength ) {
2074 $char = substr( $prefix, $commonPrefixLength, 1 );
2075 $output .= $this->openList( $char );
2077 if ( ';' === $char ) {
2078 # FIXME: This is dupe of code above
2079 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2081 $output .= $term . $this->nextItem( ':' );
2084 ++
$commonPrefixLength;
2086 $lastPrefix = $prefix2;
2089 // If we have no prefixes, go to paragraph mode.
2090 if( 0 == $prefixLength ) {
2091 wfProfileIn( __METHOD__
."-paragraph" );
2092 # No prefix (not in list)--go to paragraph mode
2093 // XXX: use a stack for nestable elements like span, table and div
2094 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2095 $closematch = preg_match(
2096 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2097 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2098 if ( $openmatch or $closematch ) {
2099 $paragraphStack = false;
2100 #Â TODO bug 5718: paragraph closed
2101 $output .= $this->closeParagraph();
2102 if ( $preOpenMatch and !$preCloseMatch ) {
2103 $this->mInPre
= true;
2105 if ( $closematch ) {
2106 $inBlockElem = false;
2108 $inBlockElem = true;
2110 } else if ( !$inBlockElem && !$this->mInPre
) {
2111 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' or trim($t) != '' ) ) {
2113 if ($this->mLastSection
!== 'pre') {
2114 $paragraphStack = false;
2115 $output .= $this->closeParagraph().'<pre>';
2116 $this->mLastSection
= 'pre';
2118 $t = substr( $t, 1 );
2121 if ( '' == trim($t) ) {
2122 if ( $paragraphStack ) {
2123 $output .= $paragraphStack.'<br />';
2124 $paragraphStack = false;
2125 $this->mLastSection
= 'p';
2127 if ($this->mLastSection
!== 'p' ) {
2128 $output .= $this->closeParagraph();
2129 $this->mLastSection
= '';
2130 $paragraphStack = '<p>';
2132 $paragraphStack = '</p><p>';
2136 if ( $paragraphStack ) {
2137 $output .= $paragraphStack;
2138 $paragraphStack = false;
2139 $this->mLastSection
= 'p';
2140 } else if ($this->mLastSection
!== 'p') {
2141 $output .= $this->closeParagraph().'<p>';
2142 $this->mLastSection
= 'p';
2147 wfProfileOut( __METHOD__
."-paragraph" );
2149 // somewhere above we forget to get out of pre block (bug 785)
2150 if($preCloseMatch && $this->mInPre
) {
2151 $this->mInPre
= false;
2153 if ($paragraphStack === false) {
2157 while ( $prefixLength ) {
2158 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2161 if ( '' != $this->mLastSection
) {
2162 $output .= '</' . $this->mLastSection
. '>';
2163 $this->mLastSection
= '';
2166 wfProfileOut( __METHOD__
);
2171 * Split up a string on ':', ignoring any occurences inside tags
2172 * to prevent illegal overlapping.
2173 * @param string $str the string to split
2174 * @param string &$before set to everything before the ':'
2175 * @param string &$after set to everything after the ':'
2176 * return string the position of the ':', or false if none found
2178 function findColonNoLinks($str, &$before, &$after) {
2179 wfProfileIn( __METHOD__
);
2181 $pos = strpos( $str, ':' );
2182 if( $pos === false ) {
2184 wfProfileOut( __METHOD__
);
2188 $lt = strpos( $str, '<' );
2189 if( $lt === false ||
$lt > $pos ) {
2190 // Easy; no tag nesting to worry about
2191 $before = substr( $str, 0, $pos );
2192 $after = substr( $str, $pos+
1 );
2193 wfProfileOut( __METHOD__
);
2197 // Ugly state machine to walk through avoiding tags.
2198 $state = self
::COLON_STATE_TEXT
;
2200 $len = strlen( $str );
2201 for( $i = 0; $i < $len; $i++
) {
2205 // (Using the number is a performance hack for common cases)
2206 case 0: // self::COLON_STATE_TEXT:
2209 // Could be either a <start> tag or an </end> tag
2210 $state = self
::COLON_STATE_TAGSTART
;
2215 $before = substr( $str, 0, $i );
2216 $after = substr( $str, $i +
1 );
2217 wfProfileOut( __METHOD__
);
2220 // Embedded in a tag; don't break it.
2223 // Skip ahead looking for something interesting
2224 $colon = strpos( $str, ':', $i );
2225 if( $colon === false ) {
2226 // Nothing else interesting
2227 wfProfileOut( __METHOD__
);
2230 $lt = strpos( $str, '<', $i );
2231 if( $stack === 0 ) {
2232 if( $lt === false ||
$colon < $lt ) {
2234 $before = substr( $str, 0, $colon );
2235 $after = substr( $str, $colon +
1 );
2236 wfProfileOut( __METHOD__
);
2240 if( $lt === false ) {
2241 // Nothing else interesting to find; abort!
2242 // We're nested, but there's no close tags left. Abort!
2245 // Skip ahead to next tag start
2247 $state = self
::COLON_STATE_TAGSTART
;
2250 case 1: // self::COLON_STATE_TAG:
2255 $state = self
::COLON_STATE_TEXT
;
2258 // Slash may be followed by >?
2259 $state = self
::COLON_STATE_TAGSLASH
;
2265 case 2: // self::COLON_STATE_TAGSTART:
2268 $state = self
::COLON_STATE_CLOSETAG
;
2271 $state = self
::COLON_STATE_COMMENT
;
2274 // Illegal early close? This shouldn't happen D:
2275 $state = self
::COLON_STATE_TEXT
;
2278 $state = self
::COLON_STATE_TAG
;
2281 case 3: // self::COLON_STATE_CLOSETAG:
2286 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2287 wfProfileOut( __METHOD__
);
2290 $state = self
::COLON_STATE_TEXT
;
2293 case self
::COLON_STATE_TAGSLASH
:
2295 // Yes, a self-closed tag <blah/>
2296 $state = self
::COLON_STATE_TEXT
;
2298 // Probably we're jumping the gun, and this is an attribute
2299 $state = self
::COLON_STATE_TAG
;
2302 case 5: // self::COLON_STATE_COMMENT:
2304 $state = self
::COLON_STATE_COMMENTDASH
;
2307 case self
::COLON_STATE_COMMENTDASH
:
2309 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2311 $state = self
::COLON_STATE_COMMENT
;
2314 case self
::COLON_STATE_COMMENTDASHDASH
:
2316 $state = self
::COLON_STATE_TEXT
;
2318 $state = self
::COLON_STATE_COMMENT
;
2322 throw new MWException( "State machine error in " . __METHOD__
);
2326 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2329 wfProfileOut( __METHOD__
);
2334 * Return value of a magic variable (like PAGENAME)
2338 function getVariableValue( $index ) {
2339 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2342 * Some of these require message or data lookups and can be
2343 * expensive to check many times.
2345 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2346 if ( isset( $this->mVarCache
[$index] ) ) {
2347 return $this->mVarCache
[$index];
2351 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2352 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2355 global $wgLocaltimezone;
2356 if ( isset( $wgLocaltimezone ) ) {
2357 $oldtz = getenv( 'TZ' );
2358 putenv( 'TZ='.$wgLocaltimezone );
2361 wfSuppressWarnings(); // E_STRICT system time bitching
2362 $localTimestamp = date( 'YmdHis', $ts );
2363 $localMonth = date( 'm', $ts );
2364 $localMonth1 = date( 'n', $ts );
2365 $localMonthName = date( 'n', $ts );
2366 $localDay = date( 'j', $ts );
2367 $localDay2 = date( 'd', $ts );
2368 $localDayOfWeek = date( 'w', $ts );
2369 $localWeek = date( 'W', $ts );
2370 $localYear = date( 'Y', $ts );
2371 $localHour = date( 'H', $ts );
2372 if ( isset( $wgLocaltimezone ) ) {
2373 putenv( 'TZ='.$oldtz );
2375 wfRestoreWarnings();
2378 case 'currentmonth':
2379 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2380 case 'currentmonth1':
2381 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2382 case 'currentmonthname':
2383 return $this->mVarCache
[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2384 case 'currentmonthnamegen':
2385 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2386 case 'currentmonthabbrev':
2387 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2389 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2391 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2393 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localMonth );
2395 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localMonth1 );
2396 case 'localmonthname':
2397 return $this->mVarCache
[$index] = $wgContLang->getMonthName( $localMonthName );
2398 case 'localmonthnamegen':
2399 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2400 case 'localmonthabbrev':
2401 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2403 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay );
2405 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay2 );
2407 return wfEscapeWikiText( $this->mTitle
->getText() );
2409 return $this->mTitle
->getPartialURL();
2410 case 'fullpagename':
2411 return wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2412 case 'fullpagenamee':
2413 return $this->mTitle
->getPrefixedURL();
2415 return wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2416 case 'subpagenamee':
2417 return $this->mTitle
->getSubpageUrlForm();
2418 case 'basepagename':
2419 return wfEscapeWikiText( $this->mTitle
->getBaseText() );
2420 case 'basepagenamee':
2421 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2422 case 'talkpagename':
2423 if( $this->mTitle
->canTalk() ) {
2424 $talkPage = $this->mTitle
->getTalkPage();
2425 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2429 case 'talkpagenamee':
2430 if( $this->mTitle
->canTalk() ) {
2431 $talkPage = $this->mTitle
->getTalkPage();
2432 return $talkPage->getPrefixedUrl();
2436 case 'subjectpagename':
2437 $subjPage = $this->mTitle
->getSubjectPage();
2438 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2439 case 'subjectpagenamee':
2440 $subjPage = $this->mTitle
->getSubjectPage();
2441 return $subjPage->getPrefixedUrl();
2443 // Let the edit saving system know we should parse the page
2444 // *after* a revision ID has been assigned.
2445 $this->mOutput
->setFlag( 'vary-revision' );
2446 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2447 return $this->mRevisionId
;
2449 // Let the edit saving system know we should parse the page
2450 // *after* a revision ID has been assigned. This is for null edits.
2451 $this->mOutput
->setFlag( 'vary-revision' );
2452 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2453 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2454 case 'revisionday2':
2455 // Let the edit saving system know we should parse the page
2456 // *after* a revision ID has been assigned. This is for null edits.
2457 $this->mOutput
->setFlag( 'vary-revision' );
2458 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2459 return substr( $this->getRevisionTimestamp(), 6, 2 );
2460 case 'revisionmonth':
2461 // Let the edit saving system know we should parse the page
2462 // *after* a revision ID has been assigned. This is for null edits.
2463 $this->mOutput
->setFlag( 'vary-revision' );
2464 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2465 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2466 case 'revisionyear':
2467 // Let the edit saving system know we should parse the page
2468 // *after* a revision ID has been assigned. This is for null edits.
2469 $this->mOutput
->setFlag( 'vary-revision' );
2470 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2471 return substr( $this->getRevisionTimestamp(), 0, 4 );
2472 case 'revisiontimestamp':
2473 // Let the edit saving system know we should parse the page
2474 // *after* a revision ID has been assigned. This is for null edits.
2475 $this->mOutput
->setFlag( 'vary-revision' );
2476 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2477 return $this->getRevisionTimestamp();
2478 case 'revisionuser':
2479 // Let the edit saving system know we should parse the page
2480 // *after* a revision ID has been assigned. This is for null edits.
2481 $this->mOutput
->setFlag( 'vary-revision' );
2482 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2483 return $this->getRevisionUser();
2485 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2487 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2489 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2491 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2492 case 'subjectspace':
2493 return $this->mTitle
->getSubjectNsText();
2494 case 'subjectspacee':
2495 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2496 case 'currentdayname':
2497 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2499 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2501 return $this->mVarCache
[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2503 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2505 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2506 // int to remove the padding
2507 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2509 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2510 case 'localdayname':
2511 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2513 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localYear, true );
2515 return $this->mVarCache
[$index] = $wgContLang->time( $localTimestamp, false, false );
2517 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localHour, true );
2519 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2520 // int to remove the padding
2521 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)$localWeek );
2523 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDayOfWeek );
2524 case 'numberofarticles':
2525 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2526 case 'numberoffiles':
2527 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::images() );
2528 case 'numberofusers':
2529 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::users() );
2530 case 'numberofactiveusers':
2531 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::activeUsers() );
2532 case 'numberofpages':
2533 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2534 case 'numberofadmins':
2535 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::numberingroup('sysop') );
2536 case 'numberofedits':
2537 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2538 case 'numberofviews':
2539 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::views() );
2540 case 'currenttimestamp':
2541 return $this->mVarCache
[$index] = wfTimestamp( TS_MW
, $ts );
2542 case 'localtimestamp':
2543 return $this->mVarCache
[$index] = $localTimestamp;
2544 case 'currentversion':
2545 return $this->mVarCache
[$index] = SpecialVersion
::getVersion();
2551 return $wgServerName;
2553 return $wgScriptPath;
2554 case 'directionmark':
2555 return $wgContLang->getDirMark();
2556 case 'contentlanguage':
2557 global $wgContLanguageCode;
2558 return $wgContLanguageCode;
2561 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret ) ) )
2569 * initialise the magic variables (like CURRENTMONTHNAME)
2573 function initialiseVariables() {
2574 wfProfileIn( __METHOD__
);
2575 $variableIDs = MagicWord
::getVariableIDs();
2577 $this->mVariables
= new MagicWordArray( $variableIDs );
2578 wfProfileOut( __METHOD__
);
2582 * Preprocess some wikitext and return the document tree.
2583 * This is the ghost of replace_variables().
2585 * @param string $text The text to parse
2586 * @param integer flags Bitwise combination of:
2587 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2588 * included. Default is to assume a direct page view.
2590 * The generated DOM tree must depend only on the input text and the flags.
2591 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2593 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2594 * change in the DOM tree for a given text, must be passed through the section identifier
2595 * in the section edit link and thus back to extractSections().
2597 * The output of this function is currently only cached in process memory, but a persistent
2598 * cache may be implemented at a later date which takes further advantage of these strict
2599 * dependency requirements.
2603 function preprocessToDom ( $text, $flags = 0 ) {
2604 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2609 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2611 public static function splitWhitespace( $s ) {
2612 $ltrimmed = ltrim( $s );
2613 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2614 $trimmed = rtrim( $ltrimmed );
2615 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2617 $w2 = substr( $ltrimmed, -$diff );
2621 return array( $w1, $trimmed, $w2 );
2625 * Replace magic variables, templates, and template arguments
2626 * with the appropriate text. Templates are substituted recursively,
2627 * taking care to avoid infinite loops.
2629 * Note that the substitution depends on value of $mOutputType:
2630 * self::OT_WIKI: only {{subst:}} templates
2631 * self::OT_PREPROCESS: templates but not extension tags
2632 * self::OT_HTML: all templates and extension tags
2634 * @param string $tex The text to transform
2635 * @param PPFrame $frame Object describing the arguments passed to the template.
2636 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2637 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2638 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2641 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2642 # Is there any text? Also, Prevent too big inclusions!
2643 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2646 wfProfileIn( __METHOD__
);
2648 if ( $frame === false ) {
2649 $frame = $this->getPreprocessor()->newFrame();
2650 } elseif ( !( $frame instanceof PPFrame
) ) {
2651 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2652 $frame = $this->getPreprocessor()->newCustomFrame($frame);
2655 $dom = $this->preprocessToDom( $text );
2656 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2657 $text = $frame->expand( $dom, $flags );
2659 wfProfileOut( __METHOD__
);
2663 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2664 static function createAssocArgs( $args ) {
2665 $assocArgs = array();
2667 foreach( $args as $arg ) {
2668 $eqpos = strpos( $arg, '=' );
2669 if ( $eqpos === false ) {
2670 $assocArgs[$index++
] = $arg;
2672 $name = trim( substr( $arg, 0, $eqpos ) );
2673 $value = trim( substr( $arg, $eqpos+
1 ) );
2674 if ( $value === false ) {
2677 if ( $name !== false ) {
2678 $assocArgs[$name] = $value;
2687 * Warn the user when a parser limitation is reached
2688 * Will warn at most once the user per limitation type
2690 * @param string $limitationType, should be one of:
2691 * 'expensive-parserfunction' (corresponding messages: 'expensive-parserfunction-warning', 'expensive-parserfunction-category')
2692 * 'post-expand-template-argument' (corresponding messages: 'post-expand-template-argument-warning', 'post-expand-template-argument-category')
2693 * 'post-expand-template-inclusion' (corresponding messages: 'post-expand-template-inclusion-warning', 'post-expand-template-inclusion-category')
2694 * @params int $current, $max When an explicit limit has been
2695 * exceeded, provide the values (optional)
2697 function limitationWarn( $limitationType, $current=null, $max=null) {
2698 $msgName = $limitationType . '-warning';
2699 //does no harm if $current and $max are present but are unnecessary for the message
2700 $warning = wfMsgExt( $msgName, array( 'parsemag', 'escape' ), $current, $max );
2701 $this->mOutput
->addWarning( $warning );
2702 $cat = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( $limitationType . '-category' ) );
2704 $this->mOutput
->addCategory( $cat->getDBkey(), $this->getDefaultSort() );
2709 * Return the text of a template, after recursively
2710 * replacing any variables or templates within the template.
2712 * @param array $piece The parts of the template
2713 * $piece['title']: the title, i.e. the part before the |
2714 * $piece['parts']: the parameter array
2715 * $piece['lineStart']: whether the brace was at the start of a line
2716 * @param PPFrame The current frame, contains template arguments
2717 * @return string the text of the template
2720 function braceSubstitution( $piece, $frame ) {
2721 global $wgContLang, $wgNonincludableNamespaces;
2722 wfProfileIn( __METHOD__
);
2723 wfProfileIn( __METHOD__
.'-setup' );
2726 $found = false; # $text has been filled
2727 $nowiki = false; # wiki markup in $text should be escaped
2728 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2729 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2730 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2731 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2733 # Title object, where $text came from
2736 # $part1 is the bit before the first |, and must contain only title characters.
2737 # Various prefixes will be stripped from it later.
2738 $titleWithSpaces = $frame->expand( $piece['title'] );
2739 $part1 = trim( $titleWithSpaces );
2742 # Original title text preserved for various purposes
2743 $originalTitle = $part1;
2745 # $args is a list of argument nodes, starting from index 0, not including $part1
2746 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2747 wfProfileOut( __METHOD__
.'-setup' );
2750 wfProfileIn( __METHOD__
.'-modifiers' );
2752 $mwSubst = MagicWord
::get( 'subst' );
2753 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2754 # One of two possibilities is true:
2755 # 1) Found SUBST but not in the PST phase
2756 # 2) Didn't find SUBST and in the PST phase
2757 # In either case, return without further processing
2758 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2765 if ( !$found && $args->getLength() == 0 ) {
2766 $id = $this->mVariables
->matchStartToEnd( $part1 );
2767 if ( $id !== false ) {
2768 $text = $this->getVariableValue( $id );
2769 if (MagicWord
::getCacheTTL($id)>-1)
2770 $this->mOutput
->mContainsOldMagic
= true;
2775 # MSG, MSGNW and RAW
2778 $mwMsgnw = MagicWord
::get( 'msgnw' );
2779 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2782 # Remove obsolete MSG:
2783 $mwMsg = MagicWord
::get( 'msg' );
2784 $mwMsg->matchStartAndRemove( $part1 );
2788 $mwRaw = MagicWord
::get( 'raw' );
2789 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2790 $forceRawInterwiki = true;
2793 wfProfileOut( __METHOD__
.'-modifiers' );
2797 wfProfileIn( __METHOD__
. '-pfunc' );
2799 $colonPos = strpos( $part1, ':' );
2800 if ( $colonPos !== false ) {
2801 # Case sensitive functions
2802 $function = substr( $part1, 0, $colonPos );
2803 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2804 $function = $this->mFunctionSynonyms
[1][$function];
2806 # Case insensitive functions
2807 $function = strtolower( $function );
2808 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2809 $function = $this->mFunctionSynonyms
[0][$function];
2815 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2816 $initialArgs = array( &$this );
2817 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2818 if ( $flags & SFH_OBJECT_ARGS
) {
2819 # Add a frame parameter, and pass the arguments as an array
2820 $allArgs = $initialArgs;
2821 $allArgs[] = $frame;
2822 for ( $i = 0; $i < $args->getLength(); $i++
) {
2823 $funcArgs[] = $args->item( $i );
2825 $allArgs[] = $funcArgs;
2827 # Convert arguments to plain text
2828 for ( $i = 0; $i < $args->getLength(); $i++
) {
2829 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2831 $allArgs = array_merge( $initialArgs, $funcArgs );
2834 # Workaround for PHP bug 35229 and similar
2835 if ( !is_callable( $callback ) ) {
2836 wfProfileOut( __METHOD__
. '-pfunc' );
2837 wfProfileOut( __METHOD__
);
2838 throw new MWException( "Tag hook for $function is not callable\n" );
2840 $result = call_user_func_array( $callback, $allArgs );
2843 $preprocessFlags = 0;
2845 if ( is_array( $result ) ) {
2846 if ( isset( $result[0] ) ) {
2848 unset( $result[0] );
2851 // Extract flags into the local scope
2852 // This allows callers to set flags such as nowiki, found, etc.
2858 $text = $this->preprocessToDom( $text, $preprocessFlags );
2863 wfProfileOut( __METHOD__
. '-pfunc' );
2866 # Finish mangling title and then check for loops.
2867 # Set $title to a Title object and $titleText to the PDBK
2870 # Split the title into page and subpage
2872 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2873 if ($subpage !== '') {
2874 $ns = $this->mTitle
->getNamespace();
2876 $title = Title
::newFromText( $part1, $ns );
2878 $titleText = $title->getPrefixedText();
2879 # Check for language variants if the template is not found
2880 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2881 $wgContLang->findVariantLink( $part1, $title, true );
2883 # Do recursion depth check
2884 $limit = $this->mOptions
->getMaxTemplateDepth();
2885 if ( $frame->depth
>= $limit ) {
2887 $text = '<span class="error">' . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit ) . '</span>';
2892 # Load from database
2893 if ( !$found && $title ) {
2894 wfProfileIn( __METHOD__
. '-loadtpl' );
2895 if ( !$title->isExternal() ) {
2896 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2897 $text = SpecialPage
::capturePath( $title );
2898 if ( is_string( $text ) ) {
2901 $this->disableCache();
2903 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2904 $found = false; //access denied
2905 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
2907 list( $text, $title ) = $this->getTemplateDom( $title );
2908 if ( $text !== false ) {
2914 # If the title is valid but undisplayable, make a link to it
2915 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2916 $text = "[[:$titleText]]";
2919 } elseif ( $title->isTrans() ) {
2920 // Interwiki transclusion
2921 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
2922 $text = $this->interwikiTransclude( $title, 'render' );
2925 $text = $this->interwikiTransclude( $title, 'raw' );
2926 // Preprocess it like a template
2927 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
2933 # Do infinite loop check
2934 # This has to be done after redirect resolution to avoid infinite loops via redirects
2935 if ( !$frame->loopCheck( $title ) ) {
2937 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
2938 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
2940 wfProfileOut( __METHOD__
. '-loadtpl' );
2943 # If we haven't found text to substitute by now, we're done
2944 # Recover the source wikitext and return it
2946 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2947 wfProfileOut( __METHOD__
);
2948 return array( 'object' => $text );
2951 # Expand DOM-style return values in a child frame
2952 if ( $isChildObj ) {
2953 # Clean up argument array
2954 $newFrame = $frame->newChild( $args, $title );
2957 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
2958 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
2959 # Expansion is eligible for the empty-frame cache
2960 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
2961 $text = $this->mTplExpandCache
[$titleText];
2963 $text = $newFrame->expand( $text );
2964 $this->mTplExpandCache
[$titleText] = $text;
2967 # Uncached expansion
2968 $text = $newFrame->expand( $text );
2971 if ( $isLocalObj && $nowiki ) {
2972 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
2973 $isLocalObj = false;
2976 # Replace raw HTML by a placeholder
2977 # Add a blank line preceding, to prevent it from mucking up
2978 # immediately preceding headings
2980 $text = "\n\n" . $this->insertStripItem( $text );
2982 # Escape nowiki-style return values
2983 elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2984 $text = wfEscapeWikiText( $text );
2986 # Bug 529: if the template begins with a table or block-level
2987 # element, it should be treated as beginning a new line.
2988 # This behaviour is somewhat controversial.
2989 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
2990 $text = "\n" . $text;
2993 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
2994 # Error, oversize inclusion
2995 $text = "[[$originalTitle]]" .
2996 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
2997 $this->limitationWarn( 'post-expand-template-inclusion' );
3000 if ( $isLocalObj ) {
3001 $ret = array( 'object' => $text );
3003 $ret = array( 'text' => $text );
3006 wfProfileOut( __METHOD__
);
3011 * Get the semi-parsed DOM representation of a template with a given title,
3012 * and its redirect destination title. Cached.
3014 function getTemplateDom( $title ) {
3015 $cacheTitle = $title;
3016 $titleText = $title->getPrefixedDBkey();
3018 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3019 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3020 $title = Title
::makeTitle( $ns, $dbk );
3021 $titleText = $title->getPrefixedDBkey();
3023 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3024 return array( $this->mTplDomCache
[$titleText], $title );
3027 // Cache miss, go to the database
3028 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3030 if ( $text === false ) {
3031 $this->mTplDomCache
[$titleText] = false;
3032 return array( false, $title );
3035 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3036 $this->mTplDomCache
[ $titleText ] = $dom;
3038 if (! $title->equals($cacheTitle)) {
3039 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3040 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3043 return array( $dom, $title );
3047 * Fetch the unparsed text of a template and register a reference to it.
3049 function fetchTemplateAndTitle( $title ) {
3050 $templateCb = $this->mOptions
->getTemplateCallback();
3051 $stuff = call_user_func( $templateCb, $title, $this );
3052 $text = $stuff['text'];
3053 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3054 if ( isset( $stuff['deps'] ) ) {
3055 foreach ( $stuff['deps'] as $dep ) {
3056 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3059 return array($text,$finalTitle);
3062 function fetchTemplate( $title ) {
3063 $rv = $this->fetchTemplateAndTitle($title);
3068 * Static function to get a template
3069 * Can be overridden via ParserOptions::setTemplateCallback().
3071 static function statelessFetchTemplate( $title, $parser=false ) {
3072 $text = $skip = false;
3073 $finalTitle = $title;
3076 // Loop to fetch the article, with up to 1 redirect
3077 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3078 # Give extensions a chance to select the revision instead
3079 $id = false; // Assume current
3080 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3086 'page_id' => $title->getArticleID(),
3090 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3091 $rev_id = $rev ?
$rev->getId() : 0;
3092 // If there is no current revision, there is no page
3093 if( $id === false && !$rev ) {
3094 $linkCache = LinkCache
::singleton();
3095 $linkCache->addBadLinkObj( $title );
3100 'page_id' => $title->getArticleID(),
3101 'rev_id' => $rev_id );
3104 $text = $rev->getText();
3105 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3107 $message = $wgContLang->lcfirst( $title->getText() );
3108 $text = wfMsgForContentNoTrans( $message );
3109 if( wfEmptyMsg( $message, $text ) ) {
3116 if ( $text === false ) {
3120 $finalTitle = $title;
3121 $title = Title
::newFromRedirect( $text );
3125 'finalTitle' => $finalTitle,
3130 * Transclude an interwiki link.
3132 function interwikiTransclude( $title, $action ) {
3133 global $wgEnableScaryTranscluding;
3135 if (!$wgEnableScaryTranscluding)
3136 return wfMsg('scarytranscludedisabled');
3138 $url = $title->getFullUrl( "action=$action" );
3140 if (strlen($url) > 255)
3141 return wfMsg('scarytranscludetoolong');
3142 return $this->fetchScaryTemplateMaybeFromCache($url);
3145 function fetchScaryTemplateMaybeFromCache($url) {
3146 global $wgTranscludeCacheExpiry;
3147 $dbr = wfGetDB(DB_SLAVE
);
3148 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3149 array('tc_url' => $url));
3151 $time = $obj->tc_time
;
3152 $text = $obj->tc_contents
;
3153 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3158 $text = Http
::get($url);
3160 return wfMsg('scarytranscludefailed', $url);
3162 $dbw = wfGetDB(DB_MASTER
);
3163 $dbw->replace('transcache', array('tc_url'), array(
3165 'tc_time' => time(),
3166 'tc_contents' => $text));
3172 * Triple brace replacement -- used for template arguments
3175 function argSubstitution( $piece, $frame ) {
3176 wfProfileIn( __METHOD__
);
3179 $parts = $piece['parts'];
3180 $nameWithSpaces = $frame->expand( $piece['title'] );
3181 $argName = trim( $nameWithSpaces );
3183 $text = $frame->getArgument( $argName );
3184 if ( $text === false && $parts->getLength() > 0
3188 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3191 # No match in frame, use the supplied default
3192 $object = $parts->item( 0 )->getChildren();
3194 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3195 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3196 $this->limitationWarn( 'post-expand-template-argument' );
3199 if ( $text === false && $object === false ) {
3201 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3203 if ( $error !== false ) {
3206 if ( $object !== false ) {
3207 $ret = array( 'object' => $object );
3209 $ret = array( 'text' => $text );
3212 wfProfileOut( __METHOD__
);
3217 * Return the text to be used for a given extension tag.
3218 * This is the ghost of strip().
3220 * @param array $params Associative array of parameters:
3221 * name PPNode for the tag name
3222 * attr PPNode for unparsed text where tag attributes are thought to be
3223 * attributes Optional associative array of parsed attributes
3224 * inner Contents of extension element
3225 * noClose Original text did not have a close tag
3226 * @param PPFrame $frame
3228 function extensionSubstitution( $params, $frame ) {
3229 global $wgRawHtml, $wgContLang;
3231 $name = $frame->expand( $params['name'] );
3232 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3233 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3235 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3237 if ( $this->ot
['html'] ) {
3238 $name = strtolower( $name );
3240 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3241 if ( isset( $params['attributes'] ) ) {
3242 $attributes = $attributes +
$params['attributes'];
3250 throw new MWException( '<html> extension tag encountered unexpectedly' );
3253 $content = strtr($content, array('-{' => '-{', '}-' => '}-'));
3254 $output = Xml
::escapeTagsOnly( $content );
3257 $output = $wgContLang->armourMath(
3258 MathRenderer
::renderMath( $content, $attributes ) );
3261 $output = $this->renderImageGallery( $content, $attributes );
3264 if( isset( $this->mTagHooks
[$name] ) ) {
3265 # Workaround for PHP bug 35229 and similar
3266 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3267 throw new MWException( "Tag hook for $name is not callable\n" );
3269 $output = call_user_func_array( $this->mTagHooks
[$name],
3270 array( $content, $attributes, $this ) );
3272 $output = '<span class="error">Invalid tag extension name: ' .
3273 htmlspecialchars( $name ) . '</span>';
3277 if ( is_null( $attrText ) ) {
3280 if ( isset( $params['attributes'] ) ) {
3281 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3282 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3283 htmlspecialchars( $attrValue ) . '"';
3286 if ( $content === null ) {
3287 $output = "<$name$attrText/>";
3289 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3290 $output = "<$name$attrText>$content$close";
3294 if ( $name === 'html' ||
$name === 'nowiki' ) {
3295 $this->mStripState
->nowiki
->setPair( $marker, $output );
3297 $this->mStripState
->general
->setPair( $marker, $output );
3303 * Increment an include size counter
3305 * @param string $type The type of expansion
3306 * @param integer $size The size of the text
3307 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3309 function incrementIncludeSize( $type, $size ) {
3310 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3313 $this->mIncludeSizes
[$type] +
= $size;
3319 * Increment the expensive function count
3321 * @return boolean False if the limit has been exceeded
3323 function incrementExpensiveFunctionCount() {
3324 global $wgExpensiveParserFunctionLimit;
3325 $this->mExpensiveFunctionCount++
;
3326 if($this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit) {
3333 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3334 * Fills $this->mDoubleUnderscores, returns the modified text
3336 function doDoubleUnderscore( $text ) {
3337 wfProfileIn( __METHOD__
);
3338 // The position of __TOC__ needs to be recorded
3339 $mw = MagicWord
::get( 'toc' );
3340 if( $mw->match( $text ) ) {
3341 $this->mShowToc
= true;
3342 $this->mForceTocPosition
= true;
3344 // Set a placeholder. At the end we'll fill it in with the TOC.
3345 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3347 // Only keep the first one.
3348 $text = $mw->replace( '', $text );
3351 // Now match and remove the rest of them
3352 $mwa = MagicWord
::getDoubleUnderscoreArray();
3353 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3355 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3356 $this->mOutput
->mNoGallery
= true;
3358 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3359 $this->mShowToc
= false;
3361 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3362 $this->mOutput
->setProperty( 'hiddencat', 'y' );
3364 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( 'hidden-category-category' ) );
3365 if ( $containerCategory ) {
3366 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3368 wfDebug( __METHOD__
.": [[MediaWiki:hidden-category-category]] is not a valid title!\n" );
3371 # (bug 8068) Allow control over whether robots index a page.
3373 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3374 # is not desirable, the last one on the page should win.
3375 if( isset( $this->mDoubleUnderscores
['noindex'] ) ) {
3376 $this->mOutput
->setIndexPolicy( 'noindex' );
3377 } elseif( isset( $this->mDoubleUnderscores
['index'] ) ) {
3378 $this->mOutput
->setIndexPolicy( 'index' );
3380 wfProfileOut( __METHOD__
);
3385 * This function accomplishes several tasks:
3386 * 1) Auto-number headings if that option is enabled
3387 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3388 * 3) Add a Table of contents on the top for users who have enabled the option
3389 * 4) Auto-anchor headings
3391 * It loops through all headlines, collects the necessary data, then splits up the
3392 * string and re-inserts the newly formatted headlines.
3394 * @param string $text
3395 * @param string $origText Original, untouched wikitext
3396 * @param boolean $isMain
3399 function formatHeadings( $text, $origText, $isMain=true ) {
3400 global $wgMaxTocLevel, $wgContLang, $wgEnforceHtmlIds;
3402 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3403 $showEditLink = $this->mOptions
->getEditSection();
3405 // Do not call quickUserCan unless necessary
3406 if( $showEditLink && !$this->mTitle
->quickUserCan( 'edit' ) ) {
3410 # Inhibit editsection links if requested in the page
3411 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ||
$this->mOptions
->getIsPrintable() ) {
3415 # Get all headlines for numbering them and adding funky stuff like [edit]
3416 # links - this is for later, but we need the number of headlines right now
3418 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3420 # if there are fewer than 4 headlines in the article, do not show TOC
3421 # unless it's been explicitly enabled.
3422 $enoughToc = $this->mShowToc
&&
3423 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3425 # Allow user to stipulate that a page should have a "new section"
3426 # link added via __NEWSECTIONLINK__
3427 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3428 $this->mOutput
->setNewSection( true );
3431 # Allow user to remove the "new section"
3432 # link via __NONEWSECTIONLINK__
3433 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3434 $this->mOutput
->hideNewSection( true );
3437 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3438 # override above conditions and always show TOC above first header
3439 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3440 $this->mShowToc
= true;
3444 # We need this to perform operations on the HTML
3445 $sk = $this->mOptions
->getSkin();
3451 # Ugh .. the TOC should have neat indentation levels which can be
3452 # passed to the skin functions. These are determined here
3456 $sublevelCount = array();
3457 $levelCount = array();
3463 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3464 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3465 $oldType = $this->mOutputType
;
3466 $this->setOutputType( self
::OT_WIKI
);
3467 $frame = $this->getPreprocessor()->newFrame();
3468 $root = $this->preprocessToDom( $origText );
3469 $node = $root->getFirstChild();
3473 foreach( $matches[3] as $headline ) {
3474 $isTemplate = false;
3476 $sectionIndex = false;
3478 $markerMatches = array();
3479 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3480 $serial = $markerMatches[1];
3481 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3482 $isTemplate = ($titleText != $baseTitleText);
3483 $headline = preg_replace("/^$markerRegex/", "", $headline);
3487 $prevlevel = $level;
3488 $prevtoclevel = $toclevel;
3490 $level = $matches[1][$headlineCount];
3492 if ( $level > $prevlevel ) {
3493 # Increase TOC level
3495 $sublevelCount[$toclevel] = 0;
3496 if( $toclevel<$wgMaxTocLevel ) {
3497 $prevtoclevel = $toclevel;
3498 $toc .= $sk->tocIndent();
3502 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3503 # Decrease TOC level, find level to jump to
3505 for ($i = $toclevel; $i > 0; $i--) {
3506 if ( $levelCount[$i] == $level ) {
3507 # Found last matching level
3511 elseif ( $levelCount[$i] < $level ) {
3512 # Found first matching level below current level
3517 if( $i == 0 ) $toclevel = 1;
3518 if( $toclevel<$wgMaxTocLevel ) {
3519 if($prevtoclevel < $wgMaxTocLevel) {
3520 # Unindent only if the previous toc level was shown :p
3521 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3522 $prevtoclevel = $toclevel;
3524 $toc .= $sk->tocLineEnd();
3529 # No change in level, end TOC line
3530 if( $toclevel<$wgMaxTocLevel ) {
3531 $toc .= $sk->tocLineEnd();
3535 $levelCount[$toclevel] = $level;
3537 # count number of headlines for each level
3538 @$sublevelCount[$toclevel]++
;
3540 for( $i = 1; $i <= $toclevel; $i++
) {
3541 if( !empty( $sublevelCount[$i] ) ) {
3545 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3550 # The safe header is a version of the header text safe to use for links
3551 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3552 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3554 # Remove link placeholders by the link text.
3555 # <!--LINK number-->
3557 # link text with suffix
3558 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3560 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3561 $tocline = preg_replace(
3562 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3566 $tocline = trim( $tocline );
3568 # For the anchor, strip out HTML-y stuff period
3569 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3570 $safeHeadline = preg_replace( '/[ _]+/', ' ', $safeHeadline );
3571 $safeHeadline = trim( $safeHeadline );
3573 # Save headline for section edit hint before it's escaped
3574 $headlineHint = $safeHeadline;
3576 if ( $wgEnforceHtmlIds ) {
3577 $legacyHeadline = false;
3578 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
3581 # For reverse compatibility, provide an id that's
3582 # HTML4-compatible, like we used to.
3584 # It may be worth noting, academically, that it's possible for
3585 # the legacy anchor to conflict with a non-legacy headline
3586 # anchor on the page. In this case likely the "correct" thing
3587 # would be to either drop the legacy anchors or make sure
3588 # they're numbered first. However, this would require people
3589 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3590 # manually, so let's not bother worrying about it.
3591 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
3593 $safeHeadline = Sanitizer
::escapeId( $safeHeadline, 'xml' );
3595 if ( $legacyHeadline == $safeHeadline ) {
3596 # No reason to have both (in fact, we can't)
3597 $legacyHeadline = false;
3598 } elseif ( $legacyHeadline != Sanitizer
::escapeId(
3599 $legacyHeadline, 'xml' ) ) {
3600 # The legacy id is invalid XML. We used to allow this, but
3601 # there's no reason to do so anymore. Backward
3602 # compatibility will fail slightly in this case, but it's
3604 $legacyHeadline = false;
3608 # HTML names must be case-insensitively unique (bug 10721). FIXME:
3609 # Does this apply to Unicode characters? Because we aren't
3610 # handling those here.
3611 $arrayKey = strtolower( $safeHeadline );
3612 if ( $legacyHeadline === false ) {
3613 $legacyArrayKey = false;
3615 $legacyArrayKey = strtolower( $legacyHeadline );
3618 # count how many in assoc. array so we can track dupes in anchors
3619 if ( isset( $refers[$arrayKey] ) ) {
3620 $refers[$arrayKey]++
;
3622 $refers[$arrayKey] = 1;
3624 if ( isset( $refers[$legacyArrayKey] ) ) {
3625 $refers[$legacyArrayKey]++
;
3627 $refers[$legacyArrayKey] = 1;
3630 # Don't number the heading if it is the only one (looks silly)
3631 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3632 # the two are different if the line contains a link
3633 $headline=$numbering . ' ' . $headline;
3636 # Create the anchor for linking from the TOC to the section
3637 $anchor = $safeHeadline;
3638 $legacyAnchor = $legacyHeadline;
3639 if ( $refers[$arrayKey] > 1 ) {
3640 $anchor .= '_' . $refers[$arrayKey];
3642 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3643 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3645 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3646 $toc .= $sk->tocLine($anchor, $tocline,
3647 $numbering, $toclevel, ($isTemplate ?
false : $sectionIndex));
3650 # Add the section to the section tree
3651 # Find the DOM node for this header
3652 while ( $node && !$isTemplate ) {
3653 if ( $node->getName() === 'h' ) {
3654 $bits = $node->splitHeading();
3655 if ( $bits['i'] == $sectionIndex )
3658 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
3659 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
3660 $node = $node->getNextSibling();
3663 'toclevel' => $toclevel,
3666 'number' => $numbering,
3667 'index' => ($isTemplate ?
'T-' : '' ) . $sectionIndex,
3668 'fromtitle' => $titleText,
3669 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
3670 'anchor' => $anchor,
3673 # give headline the correct <h#> tag
3674 if( $showEditLink && $sectionIndex !== false ) {
3676 # Put a T flag in the section identifier, to indicate to extractSections()
3677 # that sections inside <includeonly> should be counted.
3678 $editlink = $sk->doEditSectionLink(Title
::newFromText( $titleText ), "T-$sectionIndex");
3680 $editlink = $sk->doEditSectionLink($this->mTitle
, $sectionIndex, $headlineHint);
3685 $head[$headlineCount] = $sk->makeHeadline( $level,
3686 $matches['attrib'][$headlineCount], $anchor, $headline,
3687 $editlink, $legacyAnchor );
3692 $this->setOutputType( $oldType );
3694 # Never ever show TOC if no headers
3695 if( $numVisible < 1 ) {
3700 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3701 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3703 $toc = $sk->tocList( $toc );
3707 $this->mOutput
->setSections( $tocraw );
3708 $this->mOutput
->setTOCHTML( $toc );
3711 # split up and insert constructed headlines
3713 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3716 foreach( $blocks as $block ) {
3717 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3718 # This is the [edit] link that appears for the top block of text when
3719 # section editing is enabled
3721 # Disabled because it broke block formatting
3722 # For example, a bullet point in the top line
3723 # $full .= $sk->editSectionLink(0);
3726 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3727 # Top anchor now in skin
3731 if( !empty( $head[$i] ) ) {
3736 if( $this->mForceTocPosition
) {
3737 return str_replace( '<!--MWTOC-->', $toc, $full );
3744 * Merge $tree2 into $tree1 by replacing the section with index
3745 * $section in $tree1 and its descendants with the sections in $tree2.
3746 * Note that in the returned section tree, only the 'index' and
3747 * 'byteoffset' fields are guaranteed to be correct.
3748 * @param $tree1 array Section tree from ParserOutput::getSectons()
3749 * @param $tree2 array Section tree
3750 * @param $section int Section index
3751 * @param $title Title Title both section trees come from
3752 * @param $len2 int Length of the original wikitext for $tree2
3753 * @return array Merged section tree
3755 public static function mergeSectionTrees( $tree1, $tree2, $section, $title, $len2 ) {
3758 $targetLevel = false;
3762 $numbering = array( 0 );
3763 $titletext = $title->getPrefixedDBkey();
3764 foreach ( $tree1 as $s ) {
3765 if ( $targetLevel !== false ) {
3766 if ( $s['level'] <= $targetLevel )
3767 // We've skipped enough
3768 $targetLevel = false;
3772 if ( $s['index'] != $section ||
3773 $s['fromtitle'] != $titletext ) {
3774 self
::incrementNumbering( $numbering,
3775 $s['toclevel'], $lastLevel );
3777 // Rewrite index, byteoffset and number
3778 if ( $s['fromtitle'] == $titletext ) {
3779 $s['index'] = $nextIndex++
;
3781 $s['byteoffset'] +
= $len2;
3783 $s['number'] = implode( '.', array_map(
3784 array( $wgContLang, 'formatnum' ),
3786 $lastLevel = $s['toclevel'];
3789 // We're at $section
3790 // Insert sections from $tree2 here
3791 foreach ( $tree2 as $s2 ) {
3792 // Rewrite the fields in $s2
3793 // before inserting it
3794 $s2['toclevel'] +
= $s['toclevel'] - 1;
3795 $s2['level'] +
= $s['level'] - 1;
3796 $s2['index'] = $nextIndex++
;
3797 $s2['byteoffset'] +
= $s['byteoffset'];
3799 self
::incrementNumbering( $numbering,
3800 $s2['toclevel'], $lastLevel );
3801 $s2['number'] = implode( '.', array_map(
3802 array( $wgContLang, 'formatnum' ),
3804 $lastLevel = $s2['toclevel'];
3807 // Skip all descendants of $section in $tree1
3808 $targetLevel = $s['level'];
3816 * Increment a section number. Helper function for mergeSectionTrees()
3817 * @param $number array Array representing a section number
3818 * @param $level int Current TOC level (depth)
3819 * @param $lastLevel int Level of previous TOC entry
3821 private static function incrementNumbering( &$number, $level, $lastLevel ) {
3822 if ( $level > $lastLevel )
3823 $number[$level - 1] = 1;
3824 else if ( $level < $lastLevel ) {
3825 foreach ( $number as $key => $unused )
3826 if ( $key >= $level )
3827 unset( $number[$key] );
3828 $number[$level - 1]++
;
3830 $number[$level - 1]++
;
3834 * Transform wiki markup when saving a page by doing \r\n -> \n
3835 * conversion, substitting signatures, {{subst:}} templates, etc.
3837 * @param string $text the text to transform
3838 * @param Title &$title the Title object for the current article
3839 * @param User $user the User object describing the current user
3840 * @param ParserOptions $options parsing options
3841 * @param bool $clearState whether to clear the parser state first
3842 * @return string the altered wiki markup
3845 function preSaveTransform( $text, Title
$title, $user, $options, $clearState = true ) {
3846 $this->mOptions
= $options;
3847 $this->setTitle( $title );
3848 $this->setOutputType( self
::OT_WIKI
);
3850 if ( $clearState ) {
3851 $this->clearState();
3857 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3858 $text = $this->pstPass2( $text, $user );
3859 $text = $this->mStripState
->unstripBoth( $text );
3864 * Pre-save transform helper function
3867 function pstPass2( $text, $user ) {
3868 global $wgContLang, $wgLocaltimezone;
3870 /* Note: This is the timestamp saved as hardcoded wikitext to
3871 * the database, we use $wgContLang here in order to give
3872 * everyone the same signature and use the default one rather
3873 * than the one selected in each user's preferences.
3875 * (see also bug 12815)
3877 $ts = $this->mOptions
->getTimestamp();
3878 $tz = wfMsgForContent( 'timezone-utc' );
3879 if ( isset( $wgLocaltimezone ) ) {
3880 $unixts = wfTimestamp( TS_UNIX
, $ts );
3881 $oldtz = getenv( 'TZ' );
3882 putenv( 'TZ='.$wgLocaltimezone );
3883 $ts = date( 'YmdHis', $unixts );
3884 $tz = date( 'T', $unixts ); # might vary on DST changeover!
3886 /* Allow translation of timezones trough wiki. date() can return
3887 * whatever crap the system uses, localised or not, so we cannot
3888 * ship premade translations.
3890 $key = 'timezone-' . strtolower( trim( $tz ) );
3891 $value = wfMsgForContent( $key );
3892 if ( !wfEmptyMsg( $key, $value ) ) $tz = $value;
3894 putenv( 'TZ='.$oldtz );
3897 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tz)";
3899 # Variable replacement
3900 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3901 $text = $this->replaceVariables( $text );
3904 $sigText = $this->getUserSig( $user );
3905 $text = strtr( $text, array(
3907 '~~~~' => "$sigText $d",
3911 # Context links: [[|name]] and [[name (context)|]]
3913 global $wgLegalTitleChars;
3914 $tc = "[$wgLegalTitleChars]";
3915 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
3917 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3918 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
3919 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3920 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3922 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3923 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3924 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
3925 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3927 $t = $this->mTitle
->getText();
3929 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3930 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3931 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3932 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3934 # if there's no context, don't bother duplicating the title
3935 $text = preg_replace( $p2, '[[\\1]]', $text );
3938 # Trim trailing whitespace
3939 $text = rtrim( $text );
3945 * Fetch the user's signature text, if any, and normalize to
3946 * validated, ready-to-insert wikitext.
3952 function getUserSig( &$user ) {
3953 global $wgMaxSigChars;
3955 $username = $user->getName();
3956 $nickname = $user->getOption( 'nickname' );
3957 $nickname = $nickname === null ?
$username : $nickname;
3959 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3960 $nickname = $username;
3961 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
3962 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3963 # Sig. might contain markup; validate this
3964 if( $this->validateSig( $nickname ) !== false ) {
3965 # Validated; clean up (if needed) and return it
3966 return $this->cleanSig( $nickname, true );
3968 # Failed to validate; fall back to the default
3969 $nickname = $username;
3970 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
3974 // Make sure nickname doesnt get a sig in a sig
3975 $nickname = $this->cleanSigInSig( $nickname );
3977 # If we're still here, make it a link to the user page
3978 $userText = wfEscapeWikiText( $username );
3979 $nickText = wfEscapeWikiText( $nickname );
3980 if ( $user->isAnon() ) {
3981 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
3983 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
3988 * Check that the user's signature contains no bad XML
3990 * @param string $text
3991 * @return mixed An expanded string, or false if invalid.
3993 function validateSig( $text ) {
3994 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
3998 * Clean up signature text
4000 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4001 * 2) Substitute all transclusions
4003 * @param string $text
4004 * @param $parsing Whether we're cleaning (preferences save) or parsing
4005 * @return string Signature text
4007 function cleanSig( $text, $parsing = false ) {
4010 $this->clearState();
4011 $this->setTitle( $wgTitle );
4012 $this->mOptions
= new ParserOptions
;
4013 $this->setOutputType
= self
::OT_PREPROCESS
;
4016 # Option to disable this feature
4017 if ( !$this->mOptions
->getCleanSignatures() ) {
4021 # FIXME: regex doesn't respect extension tags or nowiki
4022 # => Move this logic to braceSubstitution()
4023 $substWord = MagicWord
::get( 'subst' );
4024 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4025 $substText = '{{' . $substWord->getSynonym( 0 );
4027 $text = preg_replace( $substRegex, $substText, $text );
4028 $text = $this->cleanSigInSig( $text );
4029 $dom = $this->preprocessToDom( $text );
4030 $frame = $this->getPreprocessor()->newFrame();
4031 $text = $frame->expand( $dom );
4034 $text = $this->mStripState
->unstripBoth( $text );
4041 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4042 * @param string $text
4043 * @return string Signature text with /~{3,5}/ removed
4045 function cleanSigInSig( $text ) {
4046 $text = preg_replace( '/~{3,5}/', '', $text );
4051 * Set up some variables which are usually set up in parse()
4052 * so that an external function can call some class members with confidence
4055 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
4056 $this->setTitle( $title );
4057 $this->mOptions
= $options;
4058 $this->setOutputType( $outputType );
4059 if ( $clearState ) {
4060 $this->clearState();
4065 * Wrapper for preprocess()
4067 * @param string $text the text to preprocess
4068 * @param ParserOptions $options options
4072 function transformMsg( $text, $options ) {
4074 static $executing = false;
4076 # Guard against infinite recursion
4082 wfProfileIn(__METHOD__
);
4083 $text = $this->preprocess( $text, $wgTitle, $options );
4086 wfProfileOut(__METHOD__
);
4091 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4092 * The callback should have the following form:
4093 * function myParserHook( $text, $params, &$parser ) { ... }
4095 * Transform and return $text. Use $parser for any required context, e.g. use
4096 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4100 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
4101 * @param mixed $callback The callback function (and object) to use for the tag
4103 * @return The old value of the mTagHooks array associated with the hook
4105 function setHook( $tag, $callback ) {
4106 $tag = strtolower( $tag );
4107 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4108 $this->mTagHooks
[$tag] = $callback;
4109 if( !in_array( $tag, $this->mStripList
) ) {
4110 $this->mStripList
[] = $tag;
4116 function setTransparentTagHook( $tag, $callback ) {
4117 $tag = strtolower( $tag );
4118 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4119 $this->mTransparentTagHooks
[$tag] = $callback;
4125 * Remove all tag hooks
4127 function clearTagHooks() {
4128 $this->mTagHooks
= array();
4129 $this->mStripList
= $this->mDefaultStripList
;
4133 * Create a function, e.g. {{sum:1|2|3}}
4134 * The callback function should have the form:
4135 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4137 * Or with SFH_OBJECT_ARGS:
4138 * function myParserFunction( $parser, $frame, $args ) { ... }
4140 * The callback may either return the text result of the function, or an array with the text
4141 * in element 0, and a number of flags in the other elements. The names of the flags are
4142 * specified in the keys. Valid flags are:
4143 * found The text returned is valid, stop processing the template. This
4145 * nowiki Wiki markup in the return value should be escaped
4146 * isHTML The returned text is HTML, armour it against wikitext transformation
4150 * @param string $id The magic word ID
4151 * @param mixed $callback The callback function (and object) to use
4152 * @param integer $flags a combination of the following flags:
4153 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4155 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4156 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4157 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4158 * the arguments, and to control the way they are expanded.
4160 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4161 * arguments, for instance:
4162 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4164 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4165 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4166 * working if/when this is changed.
4168 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4171 * Please read the documentation in includes/parser/Preprocessor.php for more information
4172 * about the methods available in PPFrame and PPNode.
4174 * @return The old callback function for this name, if any
4176 function setFunctionHook( $id, $callback, $flags = 0 ) {
4177 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4178 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4180 # Add to function cache
4181 $mw = MagicWord
::get( $id );
4183 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4185 $synonyms = $mw->getSynonyms();
4186 $sensitive = intval( $mw->isCaseSensitive() );
4188 foreach ( $synonyms as $syn ) {
4190 if ( !$sensitive ) {
4191 $syn = strtolower( $syn );
4194 if ( !( $flags & SFH_NO_HASH
) ) {
4197 # Remove trailing colon
4198 if ( substr( $syn, -1, 1 ) === ':' ) {
4199 $syn = substr( $syn, 0, -1 );
4201 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4207 * Get all registered function hook identifiers
4211 function getFunctionHooks() {
4212 return array_keys( $this->mFunctionHooks
);
4216 * FIXME: update documentation. makeLinkObj() is deprecated.
4217 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4218 * Placeholders created in Skin::makeLinkObj()
4219 * Returns an array of link CSS classes, indexed by PDBK.
4221 function replaceLinkHolders( &$text, $options = 0 ) {
4222 return $this->mLinkHolders
->replace( $text );
4226 * Replace <!--LINK--> link placeholders with plain text of links
4227 * (not HTML-formatted).
4228 * @param string $text
4231 function replaceLinkHoldersText( $text ) {
4232 return $this->mLinkHolders
->replaceText( $text );
4236 * Tag hook handler for 'pre'.
4238 function renderPreTag( $text, $attribs ) {
4239 // Backwards-compatibility hack
4240 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4242 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4243 return Xml
::openElement( 'pre', $attribs ) .
4244 Xml
::escapeTagsOnly( $content ) .
4249 * Renders an image gallery from a text with one line per image.
4250 * text labels may be given by using |-style alternative text. E.g.
4251 * Image:one.jpg|The number "1"
4252 * Image:tree.jpg|A tree
4253 * given as text will return the HTML of a gallery with two images,
4254 * labeled 'The number "1"' and
4257 function renderImageGallery( $text, $params ) {
4258 $ig = new ImageGallery();
4259 $ig->setContextTitle( $this->mTitle
);
4260 $ig->setShowBytes( false );
4261 $ig->setShowFilename( false );
4262 $ig->setParser( $this );
4263 $ig->setHideBadImages();
4264 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4265 $ig->useSkin( $this->mOptions
->getSkin() );
4266 $ig->mRevisionId
= $this->mRevisionId
;
4268 if( isset( $params['caption'] ) ) {
4269 $caption = $params['caption'];
4270 $caption = htmlspecialchars( $caption );
4271 $caption = $this->replaceInternalLinks( $caption );
4272 $ig->setCaptionHtml( $caption );
4274 if( isset( $params['perrow'] ) ) {
4275 $ig->setPerRow( $params['perrow'] );
4277 if( isset( $params['widths'] ) ) {
4278 $ig->setWidths( $params['widths'] );
4280 if( isset( $params['heights'] ) ) {
4281 $ig->setHeights( $params['heights'] );
4284 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4286 $lines = StringUtils
::explode( "\n", $text );
4287 foreach ( $lines as $line ) {
4288 # match lines like these:
4289 # Image:someimage.jpg|This is some image
4291 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4293 if ( count( $matches ) == 0 ) {
4297 if ( strpos( $matches[0], '%' ) !== false )
4298 $matches[1] = urldecode( $matches[1] );
4299 $tp = Title
::newFromText( $matches[1]/*, NS_FILE*/ );
4301 if( is_null( $nt ) ) {
4302 # Bogus title. Ignore these so we don't bomb out later.
4305 if ( isset( $matches[3] ) ) {
4306 $label = $matches[3];
4311 $html = $this->recursiveTagParse( trim( $label ) );
4313 $ig->add( $nt, $html );
4315 # Only add real images (bug #5586)
4316 if ( $nt->getNamespace() == NS_FILE
) {
4317 $this->mOutput
->addImage( $nt->getDBkey() );
4320 return $ig->toHTML();
4323 function getImageParams( $handler ) {
4325 $handlerClass = get_class( $handler );
4329 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4330 // Initialise static lists
4331 static $internalParamNames = array(
4332 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4333 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4334 'bottom', 'text-bottom' ),
4335 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4336 'upright', 'border', 'link', 'alt' ),
4338 static $internalParamMap;
4339 if ( !$internalParamMap ) {
4340 $internalParamMap = array();
4341 foreach ( $internalParamNames as $type => $names ) {
4342 foreach ( $names as $name ) {
4343 $magicName = str_replace( '-', '_', "img_$name" );
4344 $internalParamMap[$magicName] = array( $type, $name );
4349 // Add handler params
4350 $paramMap = $internalParamMap;
4352 $handlerParamMap = $handler->getParamMap();
4353 foreach ( $handlerParamMap as $magic => $paramName ) {
4354 $paramMap[$magic] = array( 'handler', $paramName );
4357 $this->mImageParams
[$handlerClass] = $paramMap;
4358 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4360 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4364 * Parse image options text and use it to make an image
4365 * @param Title $title
4366 * @param string $options
4367 * @param LinkHolderArray $holders
4369 function makeImage( $title, $options, $holders = false ) {
4370 # Check if the options text is of the form "options|alt text"
4372 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4373 # * left no resizing, just left align. label is used for alt= only
4374 # * right same, but right aligned
4375 # * none same, but not aligned
4376 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4377 # * center center the image
4378 # * framed Keep original image size, no magnify-button.
4379 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4380 # * upright reduce width for upright images, rounded to full __0 px
4381 # * border draw a 1px border around the image
4382 # * alt Text for HTML alt attribute (defaults to empty)
4383 # vertical-align values (no % or length right now):
4393 $parts = StringUtils
::explode( "|", $options );
4394 $sk = $this->mOptions
->getSkin();
4396 # Give extensions a chance to select the file revision for us
4397 $skip = $time = $descQuery = false;
4398 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4401 return $sk->link( $title );
4405 $imagename = $title->getDBkey();
4406 if ( isset( $this->mFileCache
[$imagename][$time] ) ) {
4407 $file = $this->mFileCache
[$imagename][$time];
4409 $file = wfFindFile( $title, $time );
4410 if ( count( $this->mFileCache
) > 1000 ) {
4411 $this->mFileCache
= array();
4413 $this->mFileCache
[$imagename][$time] = $file;
4416 $handler = $file ?
$file->getHandler() : false;
4418 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4420 # Process the input parameters
4422 $params = array( 'frame' => array(), 'handler' => array(),
4423 'horizAlign' => array(), 'vertAlign' => array() );
4424 foreach( $parts as $part ) {
4425 $part = trim( $part );
4426 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4428 if( isset( $paramMap[$magicName] ) ) {
4429 list( $type, $paramName ) = $paramMap[$magicName];
4431 // Special case; width and height come in one variable together
4432 if( $type === 'handler' && $paramName === 'width' ) {
4434 # (bug 13500) In both cases (width/height and width only),
4435 # permit trailing "px" for backward compatibility.
4436 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4437 $width = intval( $m[1] );
4438 $height = intval( $m[2] );
4439 if ( $handler->validateParam( 'width', $width ) ) {
4440 $params[$type]['width'] = $width;
4443 if ( $handler->validateParam( 'height', $height ) ) {
4444 $params[$type]['height'] = $height;
4447 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4448 $width = intval( $value );
4449 if ( $handler->validateParam( 'width', $width ) ) {
4450 $params[$type]['width'] = $width;
4453 } // else no validation -- bug 13436
4455 if ( $type === 'handler' ) {
4456 # Validate handler parameter
4457 $validated = $handler->validateParam( $paramName, $value );
4459 # Validate internal parameters
4460 switch( $paramName ) {
4463 // @fixme - possibly check validity here for
4464 // manualthumb? downstream behavior seems odd with
4465 // missing manual thumbs.
4467 $value = $this->stripAltText( $value, $holders );
4470 $chars = self
::EXT_LINK_URL_CLASS
;
4471 $prots = $this->mUrlProtocols
;
4472 if ( $value === '' ) {
4473 $paramName = 'no-link';
4476 } elseif ( preg_match( "/^$prots/", $value ) ) {
4477 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4478 $paramName = 'link-url';
4479 $this->mOutput
->addExternalLink( $value );
4483 $linkTitle = Title
::newFromText( $value );
4485 $paramName = 'link-title';
4486 $value = $linkTitle;
4487 $this->mOutput
->addLink( $linkTitle );
4493 // Most other things appear to be empty or numeric...
4494 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4499 $params[$type][$paramName] = $value;
4503 if ( !$validated ) {
4508 # Process alignment parameters
4509 if ( $params['horizAlign'] ) {
4510 $params['frame']['align'] = key( $params['horizAlign'] );
4512 if ( $params['vertAlign'] ) {
4513 $params['frame']['valign'] = key( $params['vertAlign'] );
4516 $params['frame']['caption'] = $caption;
4518 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4520 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4521 # came to also set the caption, ordinary text after the image -- which
4522 # makes no sense, because that just repeats the text multiple times in
4523 # screen readers. It *also* came to set the title attribute.
4525 # Now that we have an alt attribute, we should not set the alt text to
4526 # equal the caption: that's worse than useless, it just repeats the
4527 # text. This is the framed/thumbnail case. If there's no caption, we
4528 # use the unnamed parameter for alt text as well, just for the time be-
4529 # ing, if the unnamed param is set and the alt param is not.
4531 # For the future, we need to figure out if we want to tweak this more,
4532 # e.g., introducing a title= parameter for the title; ignoring the un-
4533 # named parameter entirely for images without a caption; adding an ex-
4534 # plicit caption= parameter and preserving the old magic unnamed para-
4536 if( $caption !== '' && !isset( $params['frame']['alt'] )
4537 && !isset( $params['frame']['framed'] )
4538 && !isset( $params['frame']['thumbnail'] )
4539 && !isset( $params['frame']['manualthumb'] ) ) {
4540 $params['frame']['alt'] = $params['frame']['title'];
4543 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4545 # Linker does the rest
4546 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4548 # Give the handler a chance to modify the parser object
4550 $handler->parserTransformHook( $this, $file );
4556 protected function stripAltText( $caption, $holders ) {
4557 # Strip bad stuff out of the title (tooltip). We can't just use
4558 # replaceLinkHoldersText() here, because if this function is called
4559 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4561 $tooltip = $holders->replaceText( $caption );
4563 $tooltip = $this->replaceLinkHoldersText( $caption );
4566 # make sure there are no placeholders in thumbnail attributes
4567 # that are later expanded to html- so expand them now and
4569 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
4570 $tooltip = Sanitizer
::stripAllTags( $tooltip );
4576 * Set a flag in the output object indicating that the content is dynamic and
4577 * shouldn't be cached.
4579 function disableCache() {
4580 wfDebug( "Parser output marked as uncacheable.\n" );
4581 $this->mOutput
->mCacheTime
= -1;
4585 * Callback from the Sanitizer for expanding items found in HTML attribute
4586 * values, so they can be safely tested and escaped.
4587 * @param string $text
4588 * @param PPFrame $frame
4592 function attributeStripCallback( &$text, $frame = false ) {
4593 $text = $this->replaceVariables( $text, $frame );
4594 $text = $this->mStripState
->unstripBoth( $text );
4603 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4604 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4605 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4611 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4616 * Break wikitext input into sections, and either pull or replace
4617 * some particular section's text.
4619 * External callers should use the getSection and replaceSection methods.
4621 * @param string $text Page wikitext
4622 * @param string $section A section identifier string of the form:
4623 * <flag1> - <flag2> - ... - <section number>
4625 * Currently the only recognised flag is "T", which means the target section number
4626 * was derived during a template inclusion parse, in other words this is a template
4627 * section edit link. If no flags are given, it was an ordinary section edit link.
4628 * This flag is required to avoid a section numbering mismatch when a section is
4629 * enclosed by <includeonly> (bug 6563).
4631 * The section number 0 pulls the text before the first heading; other numbers will
4632 * pull the given section along with its lower-level subsections. If the section is
4633 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4635 * @param string $mode One of "get" or "replace"
4636 * @param string $newText Replacement text for section data.
4637 * @return string for "get", the extracted section text.
4638 * for "replace", the whole page with the section replaced.
4640 private function extractSections( $text, $section, $mode, $newText='' ) {
4642 $this->clearState();
4643 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4644 $this->mOptions
= new ParserOptions
;
4645 $this->setOutputType( self
::OT_WIKI
);
4647 $frame = $this->getPreprocessor()->newFrame();
4649 // Process section extraction flags
4651 $sectionParts = explode( '-', $section );
4652 $sectionIndex = array_pop( $sectionParts );
4653 foreach ( $sectionParts as $part ) {
4654 if ( $part === 'T' ) {
4655 $flags |
= self
::PTD_FOR_INCLUSION
;
4658 // Preprocess the text
4659 $root = $this->preprocessToDom( $text, $flags );
4661 // <h> nodes indicate section breaks
4662 // They can only occur at the top level, so we can find them by iterating the root's children
4663 $node = $root->getFirstChild();
4665 // Find the target section
4666 if ( $sectionIndex == 0 ) {
4667 // Section zero doesn't nest, level=big
4668 $targetLevel = 1000;
4671 if ( $node->getName() === 'h' ) {
4672 $bits = $node->splitHeading();
4673 if ( $bits['i'] == $sectionIndex ) {
4674 $targetLevel = $bits['level'];
4678 if ( $mode === 'replace' ) {
4679 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4681 $node = $node->getNextSibling();
4687 if ( $mode === 'get' ) {
4694 // Find the end of the section, including nested sections
4696 if ( $node->getName() === 'h' ) {
4697 $bits = $node->splitHeading();
4698 $curLevel = $bits['level'];
4699 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4703 if ( $mode === 'get' ) {
4704 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4706 $node = $node->getNextSibling();
4709 // Write out the remainder (in replace mode only)
4710 if ( $mode === 'replace' ) {
4711 // Output the replacement text
4712 // Add two newlines on -- trailing whitespace in $newText is conventionally
4713 // stripped by the editor, so we need both newlines to restore the paragraph gap
4714 // Only add trailing whitespace if there is newText
4715 if($newText != "") {
4716 $outText .= $newText . "\n\n";
4720 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4721 $node = $node->getNextSibling();
4725 if ( is_string( $outText ) ) {
4726 // Re-insert stripped tags
4727 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4734 * This function returns the text of a section, specified by a number ($section).
4735 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4736 * the first section before any such heading (section 0).
4738 * If a section contains subsections, these are also returned.
4740 * @param string $text text to look in
4741 * @param string $section section identifier
4742 * @param string $deftext default to return if section is not found
4743 * @return string text of the requested section
4745 public function getSection( $text, $section, $deftext='' ) {
4746 return $this->extractSections( $text, $section, "get", $deftext );
4749 public function replaceSection( $oldtext, $section, $text ) {
4750 return $this->extractSections( $oldtext, $section, "replace", $text );
4754 * Get the timestamp associated with the current revision, adjusted for
4755 * the default server-local timestamp
4757 function getRevisionTimestamp() {
4758 if ( is_null( $this->mRevisionTimestamp
) ) {
4759 wfProfileIn( __METHOD__
);
4761 $dbr = wfGetDB( DB_SLAVE
);
4762 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4763 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4765 // Normalize timestamp to internal MW format for timezone processing.
4766 // This has the added side-effect of replacing a null value with
4767 // the current time, which gives us more sensible behavior for
4769 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4771 // The cryptic '' timezone parameter tells to use the site-default
4772 // timezone offset instead of the user settings.
4774 // Since this value will be saved into the parser cache, served
4775 // to other users, and potentially even used inside links and such,
4776 // it needs to be consistent for all visitors.
4777 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4779 wfProfileOut( __METHOD__
);
4781 return $this->mRevisionTimestamp
;
4785 * Get the name of the user that edited the last revision
4787 function getRevisionUser() {
4788 // if this template is subst: the revision id will be blank,
4789 // so just use the current user's name
4790 if( $this->mRevisionId
) {
4791 $revision = Revision
::newFromId( $this->mRevisionId
);
4792 $revuser = $revision->getUserText();
4795 $revuser = $wgUser->getName();
4801 * Mutator for $mDefaultSort
4803 * @param $sort New value
4805 public function setDefaultSort( $sort ) {
4806 $this->mDefaultSort
= $sort;
4810 * Accessor for $mDefaultSort
4811 * Will use the title/prefixed title if none is set
4815 public function getDefaultSort() {
4816 global $wgCategoryPrefixedDefaultSortkey;
4817 if( $this->mDefaultSort
!== false ) {
4818 return $this->mDefaultSort
;
4819 } elseif ($this->mTitle
->getNamespace() == NS_CATEGORY ||
4820 !$wgCategoryPrefixedDefaultSortkey) {
4821 return $this->mTitle
->getText();
4823 return $this->mTitle
->getPrefixedText();
4828 * Accessor for $mDefaultSort
4829 * Unlike getDefaultSort(), will return false if none is set
4831 * @return string or false
4833 public function getCustomDefaultSort() {
4834 return $this->mDefaultSort
;
4838 * Try to guess the section anchor name based on a wikitext fragment
4839 * presumably extracted from a heading, for example "Header" from
4842 public function guessSectionNameFromWikiText( $text ) {
4843 # Strip out wikitext links(they break the anchor)
4844 $text = $this->stripSectionName( $text );
4845 $headline = Sanitizer
::decodeCharReferences( $text );
4847 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
4848 $headline = trim( $headline );
4849 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4850 $replacearray = array(
4855 array_keys( $replacearray ),
4856 array_values( $replacearray ),
4861 * Strips a text string of wikitext for use in a section anchor
4863 * Accepts a text string and then removes all wikitext from the
4864 * string and leaves only the resultant text (i.e. the result of
4865 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4866 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4867 * to create valid section anchors by mimicing the output of the
4868 * parser when headings are parsed.
4870 * @param $text string Text string to be stripped of wikitext
4871 * for use in a Section anchor
4872 * @return Filtered text string
4874 public function stripSectionName( $text ) {
4875 # Strip internal link markup
4876 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4877 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4879 # Strip external link markup (FIXME: Not Tolerant to blank link text
4880 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4881 # on how many empty links there are on the page - need to figure that out.
4882 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4884 # Parse wikitext quotes (italics & bold)
4885 $text = $this->doQuotes($text);
4888 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
4892 function srvus( $text ) {
4893 return $this->testSrvus( $text, $this->mOutputType
);
4897 * strip/replaceVariables/unstrip for preprocessor regression testing
4899 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
4900 $this->clearState();
4901 if ( ! ( $title instanceof Title
) ) {
4902 $title = Title
::newFromText( $title );
4904 $this->mTitle
= $title;
4905 $this->mOptions
= $options;
4906 $this->setOutputType( $outputType );
4907 $text = $this->replaceVariables( $text );
4908 $text = $this->mStripState
->unstripBoth( $text );
4909 $text = Sanitizer
::removeHTMLtags( $text );
4913 function testPst( $text, $title, $options ) {
4915 if ( ! ( $title instanceof Title
) ) {
4916 $title = Title
::newFromText( $title );
4918 return $this->preSaveTransform( $text, $title, $wgUser, $options );
4921 function testPreprocess( $text, $title, $options ) {
4922 if ( ! ( $title instanceof Title
) ) {
4923 $title = Title
::newFromText( $title );
4925 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
4928 function markerSkipCallback( $s, $callback ) {
4931 while ( $i < strlen( $s ) ) {
4932 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
4933 if ( $markerStart === false ) {
4934 $out .= call_user_func( $callback, substr( $s, $i ) );
4937 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
4938 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
4939 if ( $markerEnd === false ) {
4940 $out .= substr( $s, $markerStart );
4943 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
4944 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
4952 function serialiseHalfParsedText( $text ) {
4954 $data['text'] = $text;
4956 // First, find all strip markers, and store their
4957 // data in an array.
4958 $stripState = new StripState
;
4960 while( ( $start_pos = strpos( $text, $this->mUniqPrefix
, $pos ) ) && ( $end_pos = strpos( $text, self
::MARKER_SUFFIX
, $pos ) ) ) {
4961 $end_pos +
= strlen( self
::MARKER_SUFFIX
);
4962 $marker = substr( $text, $start_pos, $end_pos-$start_pos );
4964 if ( !empty( $this->mStripState
->general
->data
[$marker] ) ) {
4965 $replaceArray = $stripState->general
;
4966 $stripText = $this->mStripState
->general
->data
[$marker];
4967 } elseif ( !empty( $this->mStripState
->nowiki
->data
[$marker] ) ) {
4968 $replaceArray = $stripState->nowiki
;
4969 $stripText = $this->mStripState
->nowiki
->data
[$marker];
4971 throw new MWException( "Hanging strip marker: '$marker'." );
4974 $replaceArray->setPair( $marker, $stripText );
4977 $data['stripstate'] = $stripState;
4979 // Now, find all of our links, and store THEIR
4980 // data in an array! :)
4981 $links = array( 'internal' => array(), 'interwiki' => array() );
4985 while( ( $start_pos = strpos( $text, '<!--LINK ', $pos ) ) ) {
4986 list( $ns, $trail ) = explode( ':', substr( $text, $start_pos +
strlen( '<!--LINK ' ) ), 2 );
4989 if (empty( $links['internal'][$ns] )) {
4990 $links['internal'][$ns] = array();
4993 $key = trim( substr( $trail, 0, strpos( $trail, '-->' ) ) );
4994 $links['internal'][$ns][] = $this->mLinkHolders
->internals
[$ns][$key];
4995 $pos = $start_pos +
strlen( "<!--LINK $ns:$key-->" );
5001 while( ( $start_pos = strpos( $text, '<!--IWLINK ', $pos ) ) ) {
5002 $data = substr( $text, $start_pos );
5003 $key = trim( substr( $data, 0, strpos( $data, '-->' ) ) );
5004 $links['interwiki'][] = $this->mLinkHolders
->interwiki
[$key];
5005 $pos = $start_pos +
strlen( "<!--IWLINK $key-->" );
5008 $data['linkholder'] = $links;
5013 function unserialiseHalfParsedText( $data, $intPrefix = null /* Unique identifying prefix */ ) {
5015 $intPrefix = $this->getRandomString();
5017 // First, extract the strip state.
5018 $stripState = $data['stripstate'];
5019 $this->mStripState
->general
->merge( $stripState->general
);
5020 $this->mStripState
->nowiki
->merge( $stripState->nowiki
);
5022 // Now, extract the text, and renumber links
5023 $text = $data['text'];
5024 $links = $data['linkholder'];
5027 foreach( $links['internal'] as $ns => $nsLinks ) {
5028 foreach( $nsLinks as $key => $entry ) {
5029 $newKey = $intPrefix . '-' . $key;
5030 $this->mLinkHolders
->internals
[$ns][$newKey] = $entry;
5032 $text = str_replace( "<!--LINK $ns:$key-->", "<!--LINK $ns:$newKey-->", $text );
5037 foreach( $links['interwiki'] as $key => $entry ) {
5038 $newKey = "$intPrefix-$key";
5039 $this->mLinkHolders
->interwikis
[$newKey] = $entry;
5041 $text = str_replace( "<!--IWLINK $key-->", "<!--IWLINK $newKey-->", $text );
5044 // Should be good to go.
5050 * @todo document, briefly.
5054 var $general, $nowiki;
5056 function __construct() {
5057 $this->general
= new ReplacementArray
;
5058 $this->nowiki
= new ReplacementArray
;
5061 function unstripGeneral( $text ) {
5062 wfProfileIn( __METHOD__
);
5065 $text = $this->general
->replace( $text );
5066 } while ( $text !== $oldText );
5067 wfProfileOut( __METHOD__
);
5071 function unstripNoWiki( $text ) {
5072 wfProfileIn( __METHOD__
);
5075 $text = $this->nowiki
->replace( $text );
5076 } while ( $text !== $oldText );
5077 wfProfileOut( __METHOD__
);
5081 function unstripBoth( $text ) {
5082 wfProfileIn( __METHOD__
);
5085 $text = $this->general
->replace( $text );
5086 $text = $this->nowiki
->replace( $text );
5087 } while ( $text !== $oldText );
5088 wfProfileOut( __METHOD__
);
5094 * @todo document, briefly.
5097 class OnlyIncludeReplacer
{
5100 function replace( $matches ) {
5101 if ( substr( $matches[1], -1 ) === "\n" ) {
5102 $this->output
.= substr( $matches[1], 0, -1 );
5104 $this->output
.= $matches[1];