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 );
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 ) {
867 wfProfileIn( __METHOD__
);
869 # Hook to suspend the parser in this state
870 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
871 wfProfileOut( __METHOD__
);
875 $text = $this->replaceVariables( $text );
876 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
877 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
879 // Tables need to come after variable replacement for things to work
880 // properly; putting them before other transformations should keep
881 // exciting things like link expansions from showing up in surprising
883 $text = $this->doTableStuff( $text );
885 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
887 $text = $this->doDoubleUnderscore( $text );
888 $text = $this->doHeadings( $text );
889 if( $this->mOptions
->getUseDynamicDates() ) {
890 $df = DateFormatter
::getInstance();
891 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
893 $text = $this->doAllQuotes( $text );
894 $text = $this->replaceInternalLinks( $text );
895 $text = $this->replaceExternalLinks( $text );
897 # replaceInternalLinks may sometimes leave behind
898 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
899 $text = str_replace($this->mUniqPrefix
.'NOPARSE', '', $text);
901 $text = $this->doMagicLinks( $text );
902 $text = $this->formatHeadings( $text, $isMain );
904 wfProfileOut( __METHOD__
);
909 * Replace special strings like "ISBN xxx" and "RFC xxx" with
910 * magic external links.
915 function doMagicLinks( $text ) {
916 wfProfileIn( __METHOD__
);
917 $prots = $this->mUrlProtocols
;
918 $urlChar = self
::EXT_LINK_URL_CLASS
;
919 $text = preg_replace_callback(
921 (<a.*?</a>) | # m[1]: Skip link text
922 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
923 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
924 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
925 ISBN\s+(\b # m[5]: ISBN, capture number
926 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
927 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
928 [0-9Xx] # check digit
930 )!x', array( &$this, 'magicLinkCallback' ), $text );
931 wfProfileOut( __METHOD__
);
935 function magicLinkCallback( $m ) {
936 if ( isset( $m[1] ) && $m[1] !== '' ) {
939 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
942 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
944 return $this->makeFreeExternalLink( $m[0] );
945 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
947 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
951 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
953 $urlmsg = 'pubmedurl';
956 throw new MWException( __METHOD__
.': unrecognised match type "' .
957 substr($m[0], 0, 20 ) . '"' );
959 $url = wfMsg( $urlmsg, $id);
960 $sk = $this->mOptions
->getSkin();
961 $la = $sk->getExternalLinkAttributes( $url, $keyword.$id );
962 return "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
963 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
966 $num = strtr( $isbn, array(
971 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
973 $titleObj->escapeLocalUrl() .
974 "\" class=\"internal\">ISBN $isbn</a>";
981 * Make a free external link, given a user-supplied URL
985 function makeFreeExternalLink( $url ) {
987 wfProfileIn( __METHOD__
);
989 $sk = $this->mOptions
->getSkin();
992 # The characters '<' and '>' (which were escaped by
993 # removeHTMLtags()) should not be included in
994 # URLs, per RFC 2396.
996 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
997 $trail = substr($url, $m2[0][1]) . $trail;
998 $url = substr($url, 0, $m2[0][1]);
1001 # Move trailing punctuation to $trail
1003 # If there is no left bracket, then consider right brackets fair game too
1004 if ( strpos( $url, '(' ) === false ) {
1008 $numSepChars = strspn( strrev( $url ), $sep );
1009 if ( $numSepChars ) {
1010 $trail = substr( $url, -$numSepChars ) . $trail;
1011 $url = substr( $url, 0, -$numSepChars );
1014 $url = Sanitizer
::cleanUrl( $url );
1016 # Is this an external image?
1017 $text = $this->maybeMakeExternalImage( $url );
1018 if ( $text === false ) {
1019 # Not an image, make a link
1020 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1021 $this->getExternalLinkAttribs( $url ) );
1022 # Register it in the output object...
1023 # Replace unnecessary URL escape codes with their equivalent characters
1024 $pasteurized = self
::replaceUnusualEscapes( $url );
1025 $this->mOutput
->addExternalLink( $pasteurized );
1027 wfProfileOut( __METHOD__
);
1028 return $text . $trail;
1033 * Parse headers and return html
1037 function doHeadings( $text ) {
1038 wfProfileIn( __METHOD__
);
1039 for ( $i = 6; $i >= 1; --$i ) {
1040 $h = str_repeat( '=', $i );
1041 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1042 "<h$i>\\1</h$i>", $text );
1044 wfProfileOut( __METHOD__
);
1049 * Replace single quotes with HTML markup
1051 * @return string the altered text
1053 function doAllQuotes( $text ) {
1054 wfProfileIn( __METHOD__
);
1056 $lines = StringUtils
::explode( "\n", $text );
1057 foreach ( $lines as $line ) {
1058 $outtext .= $this->doQuotes( $line ) . "\n";
1060 $outtext = substr($outtext, 0,-1);
1061 wfProfileOut( __METHOD__
);
1066 * Helper function for doAllQuotes()
1068 public function doQuotes( $text ) {
1069 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1070 if ( count( $arr ) == 1 )
1074 # First, do some preliminary work. This may shift some apostrophes from
1075 # being mark-up to being text. It also counts the number of occurrences
1076 # of bold and italics mark-ups.
1080 foreach ( $arr as $r )
1082 if ( ( $i %
2 ) == 1 )
1084 # If there are ever four apostrophes, assume the first is supposed to
1085 # be text, and the remaining three constitute mark-up for bold text.
1086 if ( strlen( $arr[$i] ) == 4 )
1091 # If there are more than 5 apostrophes in a row, assume they're all
1092 # text except for the last 5.
1093 else if ( strlen( $arr[$i] ) > 5 )
1095 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1098 # Count the number of occurrences of bold and italics mark-ups.
1099 # We are not counting sequences of five apostrophes.
1100 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1101 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1102 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1107 # If there is an odd number of both bold and italics, it is likely
1108 # that one of the bold ones was meant to be an apostrophe followed
1109 # by italics. Which one we cannot know for certain, but it is more
1110 # likely to be one that has a single-letter word before it.
1111 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1114 $firstsingleletterword = -1;
1115 $firstmultiletterword = -1;
1117 foreach ( $arr as $r )
1119 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1121 $x1 = substr ($arr[$i-1], -1);
1122 $x2 = substr ($arr[$i-1], -2, 1);
1124 if ($firstspace == -1) $firstspace = $i;
1125 } else if ($x2 === ' ') {
1126 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1128 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1134 # If there is a single-letter word, use it!
1135 if ($firstsingleletterword > -1)
1137 $arr [ $firstsingleletterword ] = "''";
1138 $arr [ $firstsingleletterword-1 ] .= "'";
1140 # If not, but there's a multi-letter word, use that one.
1141 else if ($firstmultiletterword > -1)
1143 $arr [ $firstmultiletterword ] = "''";
1144 $arr [ $firstmultiletterword-1 ] .= "'";
1146 # ... otherwise use the first one that has neither.
1147 # (notice that it is possible for all three to be -1 if, for example,
1148 # there is only one pentuple-apostrophe in the line)
1149 else if ($firstspace > -1)
1151 $arr [ $firstspace ] = "''";
1152 $arr [ $firstspace-1 ] .= "'";
1156 # Now let's actually convert our apostrophic mush to HTML!
1161 foreach ($arr as $r)
1165 if ($state === 'both')
1172 if (strlen ($r) == 2)
1175 { $output .= '</i>'; $state = ''; }
1176 else if ($state === 'bi')
1177 { $output .= '</i>'; $state = 'b'; }
1178 else if ($state === 'ib')
1179 { $output .= '</b></i><b>'; $state = 'b'; }
1180 else if ($state === 'both')
1181 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1182 else # $state can be 'b' or ''
1183 { $output .= '<i>'; $state .= 'i'; }
1185 else if (strlen ($r) == 3)
1188 { $output .= '</b>'; $state = ''; }
1189 else if ($state === 'bi')
1190 { $output .= '</i></b><i>'; $state = 'i'; }
1191 else if ($state === 'ib')
1192 { $output .= '</b>'; $state = 'i'; }
1193 else if ($state === 'both')
1194 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1195 else # $state can be 'i' or ''
1196 { $output .= '<b>'; $state .= 'b'; }
1198 else if (strlen ($r) == 5)
1201 { $output .= '</b><i>'; $state = 'i'; }
1202 else if ($state === 'i')
1203 { $output .= '</i><b>'; $state = 'b'; }
1204 else if ($state === 'bi')
1205 { $output .= '</i></b>'; $state = ''; }
1206 else if ($state === 'ib')
1207 { $output .= '</b></i>'; $state = ''; }
1208 else if ($state === 'both')
1209 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1210 else # ($state == '')
1211 { $buffer = ''; $state = 'both'; }
1216 # Now close all remaining tags. Notice that the order is important.
1217 if ($state === 'b' ||
$state === 'ib')
1219 if ($state === 'i' ||
$state === 'bi' ||
$state === 'ib')
1221 if ($state === 'bi')
1223 # There might be lonely ''''', so make sure we have a buffer
1224 if ($state === 'both' && $buffer)
1225 $output .= '<b><i>'.$buffer.'</i></b>';
1231 * Replace external links (REL)
1233 * Note: this is all very hackish and the order of execution matters a lot.
1234 * Make sure to run maintenance/parserTests.php if you change this code.
1238 function replaceExternalLinks( $text ) {
1240 wfProfileIn( __METHOD__
);
1242 $sk = $this->mOptions
->getSkin();
1244 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1245 $s = array_shift( $bits );
1248 while ( $i<count( $bits ) ) {
1250 $protocol = $bits[$i++
];
1251 $text = $bits[$i++
];
1252 $trail = $bits[$i++
];
1254 # The characters '<' and '>' (which were escaped by
1255 # removeHTMLtags()) should not be included in
1256 # URLs, per RFC 2396.
1258 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1259 $text = substr($url, $m2[0][1]) . ' ' . $text;
1260 $url = substr($url, 0, $m2[0][1]);
1263 # If the link text is an image URL, replace it with an <img> tag
1264 # This happened by accident in the original parser, but some people used it extensively
1265 $img = $this->maybeMakeExternalImage( $text );
1266 if ( $img !== false ) {
1272 # Set linktype for CSS - if URL==text, link is essentially free
1273 $linktype = ($text === $url) ?
'free' : 'text';
1275 # No link text, e.g. [http://domain.tld/some.link]
1276 if ( $text == '' ) {
1277 # Autonumber if allowed. See bug #5918
1278 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1279 $langObj = $this->getFunctionLang();
1280 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1281 $linktype = 'autonumber';
1283 # Otherwise just use the URL
1284 $text = htmlspecialchars( $url );
1288 # Have link text, e.g. [http://domain.tld/some.link text]s
1290 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1293 $text = $wgContLang->markNoConversion($text);
1295 $url = Sanitizer
::cleanUrl( $url );
1297 # Use the encoded URL
1298 # This means that users can paste URLs directly into the text
1299 # Funny characters like ö aren't valid in URLs anyway
1300 # This was changed in August 2004
1301 $s .= $sk->makeExternalLink( $url, $text, false, $linktype,
1302 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1304 # Register link in the output object.
1305 # Replace unnecessary URL escape codes with the referenced character
1306 # This prevents spammers from hiding links from the filters
1307 $pasteurized = self
::replaceUnusualEscapes( $url );
1308 $this->mOutput
->addExternalLink( $pasteurized );
1311 wfProfileOut( __METHOD__
);
1316 * Get an associative array of additional HTML attributes appropriate for a
1317 * particular external link. This currently may include rel => nofollow
1318 * (depending on configuration, namespace, and the URL's domain) and/or a
1319 * target attribute (depending on configuration).
1321 * @param string $url Optional URL, to extract the domain from for rel =>
1322 * nofollow if appropriate
1323 * @return array Associative array of HTML attributes
1325 function getExternalLinkAttribs( $url = false ) {
1327 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1328 $ns = $this->mTitle
->getNamespace();
1329 if( $wgNoFollowLinks && !in_array($ns, $wgNoFollowNsExceptions) ) {
1330 $attribs['rel'] = 'nofollow';
1332 global $wgNoFollowDomainExceptions;
1333 if ( $wgNoFollowDomainExceptions ) {
1334 $bits = wfParseUrl( $url );
1335 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1336 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1337 if( substr( $bits['host'], -strlen( $domain ) )
1339 unset( $attribs['rel'] );
1346 if ( $this->mOptions
->getExternalLinkTarget() ) {
1347 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1354 * Replace unusual URL escape codes with their equivalent characters
1358 * @todo This can merge genuinely required bits in the path or query string,
1359 * breaking legit URLs. A proper fix would treat the various parts of
1360 * the URL differently; as a workaround, just use the output for
1361 * statistical records, not for actual linking/output.
1363 static function replaceUnusualEscapes( $url ) {
1364 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1365 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1369 * Callback function used in replaceUnusualEscapes().
1370 * Replaces unusual URL escape codes with their equivalent character
1374 private static function replaceUnusualEscapesCallback( $matches ) {
1375 $char = urldecode( $matches[0] );
1376 $ord = ord( $char );
1377 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1378 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1379 // No, shouldn't be escaped
1382 // Yes, leave it escaped
1388 * make an image if it's allowed, either through the global
1389 * option, through the exception, or through the on-wiki whitelist
1392 function maybeMakeExternalImage( $url ) {
1393 $sk = $this->mOptions
->getSkin();
1394 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1395 $imagesexception = !empty($imagesfrom);
1397 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1398 if( $imagesexception && is_array( $imagesfrom ) ) {
1399 $imagematch = false;
1400 foreach( $imagesfrom as $match ) {
1401 if( strpos( $url, $match ) === 0 ) {
1406 } elseif( $imagesexception ) {
1407 $imagematch = (strpos( $url, $imagesfrom ) === 0);
1409 $imagematch = false;
1411 if ( $this->mOptions
->getAllowExternalImages()
1412 ||
( $imagesexception && $imagematch ) ) {
1413 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1415 $text = $sk->makeExternalImage( $url );
1418 if( !$text && $this->mOptions
->getEnableImageWhitelist()
1419 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1420 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1421 foreach( $whitelist as $entry ) {
1422 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1423 if( strpos( $entry, '#' ) === 0 ||
$entry === '' )
1425 if( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1426 # Image matches a whitelist entry
1427 $text = $sk->makeExternalImage( $url );
1436 * Process [[ ]] wikilinks
1437 * @return processed text
1441 function replaceInternalLinks( $s ) {
1442 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1447 * Process [[ ]] wikilinks (RIL)
1448 * @return LinkHolderArray
1452 function replaceInternalLinks2( &$s ) {
1455 wfProfileIn( __METHOD__
);
1457 wfProfileIn( __METHOD__
.'-setup' );
1458 static $tc = FALSE, $e1, $e1_img;
1459 # the % is needed to support urlencoded titles as well
1461 $tc = Title
::legalChars() . '#%';
1462 # Match a link having the form [[namespace:link|alternate]]trail
1463 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1464 # Match cases where there is no "]]", which might still be images
1465 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1468 $sk = $this->mOptions
->getSkin();
1469 $holders = new LinkHolderArray( $this );
1471 #split the entire text string on occurences of [[
1472 $a = StringUtils
::explode( '[[', ' ' . $s );
1473 #get the first element (all text up to first [[), and remove the space we added
1476 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1477 $s = substr( $s, 1 );
1479 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1481 if ( $useLinkPrefixExtension ) {
1482 # Match the end of a line for a word that's not followed by whitespace,
1483 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1484 $e2 = wfMsgForContent( 'linkprefix' );
1487 if( is_null( $this->mTitle
) ) {
1488 wfProfileOut( __METHOD__
.'-setup' );
1489 wfProfileOut( __METHOD__
);
1490 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1492 $nottalk = !$this->mTitle
->isTalkPage();
1494 if ( $useLinkPrefixExtension ) {
1496 if ( preg_match( $e2, $s, $m ) ) {
1497 $first_prefix = $m[2];
1499 $first_prefix = false;
1505 if($wgContLang->hasVariants()) {
1506 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1508 $selflink = array($this->mTitle
->getPrefixedText());
1510 $useSubpages = $this->areSubpagesAllowed();
1511 wfProfileOut( __METHOD__
.'-setup' );
1513 # Loop for each link
1514 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1515 # Check for excessive memory usage
1516 if ( $holders->isBig() ) {
1518 # Do the existence check, replace the link holders and clear the array
1519 $holders->replace( $s );
1523 if ( $useLinkPrefixExtension ) {
1524 wfProfileIn( __METHOD__
.'-prefixhandling' );
1525 if ( preg_match( $e2, $s, $m ) ) {
1533 $prefix = $first_prefix;
1534 $first_prefix = false;
1536 wfProfileOut( __METHOD__
.'-prefixhandling' );
1539 $might_be_img = false;
1541 wfProfileIn( __METHOD__
."-e1" );
1542 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1544 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1545 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1546 # the real problem is with the $e1 regex
1549 # Still some problems for cases where the ] is meant to be outside punctuation,
1550 # and no image is in sight. See bug 2095.
1553 substr( $m[3], 0, 1 ) === ']' &&
1554 strpos($text, '[') !== false
1557 $text .= ']'; # so that replaceExternalLinks($text) works later
1558 $m[3] = substr( $m[3], 1 );
1560 # fix up urlencoded title texts
1561 if( strpos( $m[1], '%' ) !== false ) {
1562 # Should anchors '#' also be rejected?
1563 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1566 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1567 $might_be_img = true;
1569 if ( strpos( $m[1], '%' ) !== false ) {
1570 $m[1] = urldecode($m[1]);
1573 } else { # Invalid form; output directly
1574 $s .= $prefix . '[[' . $line ;
1575 wfProfileOut( __METHOD__
."-e1" );
1578 wfProfileOut( __METHOD__
."-e1" );
1579 wfProfileIn( __METHOD__
."-misc" );
1581 # Don't allow internal links to pages containing
1582 # PROTO: where PROTO is a valid URL protocol; these
1583 # should be external links.
1584 if (preg_match('/^\b(?:' . wfUrlProtocols() . ')/', $m[1])) {
1585 $s .= $prefix . '[[' . $line ;
1586 wfProfileOut( __METHOD__
."-misc" );
1590 # Make subpage if necessary
1591 if( $useSubpages ) {
1592 $link = $this->maybeDoSubpageLink( $m[1], $text );
1597 $noforce = (substr($m[1], 0, 1) !== ':');
1599 # Strip off leading ':'
1600 $link = substr($link, 1);
1603 wfProfileOut( __METHOD__
."-misc" );
1604 wfProfileIn( __METHOD__
."-title" );
1605 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki($link) );
1606 if( $nt === NULL ) {
1607 $s .= $prefix . '[[' . $line;
1608 wfProfileOut( __METHOD__
."-title" );
1612 $ns = $nt->getNamespace();
1613 $iw = $nt->getInterWiki();
1614 wfProfileOut( __METHOD__
."-title" );
1616 if ($might_be_img) { # if this is actually an invalid link
1617 wfProfileIn( __METHOD__
."-might_be_img" );
1618 if ($ns == NS_FILE
&& $noforce) { #but might be an image
1621 #look at the next 'line' to see if we can close it there
1623 $next_line = $a->current();
1624 if ( $next_line === false ||
$next_line === null ) {
1627 $m = explode( ']]', $next_line, 3 );
1628 if ( count( $m ) == 3 ) {
1629 # the first ]] closes the inner link, the second the image
1631 $text .= "[[{$m[0]}]]{$m[1]}";
1634 } elseif ( count( $m ) == 2 ) {
1635 #if there's exactly one ]] that's fine, we'll keep looking
1636 $text .= "[[{$m[0]}]]{$m[1]}";
1638 #if $next_line is invalid too, we need look no further
1639 $text .= '[[' . $next_line;
1644 # we couldn't find the end of this imageLink, so output it raw
1645 #but don't ignore what might be perfectly normal links in the text we've examined
1646 $holders->merge( $this->replaceInternalLinks2( $text ) );
1647 $s .= "{$prefix}[[$link|$text";
1648 # note: no $trail, because without an end, there *is* no trail
1649 wfProfileOut( __METHOD__
."-might_be_img" );
1652 } else { #it's not an image, so output it raw
1653 $s .= "{$prefix}[[$link|$text";
1654 # note: no $trail, because without an end, there *is* no trail
1655 wfProfileOut( __METHOD__
."-might_be_img" );
1658 wfProfileOut( __METHOD__
."-might_be_img" );
1661 $wasblank = ( '' == $text );
1662 if( $wasblank ) $text = $link;
1664 # Link not escaped by : , create the various objects
1668 wfProfileIn( __METHOD__
."-interwiki" );
1669 if( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1670 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1671 $s = rtrim($s . $prefix);
1672 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1673 wfProfileOut( __METHOD__
."-interwiki" );
1676 wfProfileOut( __METHOD__
."-interwiki" );
1678 if ( $ns == NS_FILE
) {
1679 wfProfileIn( __METHOD__
."-image" );
1680 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1681 # recursively parse links inside the image caption
1682 # actually, this will parse them in any other parameters, too,
1683 # but it might be hard to fix that, and it doesn't matter ATM
1684 $text = $this->replaceExternalLinks($text);
1685 $holders->merge( $this->replaceInternalLinks2( $text ) );
1687 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1688 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1690 $this->mOutput
->addImage( $nt->getDBkey() );
1691 wfProfileOut( __METHOD__
."-image" );
1696 if ( $ns == NS_CATEGORY
) {
1697 wfProfileIn( __METHOD__
."-category" );
1698 $s = rtrim($s . "\n"); # bug 87
1701 $sortkey = $this->getDefaultSort();
1705 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1706 $sortkey = str_replace( "\n", '', $sortkey );
1707 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1708 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1711 * Strip the whitespace Category links produce, see bug 87
1712 * @todo We might want to use trim($tmp, "\n") here.
1714 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1716 wfProfileOut( __METHOD__
."-category" );
1721 # Self-link checking
1722 if( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1723 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1724 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1729 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1730 # FIXME: Should do batch file existence checks, see comment below
1731 if( $ns == NS_MEDIA
) {
1732 wfProfileIn( __METHOD__
."-media" );
1733 # Give extensions a chance to select the file revision for us
1734 $skip = $time = false;
1735 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1737 $link = $sk->link( $nt );
1739 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1741 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1742 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1743 $this->mOutput
->addImage( $nt->getDBkey() );
1744 wfProfileOut( __METHOD__
."-media" );
1748 wfProfileIn( __METHOD__
."-always_known" );
1749 # Some titles, such as valid special pages or files in foreign repos, should
1750 # be shown as bluelinks even though they're not included in the page table
1752 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1753 # batch file existence checks for NS_FILE and NS_MEDIA
1754 if( $iw == '' && $nt->isAlwaysKnown() ) {
1755 $this->mOutput
->addLink( $nt );
1756 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1758 # Links will be added to the output link list after checking
1759 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1761 wfProfileOut( __METHOD__
."-always_known" );
1763 wfProfileOut( __METHOD__
);
1768 * Make a link placeholder. The text returned can be later resolved to a real link with
1769 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1770 * parsing of interwiki links, and secondly to allow all existence checks and
1771 * article length checks (for stub links) to be bundled into a single query.
1775 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1776 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1780 * Render a forced-blue link inline; protect against double expansion of
1781 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1782 * Since this little disaster has to split off the trail text to avoid
1783 * breaking URLs in the following text without breaking trails on the
1784 * wiki links, it's been made into a horrible function.
1787 * @param string $text
1788 * @param string $query
1789 * @param string $trail
1790 * @param string $prefix
1791 * @return string HTML-wikitext mix oh yuck
1793 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1794 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1795 $sk = $this->mOptions
->getSkin();
1796 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1797 return $this->armorLinks( $link ) . $trail;
1801 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1802 * going to go through further parsing steps before inline URL expansion.
1804 * Not needed quite as much as it used to be since free links are a bit
1805 * more sensible these days. But bracketed links are still an issue.
1807 * @param string more-or-less HTML
1808 * @return string less-or-more HTML with NOPARSE bits
1810 function armorLinks( $text ) {
1811 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1812 "{$this->mUniqPrefix}NOPARSE$1", $text );
1816 * Return true if subpage links should be expanded on this page.
1819 function areSubpagesAllowed() {
1820 # Some namespaces don't allow subpages
1821 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
1825 * Handle link to subpage if necessary
1826 * @param string $target the source of the link
1827 * @param string &$text the link text, modified as necessary
1828 * @return string the full name of the link
1831 function maybeDoSubpageLink($target, &$text) {
1834 # :Foobar -- override special treatment of prefix (images, language links)
1835 # /Foobar -- convert to CurrentPage/Foobar
1836 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1837 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1838 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1840 wfProfileIn( __METHOD__
);
1841 $ret = $target; # default return value is no change
1843 # Some namespaces don't allow subpages,
1844 # so only perform processing if subpages are allowed
1845 if( $this->areSubpagesAllowed() ) {
1846 $hash = strpos( $target, '#' );
1847 if( $hash !== false ) {
1848 $suffix = substr( $target, $hash );
1849 $target = substr( $target, 0, $hash );
1854 $target = trim( $target );
1855 # Look at the first character
1856 if( $target != '' && $target{0} === '/' ) {
1857 # / at end means we don't want the slash to be shown
1859 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1860 if( $trailingSlashes ) {
1861 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1863 $noslash = substr( $target, 1 );
1866 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash) . $suffix;
1867 if( '' === $text ) {
1868 $text = $target . $suffix;
1869 } # this might be changed for ugliness reasons
1871 # check for .. subpage backlinks
1873 $nodotdot = $target;
1874 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1876 $nodotdot = substr( $nodotdot, 3 );
1878 if($dotdotcount > 0) {
1879 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1880 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1881 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1882 # / at the end means don't show full path
1883 if( substr( $nodotdot, -1, 1 ) === '/' ) {
1884 $nodotdot = substr( $nodotdot, 0, -1 );
1885 if( '' === $text ) {
1886 $text = $nodotdot . $suffix;
1889 $nodotdot = trim( $nodotdot );
1890 if( $nodotdot != '' ) {
1891 $ret .= '/' . $nodotdot;
1899 wfProfileOut( __METHOD__
);
1904 * Used by doBlockLevels()
1907 /* private */ function closeParagraph() {
1909 if ( '' != $this->mLastSection
) {
1910 $result = '</' . $this->mLastSection
. ">\n";
1912 $this->mInPre
= false;
1913 $this->mLastSection
= '';
1916 # getCommon() returns the length of the longest common substring
1917 # of both arguments, starting at the beginning of both.
1919 /* private */ function getCommon( $st1, $st2 ) {
1920 $fl = strlen( $st1 );
1921 $shorter = strlen( $st2 );
1922 if ( $fl < $shorter ) { $shorter = $fl; }
1924 for ( $i = 0; $i < $shorter; ++
$i ) {
1925 if ( $st1{$i} != $st2{$i} ) { break; }
1929 # These next three functions open, continue, and close the list
1930 # element appropriate to the prefix character passed into them.
1932 /* private */ function openList( $char ) {
1933 $result = $this->closeParagraph();
1935 if ( '*' === $char ) { $result .= '<ul><li>'; }
1936 else if ( '#' === $char ) { $result .= '<ol><li>'; }
1937 else if ( ':' === $char ) { $result .= '<dl><dd>'; }
1938 else if ( ';' === $char ) {
1939 $result .= '<dl><dt>';
1940 $this->mDTopen
= true;
1942 else { $result = '<!-- ERR 1 -->'; }
1947 /* private */ function nextItem( $char ) {
1948 if ( '*' === $char ||
'#' === $char ) { return '</li><li>'; }
1949 else if ( ':' === $char ||
';' === $char ) {
1951 if ( $this->mDTopen
) { $close = '</dt>'; }
1952 if ( ';' === $char ) {
1953 $this->mDTopen
= true;
1954 return $close . '<dt>';
1956 $this->mDTopen
= false;
1957 return $close . '<dd>';
1960 return '<!-- ERR 2 -->';
1963 /* private */ function closeList( $char ) {
1964 if ( '*' === $char ) { $text = '</li></ul>'; }
1965 else if ( '#' === $char ) { $text = '</li></ol>'; }
1966 else if ( ':' === $char ) {
1967 if ( $this->mDTopen
) {
1968 $this->mDTopen
= false;
1969 $text = '</dt></dl>';
1971 $text = '</dd></dl>';
1974 else { return '<!-- ERR 3 -->'; }
1980 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
1983 * @return string the lists rendered as HTML
1985 function doBlockLevels( $text, $linestart ) {
1986 wfProfileIn( __METHOD__
);
1988 # Parsing through the text line by line. The main thing
1989 # happening here is handling of block-level elements p, pre,
1990 # and making lists from lines starting with * # : etc.
1992 $textLines = StringUtils
::explode( "\n", $text );
1994 $lastPrefix = $output = '';
1995 $this->mDTopen
= $inBlockElem = false;
1997 $paragraphStack = false;
1999 foreach ( $textLines as $oLine ) {
2001 if ( !$linestart ) {
2007 $lastPrefixLength = strlen( $lastPrefix );
2008 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2009 $preOpenMatch = preg_match('/<pre/i', $oLine );
2010 if ( !$this->mInPre
) {
2011 # Multiple prefixes may abut each other for nested lists.
2012 $prefixLength = strspn( $oLine, '*#:;' );
2013 $prefix = substr( $oLine, 0, $prefixLength );
2016 $prefix2 = str_replace( ';', ':', $prefix );
2017 $t = substr( $oLine, $prefixLength );
2018 $this->mInPre
= (bool)$preOpenMatch;
2020 # Don't interpret any other prefixes in preformatted text
2022 $prefix = $prefix2 = '';
2027 if( $prefixLength && $lastPrefix === $prefix2 ) {
2028 # Same as the last item, so no need to deal with nesting or opening stuff
2029 $output .= $this->nextItem( substr( $prefix, -1 ) );
2030 $paragraphStack = false;
2032 if ( substr( $prefix, -1 ) === ';') {
2033 # The one nasty exception: definition lists work like this:
2034 # ; title : definition text
2035 # So we check for : in the remainder text to split up the
2036 # title and definition, without b0rking links.
2038 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2040 $output .= $term . $this->nextItem( ':' );
2043 } elseif( $prefixLength ||
$lastPrefixLength ) {
2044 # Either open or close a level...
2045 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2046 $paragraphStack = false;
2048 while( $commonPrefixLength < $lastPrefixLength ) {
2049 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2050 --$lastPrefixLength;
2052 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2053 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2055 while ( $prefixLength > $commonPrefixLength ) {
2056 $char = substr( $prefix, $commonPrefixLength, 1 );
2057 $output .= $this->openList( $char );
2059 if ( ';' === $char ) {
2060 # FIXME: This is dupe of code above
2061 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2063 $output .= $term . $this->nextItem( ':' );
2066 ++
$commonPrefixLength;
2068 $lastPrefix = $prefix2;
2070 if( 0 == $prefixLength ) {
2071 wfProfileIn( __METHOD__
."-paragraph" );
2072 # No prefix (not in list)--go to paragraph mode
2073 // XXX: use a stack for nestable elements like span, table and div
2074 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2075 $closematch = preg_match(
2076 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2077 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2078 if ( $openmatch or $closematch ) {
2079 $paragraphStack = false;
2080 #Â TODO bug 5718: paragraph closed
2081 $output .= $this->closeParagraph();
2082 if ( $preOpenMatch and !$preCloseMatch ) {
2083 $this->mInPre
= true;
2085 if ( $closematch ) {
2086 $inBlockElem = false;
2088 $inBlockElem = true;
2090 } else if ( !$inBlockElem && !$this->mInPre
) {
2091 if ( ' ' == $t{0} and ( $this->mLastSection
=== 'pre' or trim($t) != '' ) ) {
2093 if ($this->mLastSection
!== 'pre') {
2094 $paragraphStack = false;
2095 $output .= $this->closeParagraph().'<pre>';
2096 $this->mLastSection
= 'pre';
2098 $t = substr( $t, 1 );
2101 if ( '' == trim($t) ) {
2102 if ( $paragraphStack ) {
2103 $output .= $paragraphStack.'<br />';
2104 $paragraphStack = false;
2105 $this->mLastSection
= 'p';
2107 if ($this->mLastSection
!== 'p' ) {
2108 $output .= $this->closeParagraph();
2109 $this->mLastSection
= '';
2110 $paragraphStack = '<p>';
2112 $paragraphStack = '</p><p>';
2116 if ( $paragraphStack ) {
2117 $output .= $paragraphStack;
2118 $paragraphStack = false;
2119 $this->mLastSection
= 'p';
2120 } else if ($this->mLastSection
!== 'p') {
2121 $output .= $this->closeParagraph().'<p>';
2122 $this->mLastSection
= 'p';
2127 wfProfileOut( __METHOD__
."-paragraph" );
2129 // somewhere above we forget to get out of pre block (bug 785)
2130 if($preCloseMatch && $this->mInPre
) {
2131 $this->mInPre
= false;
2133 if ($paragraphStack === false) {
2137 while ( $prefixLength ) {
2138 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2141 if ( '' != $this->mLastSection
) {
2142 $output .= '</' . $this->mLastSection
. '>';
2143 $this->mLastSection
= '';
2146 wfProfileOut( __METHOD__
);
2151 * Split up a string on ':', ignoring any occurences inside tags
2152 * to prevent illegal overlapping.
2153 * @param string $str the string to split
2154 * @param string &$before set to everything before the ':'
2155 * @param string &$after set to everything after the ':'
2156 * return string the position of the ':', or false if none found
2158 function findColonNoLinks($str, &$before, &$after) {
2159 wfProfileIn( __METHOD__
);
2161 $pos = strpos( $str, ':' );
2162 if( $pos === false ) {
2164 wfProfileOut( __METHOD__
);
2168 $lt = strpos( $str, '<' );
2169 if( $lt === false ||
$lt > $pos ) {
2170 // Easy; no tag nesting to worry about
2171 $before = substr( $str, 0, $pos );
2172 $after = substr( $str, $pos+
1 );
2173 wfProfileOut( __METHOD__
);
2177 // Ugly state machine to walk through avoiding tags.
2178 $state = self
::COLON_STATE_TEXT
;
2180 $len = strlen( $str );
2181 for( $i = 0; $i < $len; $i++
) {
2185 // (Using the number is a performance hack for common cases)
2186 case 0: // self::COLON_STATE_TEXT:
2189 // Could be either a <start> tag or an </end> tag
2190 $state = self
::COLON_STATE_TAGSTART
;
2195 $before = substr( $str, 0, $i );
2196 $after = substr( $str, $i +
1 );
2197 wfProfileOut( __METHOD__
);
2200 // Embedded in a tag; don't break it.
2203 // Skip ahead looking for something interesting
2204 $colon = strpos( $str, ':', $i );
2205 if( $colon === false ) {
2206 // Nothing else interesting
2207 wfProfileOut( __METHOD__
);
2210 $lt = strpos( $str, '<', $i );
2211 if( $stack === 0 ) {
2212 if( $lt === false ||
$colon < $lt ) {
2214 $before = substr( $str, 0, $colon );
2215 $after = substr( $str, $colon +
1 );
2216 wfProfileOut( __METHOD__
);
2220 if( $lt === false ) {
2221 // Nothing else interesting to find; abort!
2222 // We're nested, but there's no close tags left. Abort!
2225 // Skip ahead to next tag start
2227 $state = self
::COLON_STATE_TAGSTART
;
2230 case 1: // self::COLON_STATE_TAG:
2235 $state = self
::COLON_STATE_TEXT
;
2238 // Slash may be followed by >?
2239 $state = self
::COLON_STATE_TAGSLASH
;
2245 case 2: // self::COLON_STATE_TAGSTART:
2248 $state = self
::COLON_STATE_CLOSETAG
;
2251 $state = self
::COLON_STATE_COMMENT
;
2254 // Illegal early close? This shouldn't happen D:
2255 $state = self
::COLON_STATE_TEXT
;
2258 $state = self
::COLON_STATE_TAG
;
2261 case 3: // self::COLON_STATE_CLOSETAG:
2266 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2267 wfProfileOut( __METHOD__
);
2270 $state = self
::COLON_STATE_TEXT
;
2273 case self
::COLON_STATE_TAGSLASH
:
2275 // Yes, a self-closed tag <blah/>
2276 $state = self
::COLON_STATE_TEXT
;
2278 // Probably we're jumping the gun, and this is an attribute
2279 $state = self
::COLON_STATE_TAG
;
2282 case 5: // self::COLON_STATE_COMMENT:
2284 $state = self
::COLON_STATE_COMMENTDASH
;
2287 case self
::COLON_STATE_COMMENTDASH
:
2289 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2291 $state = self
::COLON_STATE_COMMENT
;
2294 case self
::COLON_STATE_COMMENTDASHDASH
:
2296 $state = self
::COLON_STATE_TEXT
;
2298 $state = self
::COLON_STATE_COMMENT
;
2302 throw new MWException( "State machine error in " . __METHOD__
);
2306 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2309 wfProfileOut( __METHOD__
);
2314 * Return value of a magic variable (like PAGENAME)
2318 function getVariableValue( $index ) {
2319 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2322 * Some of these require message or data lookups and can be
2323 * expensive to check many times.
2325 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2326 if ( isset( $this->mVarCache
[$index] ) ) {
2327 return $this->mVarCache
[$index];
2331 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2332 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2335 global $wgLocaltimezone;
2336 if ( isset( $wgLocaltimezone ) ) {
2337 $oldtz = getenv( 'TZ' );
2338 putenv( 'TZ='.$wgLocaltimezone );
2341 wfSuppressWarnings(); // E_STRICT system time bitching
2342 $localTimestamp = date( 'YmdHis', $ts );
2343 $localMonth = date( 'm', $ts );
2344 $localMonthName = date( 'n', $ts );
2345 $localDay = date( 'j', $ts );
2346 $localDay2 = date( 'd', $ts );
2347 $localDayOfWeek = date( 'w', $ts );
2348 $localWeek = date( 'W', $ts );
2349 $localYear = date( 'Y', $ts );
2350 $localHour = date( 'H', $ts );
2351 if ( isset( $wgLocaltimezone ) ) {
2352 putenv( 'TZ='.$oldtz );
2354 wfRestoreWarnings();
2357 case 'currentmonth':
2358 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2359 case 'currentmonthname':
2360 return $this->mVarCache
[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2361 case 'currentmonthnamegen':
2362 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2363 case 'currentmonthabbrev':
2364 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2366 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2368 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2370 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localMonth );
2371 case 'localmonthname':
2372 return $this->mVarCache
[$index] = $wgContLang->getMonthName( $localMonthName );
2373 case 'localmonthnamegen':
2374 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2375 case 'localmonthabbrev':
2376 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2378 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay );
2380 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay2 );
2382 return wfEscapeWikiText( $this->mTitle
->getText() );
2384 return $this->mTitle
->getPartialURL();
2385 case 'fullpagename':
2386 return wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2387 case 'fullpagenamee':
2388 return $this->mTitle
->getPrefixedURL();
2390 return wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2391 case 'subpagenamee':
2392 return $this->mTitle
->getSubpageUrlForm();
2393 case 'basepagename':
2394 return wfEscapeWikiText( $this->mTitle
->getBaseText() );
2395 case 'basepagenamee':
2396 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2397 case 'talkpagename':
2398 if( $this->mTitle
->canTalk() ) {
2399 $talkPage = $this->mTitle
->getTalkPage();
2400 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2404 case 'talkpagenamee':
2405 if( $this->mTitle
->canTalk() ) {
2406 $talkPage = $this->mTitle
->getTalkPage();
2407 return $talkPage->getPrefixedUrl();
2411 case 'subjectpagename':
2412 $subjPage = $this->mTitle
->getSubjectPage();
2413 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2414 case 'subjectpagenamee':
2415 $subjPage = $this->mTitle
->getSubjectPage();
2416 return $subjPage->getPrefixedUrl();
2418 // Let the edit saving system know we should parse the page
2419 // *after* a revision ID has been assigned.
2420 $this->mOutput
->setFlag( 'vary-revision' );
2421 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2422 return $this->mRevisionId
;
2424 // Let the edit saving system know we should parse the page
2425 // *after* a revision ID has been assigned. This is for null edits.
2426 $this->mOutput
->setFlag( 'vary-revision' );
2427 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2428 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2429 case 'revisionday2':
2430 // Let the edit saving system know we should parse the page
2431 // *after* a revision ID has been assigned. This is for null edits.
2432 $this->mOutput
->setFlag( 'vary-revision' );
2433 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2434 return substr( $this->getRevisionTimestamp(), 6, 2 );
2435 case 'revisionmonth':
2436 // Let the edit saving system know we should parse the page
2437 // *after* a revision ID has been assigned. This is for null edits.
2438 $this->mOutput
->setFlag( 'vary-revision' );
2439 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2440 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2441 case 'revisionyear':
2442 // Let the edit saving system know we should parse the page
2443 // *after* a revision ID has been assigned. This is for null edits.
2444 $this->mOutput
->setFlag( 'vary-revision' );
2445 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2446 return substr( $this->getRevisionTimestamp(), 0, 4 );
2447 case 'revisiontimestamp':
2448 // Let the edit saving system know we should parse the page
2449 // *after* a revision ID has been assigned. This is for null edits.
2450 $this->mOutput
->setFlag( 'vary-revision' );
2451 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2452 return $this->getRevisionTimestamp();
2454 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2456 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2458 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2460 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2461 case 'subjectspace':
2462 return $this->mTitle
->getSubjectNsText();
2463 case 'subjectspacee':
2464 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2465 case 'currentdayname':
2466 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2468 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2470 return $this->mVarCache
[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2472 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2474 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2475 // int to remove the padding
2476 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2478 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2479 case 'localdayname':
2480 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2482 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localYear, true );
2484 return $this->mVarCache
[$index] = $wgContLang->time( $localTimestamp, false, false );
2486 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localHour, true );
2488 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2489 // int to remove the padding
2490 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)$localWeek );
2492 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDayOfWeek );
2493 case 'numberofarticles':
2494 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2495 case 'numberoffiles':
2496 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::images() );
2497 case 'numberofusers':
2498 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::users() );
2499 case 'numberofactiveusers':
2500 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::activeUsers() );
2501 case 'numberofpages':
2502 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2503 case 'numberofadmins':
2504 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::numberingroup('sysop') );
2505 case 'numberofedits':
2506 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2507 case 'numberofviews':
2508 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::views() );
2509 case 'currenttimestamp':
2510 return $this->mVarCache
[$index] = wfTimestamp( TS_MW
, $ts );
2511 case 'localtimestamp':
2512 return $this->mVarCache
[$index] = $localTimestamp;
2513 case 'currentversion':
2514 return $this->mVarCache
[$index] = SpecialVersion
::getVersion();
2520 return $wgServerName;
2522 return $wgScriptPath;
2523 case 'directionmark':
2524 return $wgContLang->getDirMark();
2525 case 'contentlanguage':
2526 global $wgContLanguageCode;
2527 return $wgContLanguageCode;
2530 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret ) ) )
2538 * initialise the magic variables (like CURRENTMONTHNAME)
2542 function initialiseVariables() {
2543 wfProfileIn( __METHOD__
);
2544 $variableIDs = MagicWord
::getVariableIDs();
2546 $this->mVariables
= new MagicWordArray( $variableIDs );
2547 wfProfileOut( __METHOD__
);
2551 * Preprocess some wikitext and return the document tree.
2552 * This is the ghost of replace_variables().
2554 * @param string $text The text to parse
2555 * @param integer flags Bitwise combination of:
2556 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2557 * included. Default is to assume a direct page view.
2559 * The generated DOM tree must depend only on the input text and the flags.
2560 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2562 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2563 * change in the DOM tree for a given text, must be passed through the section identifier
2564 * in the section edit link and thus back to extractSections().
2566 * The output of this function is currently only cached in process memory, but a persistent
2567 * cache may be implemented at a later date which takes further advantage of these strict
2568 * dependency requirements.
2572 function preprocessToDom ( $text, $flags = 0 ) {
2573 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2578 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2580 public static function splitWhitespace( $s ) {
2581 $ltrimmed = ltrim( $s );
2582 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2583 $trimmed = rtrim( $ltrimmed );
2584 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2586 $w2 = substr( $ltrimmed, -$diff );
2590 return array( $w1, $trimmed, $w2 );
2594 * Replace magic variables, templates, and template arguments
2595 * with the appropriate text. Templates are substituted recursively,
2596 * taking care to avoid infinite loops.
2598 * Note that the substitution depends on value of $mOutputType:
2599 * self::OT_WIKI: only {{subst:}} templates
2600 * self::OT_PREPROCESS: templates but not extension tags
2601 * self::OT_HTML: all templates and extension tags
2603 * @param string $tex The text to transform
2604 * @param PPFrame $frame Object describing the arguments passed to the template.
2605 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2606 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2607 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2610 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2611 # Is there any text? Also, Prevent too big inclusions!
2612 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2615 wfProfileIn( __METHOD__
);
2617 if ( $frame === false ) {
2618 $frame = $this->getPreprocessor()->newFrame();
2619 } elseif ( !( $frame instanceof PPFrame
) ) {
2620 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2621 $frame = $this->getPreprocessor()->newCustomFrame($frame);
2624 $dom = $this->preprocessToDom( $text );
2625 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2626 $text = $frame->expand( $dom, $flags );
2628 wfProfileOut( __METHOD__
);
2632 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2633 static function createAssocArgs( $args ) {
2634 $assocArgs = array();
2636 foreach( $args as $arg ) {
2637 $eqpos = strpos( $arg, '=' );
2638 if ( $eqpos === false ) {
2639 $assocArgs[$index++
] = $arg;
2641 $name = trim( substr( $arg, 0, $eqpos ) );
2642 $value = trim( substr( $arg, $eqpos+
1 ) );
2643 if ( $value === false ) {
2646 if ( $name !== false ) {
2647 $assocArgs[$name] = $value;
2656 * Warn the user when a parser limitation is reached
2657 * Will warn at most once the user per limitation type
2659 * @param string $limitationType, should be one of:
2660 * 'expensive-parserfunction' (corresponding messages: 'expensive-parserfunction-warning', 'expensive-parserfunction-category')
2661 * 'post-expand-template-argument' (corresponding messages: 'post-expand-template-argument-warning', 'post-expand-template-argument-category')
2662 * 'post-expand-template-inclusion' (corresponding messages: 'post-expand-template-inclusion-warning', 'post-expand-template-inclusion-category')
2663 * @params int $current, $max When an explicit limit has been
2664 * exceeded, provide the values (optional)
2666 function limitationWarn( $limitationType, $current=null, $max=null) {
2667 $msgName = $limitationType . '-warning';
2668 //does no harm if $current and $max are present but are unnecessary for the message
2669 $warning = wfMsgExt( $msgName, array( 'parsemag', 'escape' ), $current, $max );
2670 $this->mOutput
->addWarning( $warning );
2671 $cat = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( $limitationType . '-category' ) );
2673 $this->mOutput
->addCategory( $cat->getDBkey(), $this->getDefaultSort() );
2678 * Return the text of a template, after recursively
2679 * replacing any variables or templates within the template.
2681 * @param array $piece The parts of the template
2682 * $piece['title']: the title, i.e. the part before the |
2683 * $piece['parts']: the parameter array
2684 * $piece['lineStart']: whether the brace was at the start of a line
2685 * @param PPFrame The current frame, contains template arguments
2686 * @return string the text of the template
2689 function braceSubstitution( $piece, $frame ) {
2690 global $wgContLang, $wgNonincludableNamespaces;
2691 wfProfileIn( __METHOD__
);
2692 wfProfileIn( __METHOD__
.'-setup' );
2695 $found = false; # $text has been filled
2696 $nowiki = false; # wiki markup in $text should be escaped
2697 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2698 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2699 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2700 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2702 # Title object, where $text came from
2705 # $part1 is the bit before the first |, and must contain only title characters.
2706 # Various prefixes will be stripped from it later.
2707 $titleWithSpaces = $frame->expand( $piece['title'] );
2708 $part1 = trim( $titleWithSpaces );
2711 # Original title text preserved for various purposes
2712 $originalTitle = $part1;
2714 # $args is a list of argument nodes, starting from index 0, not including $part1
2715 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2716 wfProfileOut( __METHOD__
.'-setup' );
2719 wfProfileIn( __METHOD__
.'-modifiers' );
2721 $mwSubst = MagicWord
::get( 'subst' );
2722 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2723 # One of two possibilities is true:
2724 # 1) Found SUBST but not in the PST phase
2725 # 2) Didn't find SUBST and in the PST phase
2726 # In either case, return without further processing
2727 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2734 if ( !$found && $args->getLength() == 0 ) {
2735 $id = $this->mVariables
->matchStartToEnd( $part1 );
2736 if ( $id !== false ) {
2737 $text = $this->getVariableValue( $id );
2738 if (MagicWord
::getCacheTTL($id)>-1)
2739 $this->mOutput
->mContainsOldMagic
= true;
2744 # MSG, MSGNW and RAW
2747 $mwMsgnw = MagicWord
::get( 'msgnw' );
2748 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2751 # Remove obsolete MSG:
2752 $mwMsg = MagicWord
::get( 'msg' );
2753 $mwMsg->matchStartAndRemove( $part1 );
2757 $mwRaw = MagicWord
::get( 'raw' );
2758 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2759 $forceRawInterwiki = true;
2762 wfProfileOut( __METHOD__
.'-modifiers' );
2766 wfProfileIn( __METHOD__
. '-pfunc' );
2768 $colonPos = strpos( $part1, ':' );
2769 if ( $colonPos !== false ) {
2770 # Case sensitive functions
2771 $function = substr( $part1, 0, $colonPos );
2772 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2773 $function = $this->mFunctionSynonyms
[1][$function];
2775 # Case insensitive functions
2776 $function = strtolower( $function );
2777 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2778 $function = $this->mFunctionSynonyms
[0][$function];
2784 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2785 $initialArgs = array( &$this );
2786 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2787 if ( $flags & SFH_OBJECT_ARGS
) {
2788 # Add a frame parameter, and pass the arguments as an array
2789 $allArgs = $initialArgs;
2790 $allArgs[] = $frame;
2791 for ( $i = 0; $i < $args->getLength(); $i++
) {
2792 $funcArgs[] = $args->item( $i );
2794 $allArgs[] = $funcArgs;
2796 # Convert arguments to plain text
2797 for ( $i = 0; $i < $args->getLength(); $i++
) {
2798 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2800 $allArgs = array_merge( $initialArgs, $funcArgs );
2803 # Workaround for PHP bug 35229 and similar
2804 if ( !is_callable( $callback ) ) {
2805 throw new MWException( "Tag hook for $function is not callable\n" );
2807 $result = call_user_func_array( $callback, $allArgs );
2810 $preprocessFlags = 0;
2812 if ( is_array( $result ) ) {
2813 if ( isset( $result[0] ) ) {
2815 unset( $result[0] );
2818 // Extract flags into the local scope
2819 // This allows callers to set flags such as nowiki, found, etc.
2825 $text = $this->preprocessToDom( $text, $preprocessFlags );
2830 wfProfileOut( __METHOD__
. '-pfunc' );
2833 # Finish mangling title and then check for loops.
2834 # Set $title to a Title object and $titleText to the PDBK
2837 # Split the title into page and subpage
2839 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2840 if ($subpage !== '') {
2841 $ns = $this->mTitle
->getNamespace();
2843 $title = Title
::newFromText( $part1, $ns );
2845 $titleText = $title->getPrefixedText();
2846 # Check for language variants if the template is not found
2847 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2848 $wgContLang->findVariantLink( $part1, $title, true );
2850 # Do infinite loop check
2851 if ( !$frame->loopCheck( $title ) ) {
2853 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
2854 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
2856 # Do recursion depth check
2857 $limit = $this->mOptions
->getMaxTemplateDepth();
2858 if ( $frame->depth
>= $limit ) {
2860 $text = '<span class="error">' . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit ) . '</span>';
2865 # Load from database
2866 if ( !$found && $title ) {
2867 wfProfileIn( __METHOD__
. '-loadtpl' );
2868 if ( !$title->isExternal() ) {
2869 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2870 $text = SpecialPage
::capturePath( $title );
2871 if ( is_string( $text ) ) {
2874 $this->disableCache();
2876 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2877 $found = false; //access denied
2878 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
2880 list( $text, $title ) = $this->getTemplateDom( $title );
2881 if ( $text !== false ) {
2887 # If the title is valid but undisplayable, make a link to it
2888 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2889 $text = "[[:$titleText]]";
2892 } elseif ( $title->isTrans() ) {
2893 // Interwiki transclusion
2894 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
2895 $text = $this->interwikiTransclude( $title, 'render' );
2898 $text = $this->interwikiTransclude( $title, 'raw' );
2899 // Preprocess it like a template
2900 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
2905 wfProfileOut( __METHOD__
. '-loadtpl' );
2908 # If we haven't found text to substitute by now, we're done
2909 # Recover the source wikitext and return it
2911 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2912 wfProfileOut( __METHOD__
);
2913 return array( 'object' => $text );
2916 # Expand DOM-style return values in a child frame
2917 if ( $isChildObj ) {
2918 # Clean up argument array
2919 $newFrame = $frame->newChild( $args, $title );
2922 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
2923 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
2924 # Expansion is eligible for the empty-frame cache
2925 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
2926 $text = $this->mTplExpandCache
[$titleText];
2928 $text = $newFrame->expand( $text );
2929 $this->mTplExpandCache
[$titleText] = $text;
2932 # Uncached expansion
2933 $text = $newFrame->expand( $text );
2936 if ( $isLocalObj && $nowiki ) {
2937 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
2938 $isLocalObj = false;
2941 # Replace raw HTML by a placeholder
2942 # Add a blank line preceding, to prevent it from mucking up
2943 # immediately preceding headings
2945 $text = "\n\n" . $this->insertStripItem( $text );
2947 # Escape nowiki-style return values
2948 elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2949 $text = wfEscapeWikiText( $text );
2951 # Bug 529: if the template begins with a table or block-level
2952 # element, it should be treated as beginning a new line.
2953 # This behaviour is somewhat controversial.
2954 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
2955 $text = "\n" . $text;
2958 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
2959 # Error, oversize inclusion
2960 $text = "[[$originalTitle]]" .
2961 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
2962 $this->limitationWarn( 'post-expand-template-inclusion' );
2965 if ( $isLocalObj ) {
2966 $ret = array( 'object' => $text );
2968 $ret = array( 'text' => $text );
2971 wfProfileOut( __METHOD__
);
2976 * Get the semi-parsed DOM representation of a template with a given title,
2977 * and its redirect destination title. Cached.
2979 function getTemplateDom( $title ) {
2980 $cacheTitle = $title;
2981 $titleText = $title->getPrefixedDBkey();
2983 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
2984 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
2985 $title = Title
::makeTitle( $ns, $dbk );
2986 $titleText = $title->getPrefixedDBkey();
2988 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
2989 return array( $this->mTplDomCache
[$titleText], $title );
2992 // Cache miss, go to the database
2993 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
2995 if ( $text === false ) {
2996 $this->mTplDomCache
[$titleText] = false;
2997 return array( false, $title );
3000 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3001 $this->mTplDomCache
[ $titleText ] = $dom;
3003 if (! $title->equals($cacheTitle)) {
3004 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3005 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3008 return array( $dom, $title );
3012 * Fetch the unparsed text of a template and register a reference to it.
3014 function fetchTemplateAndTitle( $title ) {
3015 $templateCb = $this->mOptions
->getTemplateCallback();
3016 $stuff = call_user_func( $templateCb, $title, $this );
3017 $text = $stuff['text'];
3018 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3019 if ( isset( $stuff['deps'] ) ) {
3020 foreach ( $stuff['deps'] as $dep ) {
3021 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3024 return array($text,$finalTitle);
3027 function fetchTemplate( $title ) {
3028 $rv = $this->fetchTemplateAndTitle($title);
3033 * Static function to get a template
3034 * Can be overridden via ParserOptions::setTemplateCallback().
3036 static function statelessFetchTemplate( $title, $parser=false ) {
3037 $text = $skip = false;
3038 $finalTitle = $title;
3041 // Loop to fetch the article, with up to 1 redirect
3042 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3043 # Give extensions a chance to select the revision instead
3044 $id = false; // Assume current
3045 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3051 'page_id' => $title->getArticleID(),
3055 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3056 $rev_id = $rev ?
$rev->getId() : 0;
3057 // If there is no current revision, there is no page
3058 if( $id === false && !$rev ) {
3059 $linkCache = LinkCache
::singleton();
3060 $linkCache->addBadLinkObj( $title );
3065 'page_id' => $title->getArticleID(),
3066 'rev_id' => $rev_id );
3069 $text = $rev->getText();
3070 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3072 $message = $wgContLang->lcfirst( $title->getText() );
3073 $text = wfMsgForContentNoTrans( $message );
3074 if( wfEmptyMsg( $message, $text ) ) {
3081 if ( $text === false ) {
3085 $finalTitle = $title;
3086 $title = Title
::newFromRedirect( $text );
3090 'finalTitle' => $finalTitle,
3095 * Transclude an interwiki link.
3097 function interwikiTransclude( $title, $action ) {
3098 global $wgEnableScaryTranscluding;
3100 if (!$wgEnableScaryTranscluding)
3101 return wfMsg('scarytranscludedisabled');
3103 $url = $title->getFullUrl( "action=$action" );
3105 if (strlen($url) > 255)
3106 return wfMsg('scarytranscludetoolong');
3107 return $this->fetchScaryTemplateMaybeFromCache($url);
3110 function fetchScaryTemplateMaybeFromCache($url) {
3111 global $wgTranscludeCacheExpiry;
3112 $dbr = wfGetDB(DB_SLAVE
);
3113 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3114 array('tc_url' => $url));
3116 $time = $obj->tc_time
;
3117 $text = $obj->tc_contents
;
3118 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3123 $text = Http
::get($url);
3125 return wfMsg('scarytranscludefailed', $url);
3127 $dbw = wfGetDB(DB_MASTER
);
3128 $dbw->replace('transcache', array('tc_url'), array(
3130 'tc_time' => time(),
3131 'tc_contents' => $text));
3137 * Triple brace replacement -- used for template arguments
3140 function argSubstitution( $piece, $frame ) {
3141 wfProfileIn( __METHOD__
);
3144 $parts = $piece['parts'];
3145 $nameWithSpaces = $frame->expand( $piece['title'] );
3146 $argName = trim( $nameWithSpaces );
3148 $text = $frame->getArgument( $argName );
3149 if ( $text === false && $parts->getLength() > 0
3153 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3156 # No match in frame, use the supplied default
3157 $object = $parts->item( 0 )->getChildren();
3159 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3160 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3161 $this->limitationWarn( 'post-expand-template-argument' );
3164 if ( $text === false && $object === false ) {
3166 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3168 if ( $error !== false ) {
3171 if ( $object !== false ) {
3172 $ret = array( 'object' => $object );
3174 $ret = array( 'text' => $text );
3177 wfProfileOut( __METHOD__
);
3182 * Return the text to be used for a given extension tag.
3183 * This is the ghost of strip().
3185 * @param array $params Associative array of parameters:
3186 * name PPNode for the tag name
3187 * attr PPNode for unparsed text where tag attributes are thought to be
3188 * attributes Optional associative array of parsed attributes
3189 * inner Contents of extension element
3190 * noClose Original text did not have a close tag
3191 * @param PPFrame $frame
3193 function extensionSubstitution( $params, $frame ) {
3194 global $wgRawHtml, $wgContLang;
3196 $name = $frame->expand( $params['name'] );
3197 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3198 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3200 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3202 if ( $this->ot
['html'] ) {
3203 $name = strtolower( $name );
3205 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3206 if ( isset( $params['attributes'] ) ) {
3207 $attributes = $attributes +
$params['attributes'];
3215 throw new MWException( '<html> extension tag encountered unexpectedly' );
3218 $content = strtr($content, array('-{' => '-{', '}-' => '}-'));
3219 $output = Xml
::escapeTagsOnly( $content );
3222 $output = $wgContLang->armourMath(
3223 MathRenderer
::renderMath( $content, $attributes ) );
3226 $output = $this->renderImageGallery( $content, $attributes );
3229 if( isset( $this->mTagHooks
[$name] ) ) {
3230 # Workaround for PHP bug 35229 and similar
3231 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3232 throw new MWException( "Tag hook for $name is not callable\n" );
3234 $output = call_user_func_array( $this->mTagHooks
[$name],
3235 array( $content, $attributes, $this ) );
3237 $output = '<span class="error">Invalid tag extension name: ' .
3238 htmlspecialchars( $name ) . '</span>';
3242 if ( is_null( $attrText ) ) {
3245 if ( isset( $params['attributes'] ) ) {
3246 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3247 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3248 htmlspecialchars( $attrValue ) . '"';
3251 if ( $content === null ) {
3252 $output = "<$name$attrText/>";
3254 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3255 $output = "<$name$attrText>$content$close";
3259 if ( $name === 'html' ||
$name === 'nowiki' ) {
3260 $this->mStripState
->nowiki
->setPair( $marker, $output );
3262 $this->mStripState
->general
->setPair( $marker, $output );
3268 * Increment an include size counter
3270 * @param string $type The type of expansion
3271 * @param integer $size The size of the text
3272 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3274 function incrementIncludeSize( $type, $size ) {
3275 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3278 $this->mIncludeSizes
[$type] +
= $size;
3284 * Increment the expensive function count
3286 * @return boolean False if the limit has been exceeded
3288 function incrementExpensiveFunctionCount() {
3289 global $wgExpensiveParserFunctionLimit;
3290 $this->mExpensiveFunctionCount++
;
3291 if($this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit) {
3298 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3299 * Fills $this->mDoubleUnderscores, returns the modified text
3301 function doDoubleUnderscore( $text ) {
3302 wfProfileIn( __METHOD__
);
3303 // The position of __TOC__ needs to be recorded
3304 $mw = MagicWord
::get( 'toc' );
3305 if( $mw->match( $text ) ) {
3306 $this->mShowToc
= true;
3307 $this->mForceTocPosition
= true;
3309 // Set a placeholder. At the end we'll fill it in with the TOC.
3310 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3312 // Only keep the first one.
3313 $text = $mw->replace( '', $text );
3316 // Now match and remove the rest of them
3317 $mwa = MagicWord
::getDoubleUnderscoreArray();
3318 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3320 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3321 $this->mOutput
->mNoGallery
= true;
3323 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3324 $this->mShowToc
= false;
3326 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3327 $this->mOutput
->setProperty( 'hiddencat', 'y' );
3329 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( 'hidden-category-category' ) );
3330 if ( $containerCategory ) {
3331 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3333 wfDebug( __METHOD__
.": [[MediaWiki:hidden-category-category]] is not a valid title!\n" );
3336 # (bug 8068) Allow control over whether robots index a page.
3338 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3339 # is not desirable, the last one on the page should win.
3340 if( isset( $this->mDoubleUnderscores
['noindex'] ) ) {
3341 $this->mOutput
->setIndexPolicy( 'noindex' );
3342 } elseif( isset( $this->mDoubleUnderscores
['index'] ) ) {
3343 $this->mOutput
->setIndexPolicy( 'index' );
3345 wfProfileOut( __METHOD__
);
3350 * This function accomplishes several tasks:
3351 * 1) Auto-number headings if that option is enabled
3352 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3353 * 3) Add a Table of contents on the top for users who have enabled the option
3354 * 4) Auto-anchor headings
3356 * It loops through all headlines, collects the necessary data, then splits up the
3357 * string and re-inserts the newly formatted headlines.
3359 * @param string $text
3360 * @param boolean $isMain
3363 function formatHeadings( $text, $isMain=true ) {
3364 global $wgMaxTocLevel, $wgContLang, $wgEnforceHtmlIds;
3366 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3367 $showEditLink = $this->mOptions
->getEditSection();
3369 // Do not call quickUserCan unless necessary
3370 if( $showEditLink && !$this->mTitle
->quickUserCan( 'edit' ) ) {
3374 # Inhibit editsection links if requested in the page
3375 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ) {
3379 # Get all headlines for numbering them and adding funky stuff like [edit]
3380 # links - this is for later, but we need the number of headlines right now
3382 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3384 # if there are fewer than 4 headlines in the article, do not show TOC
3385 # unless it's been explicitly enabled.
3386 $enoughToc = $this->mShowToc
&&
3387 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3389 # Allow user to stipulate that a page should have a "new section"
3390 # link added via __NEWSECTIONLINK__
3391 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3392 $this->mOutput
->setNewSection( true );
3395 # Allow user to remove the "new section"
3396 # link via __NONEWSECTIONLINK__
3397 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3398 $this->mOutput
->hideNewSection( true );
3401 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3402 # override above conditions and always show TOC above first header
3403 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3404 $this->mShowToc
= true;
3408 # We need this to perform operations on the HTML
3409 $sk = $this->mOptions
->getSkin();
3415 # Ugh .. the TOC should have neat indentation levels which can be
3416 # passed to the skin functions. These are determined here
3420 $sublevelCount = array();
3421 $levelCount = array();
3427 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3428 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3431 foreach( $matches[3] as $headline ) {
3432 $isTemplate = false;
3434 $sectionIndex = false;
3436 $markerMatches = array();
3437 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3438 $serial = $markerMatches[1];
3439 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3440 $isTemplate = ($titleText != $baseTitleText);
3441 $headline = preg_replace("/^$markerRegex/", "", $headline);
3445 $prevlevel = $level;
3446 $prevtoclevel = $toclevel;
3448 $level = $matches[1][$headlineCount];
3450 if( $doNumberHeadings ||
$enoughToc ) {
3452 if ( $level > $prevlevel ) {
3453 # Increase TOC level
3455 $sublevelCount[$toclevel] = 0;
3456 if( $toclevel<$wgMaxTocLevel ) {
3457 $prevtoclevel = $toclevel;
3458 $toc .= $sk->tocIndent();
3462 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3463 # Decrease TOC level, find level to jump to
3465 if ( $toclevel == 2 && $level <= $levelCount[1] ) {
3466 # Can only go down to level 1
3469 for ($i = $toclevel; $i > 0; $i--) {
3470 if ( $levelCount[$i] == $level ) {
3471 # Found last matching level
3475 elseif ( $levelCount[$i] < $level ) {
3476 # Found first matching level below current level
3482 if( $toclevel<$wgMaxTocLevel ) {
3483 if($prevtoclevel < $wgMaxTocLevel) {
3484 # Unindent only if the previous toc level was shown :p
3485 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3486 $prevtoclevel = $toclevel;
3488 $toc .= $sk->tocLineEnd();
3493 # No change in level, end TOC line
3494 if( $toclevel<$wgMaxTocLevel ) {
3495 $toc .= $sk->tocLineEnd();
3499 $levelCount[$toclevel] = $level;
3501 # count number of headlines for each level
3502 @$sublevelCount[$toclevel]++
;
3504 for( $i = 1; $i <= $toclevel; $i++
) {
3505 if( !empty( $sublevelCount[$i] ) ) {
3509 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3515 # The safe header is a version of the header text safe to use for links
3516 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3517 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3519 # Remove link placeholders by the link text.
3520 # <!--LINK number-->
3522 # link text with suffix
3523 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3525 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3526 $tocline = preg_replace(
3527 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3531 $tocline = trim( $tocline );
3533 # For the anchor, strip out HTML-y stuff period
3534 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3535 $safeHeadline = trim( $safeHeadline );
3537 # Save headline for section edit hint before it's escaped
3538 $headlineHint = $safeHeadline;
3540 if ( $wgEnforceHtmlIds ) {
3541 $legacyHeadline = false;
3542 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
3545 # For reverse compatibility, provide an id that's
3546 # HTML4-compatible, like we used to.
3548 # It may be worth noting, academically, that it's possible for
3549 # the legacy anchor to conflict with a non-legacy headline
3550 # anchor on the page. In this case likely the "correct" thing
3551 # would be to either drop the legacy anchors or make sure
3552 # they're numbered first. However, this would require people
3553 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3554 # manually, so let's not bother worrying about it.
3555 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
3557 $safeHeadline = Sanitizer
::escapeId( $safeHeadline, 'xml' );
3559 if ( $legacyHeadline == $safeHeadline ) {
3560 # No reason to have both (in fact, we can't)
3561 $legacyHeadline = false;
3562 } elseif ( $legacyHeadline != Sanitizer
::escapeId(
3563 $legacyHeadline, 'xml' ) ) {
3564 # The legacy id is invalid XML. We used to allow this, but
3565 # there's no reason to do so anymore. Backward
3566 # compatibility will fail slightly in this case, but it's
3568 $legacyHeadline = false;
3572 # HTML names must be case-insensitively unique (bug 10721). FIXME:
3573 # Does this apply to Unicode characters? Because we aren't
3574 # handling those here.
3575 $arrayKey = strtolower( $safeHeadline );
3576 if ( $legacyHeadline === false ) {
3577 $legacyArrayKey = false;
3579 $legacyArrayKey = strtolower( $legacyHeadline );
3582 # count how many in assoc. array so we can track dupes in anchors
3583 if ( isset( $refers[$arrayKey] ) ) {
3584 $refers[$arrayKey]++
;
3586 $refers[$arrayKey] = 1;
3588 if ( isset( $refers[$legacyArrayKey] ) ) {
3589 $refers[$legacyArrayKey]++
;
3591 $refers[$legacyArrayKey] = 1;
3594 # Don't number the heading if it is the only one (looks silly)
3595 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3596 # the two are different if the line contains a link
3597 $headline=$numbering . ' ' . $headline;
3600 # Create the anchor for linking from the TOC to the section
3601 $anchor = $safeHeadline;
3602 $legacyAnchor = $legacyHeadline;
3603 if ( $refers[$arrayKey] > 1 ) {
3604 $anchor .= '_' . $refers[$arrayKey];
3606 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3607 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3609 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3610 $toc .= $sk->tocLine($anchor, $tocline, $numbering, $toclevel);
3611 $tocraw[] = array( 'toclevel' => $toclevel, 'level' => $level, 'line' => $tocline, 'number' => $numbering );
3613 # give headline the correct <h#> tag
3614 if( $showEditLink && $sectionIndex !== false ) {
3616 # Put a T flag in the section identifier, to indicate to extractSections()
3617 # that sections inside <includeonly> should be counted.
3618 $editlink = $sk->doEditSectionLink(Title
::newFromText( $titleText ), "T-$sectionIndex");
3620 $editlink = $sk->doEditSectionLink($this->mTitle
, $sectionIndex, $headlineHint);
3625 $head[$headlineCount] = $sk->makeHeadline( $level,
3626 $matches['attrib'][$headlineCount], $anchor, $headline,
3627 $editlink, $legacyAnchor );
3632 $this->mOutput
->setSections( $tocraw );
3634 # Never ever show TOC if no headers
3635 if( $numVisible < 1 ) {
3640 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3641 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3643 $toc = $sk->tocList( $toc );
3646 # split up and insert constructed headlines
3648 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3651 foreach( $blocks as $block ) {
3652 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3653 # This is the [edit] link that appears for the top block of text when
3654 # section editing is enabled
3656 # Disabled because it broke block formatting
3657 # For example, a bullet point in the top line
3658 # $full .= $sk->editSectionLink(0);
3661 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3662 # Top anchor now in skin
3666 if( !empty( $head[$i] ) ) {
3671 if( $this->mForceTocPosition
) {
3672 return str_replace( '<!--MWTOC-->', $toc, $full );
3679 * Transform wiki markup when saving a page by doing \r\n -> \n
3680 * conversion, substitting signatures, {{subst:}} templates, etc.
3682 * @param string $text the text to transform
3683 * @param Title &$title the Title object for the current article
3684 * @param User &$user the User object describing the current user
3685 * @param ParserOptions $options parsing options
3686 * @param bool $clearState whether to clear the parser state first
3687 * @return string the altered wiki markup
3690 function preSaveTransform( $text, &$title, $user, $options, $clearState = true ) {
3691 $this->mOptions
= $options;
3692 $this->setTitle( $title );
3693 $this->setOutputType( self
::OT_WIKI
);
3695 if ( $clearState ) {
3696 $this->clearState();
3702 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3703 $text = $this->pstPass2( $text, $user );
3704 $text = $this->mStripState
->unstripBoth( $text );
3709 * Pre-save transform helper function
3712 function pstPass2( $text, $user ) {
3713 global $wgContLang, $wgLocaltimezone;
3715 /* Note: This is the timestamp saved as hardcoded wikitext to
3716 * the database, we use $wgContLang here in order to give
3717 * everyone the same signature and use the default one rather
3718 * than the one selected in each user's preferences.
3720 * (see also bug 12815)
3722 $ts = $this->mOptions
->getTimestamp();
3723 $tz = wfMsgForContent( 'timezone-utc' );
3724 if ( isset( $wgLocaltimezone ) ) {
3725 $unixts = wfTimestamp( TS_UNIX
, $ts );
3726 $oldtz = getenv( 'TZ' );
3727 putenv( 'TZ='.$wgLocaltimezone );
3728 $ts = date( 'YmdHis', $unixts );
3729 $tz = date( 'T', $unixts ); # might vary on DST changeover!
3731 /* Allow translation of timezones trough wiki. date() can return
3732 * whatever crap the system uses, localised or not, so we cannot
3733 * ship premade translations.
3735 $key = 'timezone-' . strtolower( trim( $tz ) );
3736 $value = wfMsgForContent( $key );
3737 if ( !wfEmptyMsg( $key, $value ) ) $tz = $value;
3739 putenv( 'TZ='.$oldtz );
3742 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tz)";
3744 # Variable replacement
3745 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3746 $text = $this->replaceVariables( $text );
3749 $sigText = $this->getUserSig( $user );
3750 $text = strtr( $text, array(
3752 '~~~~' => "$sigText $d",
3756 # Context links: [[|name]] and [[name (context)|]]
3758 global $wgLegalTitleChars;
3759 $tc = "[$wgLegalTitleChars]";
3760 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
3762 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3763 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
3764 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3765 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3767 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3768 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3769 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
3770 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3772 $t = $this->mTitle
->getText();
3774 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3775 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3776 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3777 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3779 # if there's no context, don't bother duplicating the title
3780 $text = preg_replace( $p2, '[[\\1]]', $text );
3783 # Trim trailing whitespace
3784 $text = rtrim( $text );
3790 * Fetch the user's signature text, if any, and normalize to
3791 * validated, ready-to-insert wikitext.
3797 function getUserSig( &$user ) {
3798 global $wgMaxSigChars;
3800 $username = $user->getName();
3801 $nickname = $user->getOption( 'nickname' );
3802 $nickname = $nickname === '' ?
$username : $nickname;
3804 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3805 $nickname = $username;
3806 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
3807 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3808 # Sig. might contain markup; validate this
3809 if( $this->validateSig( $nickname ) !== false ) {
3810 # Validated; clean up (if needed) and return it
3811 return $this->cleanSig( $nickname, true );
3813 # Failed to validate; fall back to the default
3814 $nickname = $username;
3815 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
3819 // Make sure nickname doesnt get a sig in a sig
3820 $nickname = $this->cleanSigInSig( $nickname );
3822 # If we're still here, make it a link to the user page
3823 $userText = wfEscapeWikiText( $username );
3824 $nickText = wfEscapeWikiText( $nickname );
3825 if ( $user->isAnon() ) {
3826 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
3828 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
3833 * Check that the user's signature contains no bad XML
3835 * @param string $text
3836 * @return mixed An expanded string, or false if invalid.
3838 function validateSig( $text ) {
3839 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
3843 * Clean up signature text
3845 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3846 * 2) Substitute all transclusions
3848 * @param string $text
3849 * @param $parsing Whether we're cleaning (preferences save) or parsing
3850 * @return string Signature text
3852 function cleanSig( $text, $parsing = false ) {
3855 $this->clearState();
3856 $this->setTitle( $wgTitle );
3857 $this->mOptions
= new ParserOptions
;
3858 $this->setOutputType
= self
::OT_PREPROCESS
;
3861 # Option to disable this feature
3862 if ( !$this->mOptions
->getCleanSignatures() ) {
3866 # FIXME: regex doesn't respect extension tags or nowiki
3867 # => Move this logic to braceSubstitution()
3868 $substWord = MagicWord
::get( 'subst' );
3869 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3870 $substText = '{{' . $substWord->getSynonym( 0 );
3872 $text = preg_replace( $substRegex, $substText, $text );
3873 $text = $this->cleanSigInSig( $text );
3874 $dom = $this->preprocessToDom( $text );
3875 $frame = $this->getPreprocessor()->newFrame();
3876 $text = $frame->expand( $dom );
3879 $text = $this->mStripState
->unstripBoth( $text );
3886 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3887 * @param string $text
3888 * @return string Signature text with /~{3,5}/ removed
3890 function cleanSigInSig( $text ) {
3891 $text = preg_replace( '/~{3,5}/', '', $text );
3896 * Set up some variables which are usually set up in parse()
3897 * so that an external function can call some class members with confidence
3900 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
3901 $this->setTitle( $title );
3902 $this->mOptions
= $options;
3903 $this->setOutputType( $outputType );
3904 if ( $clearState ) {
3905 $this->clearState();
3910 * Wrapper for preprocess()
3912 * @param string $text the text to preprocess
3913 * @param ParserOptions $options options
3917 function transformMsg( $text, $options ) {
3919 static $executing = false;
3921 # Guard against infinite recursion
3927 wfProfileIn(__METHOD__
);
3928 $text = $this->preprocess( $text, $wgTitle, $options );
3931 wfProfileOut(__METHOD__
);
3936 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
3937 * The callback should have the following form:
3938 * function myParserHook( $text, $params, &$parser ) { ... }
3940 * Transform and return $text. Use $parser for any required context, e.g. use
3941 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
3945 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
3946 * @param mixed $callback The callback function (and object) to use for the tag
3948 * @return The old value of the mTagHooks array associated with the hook
3950 function setHook( $tag, $callback ) {
3951 $tag = strtolower( $tag );
3952 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
3953 $this->mTagHooks
[$tag] = $callback;
3954 if( !in_array( $tag, $this->mStripList
) ) {
3955 $this->mStripList
[] = $tag;
3961 function setTransparentTagHook( $tag, $callback ) {
3962 $tag = strtolower( $tag );
3963 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
3964 $this->mTransparentTagHooks
[$tag] = $callback;
3970 * Remove all tag hooks
3972 function clearTagHooks() {
3973 $this->mTagHooks
= array();
3974 $this->mStripList
= $this->mDefaultStripList
;
3978 * Create a function, e.g. {{sum:1|2|3}}
3979 * The callback function should have the form:
3980 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
3982 * Or with SFH_OBJECT_ARGS:
3983 * function myParserFunction( $parser, $frame, $args ) { ... }
3985 * The callback may either return the text result of the function, or an array with the text
3986 * in element 0, and a number of flags in the other elements. The names of the flags are
3987 * specified in the keys. Valid flags are:
3988 * found The text returned is valid, stop processing the template. This
3990 * nowiki Wiki markup in the return value should be escaped
3991 * isHTML The returned text is HTML, armour it against wikitext transformation
3995 * @param string $id The magic word ID
3996 * @param mixed $callback The callback function (and object) to use
3997 * @param integer $flags a combination of the following flags:
3998 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4000 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4001 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4002 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4003 * the arguments, and to control the way they are expanded.
4005 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4006 * arguments, for instance:
4007 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4009 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4010 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4011 * working if/when this is changed.
4013 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4016 * Please read the documentation in includes/parser/Preprocessor.php for more information
4017 * about the methods available in PPFrame and PPNode.
4019 * @return The old callback function for this name, if any
4021 function setFunctionHook( $id, $callback, $flags = 0 ) {
4022 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4023 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4025 # Add to function cache
4026 $mw = MagicWord
::get( $id );
4028 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4030 $synonyms = $mw->getSynonyms();
4031 $sensitive = intval( $mw->isCaseSensitive() );
4033 foreach ( $synonyms as $syn ) {
4035 if ( !$sensitive ) {
4036 $syn = strtolower( $syn );
4039 if ( !( $flags & SFH_NO_HASH
) ) {
4042 # Remove trailing colon
4043 if ( substr( $syn, -1, 1 ) === ':' ) {
4044 $syn = substr( $syn, 0, -1 );
4046 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4052 * Get all registered function hook identifiers
4056 function getFunctionHooks() {
4057 return array_keys( $this->mFunctionHooks
);
4061 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4062 * Placeholders created in Skin::makeLinkObj()
4063 * Returns an array of link CSS classes, indexed by PDBK.
4065 function replaceLinkHolders( &$text, $options = 0 ) {
4066 return $this->mLinkHolders
->replace( $text );
4070 * Replace <!--LINK--> link placeholders with plain text of links
4071 * (not HTML-formatted).
4072 * @param string $text
4075 function replaceLinkHoldersText( $text ) {
4076 return $this->mLinkHolders
->replaceText( $text );
4080 * Tag hook handler for 'pre'.
4082 function renderPreTag( $text, $attribs ) {
4083 // Backwards-compatibility hack
4084 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4086 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4087 return Xml
::openElement( 'pre', $attribs ) .
4088 Xml
::escapeTagsOnly( $content ) .
4093 * Renders an image gallery from a text with one line per image.
4094 * text labels may be given by using |-style alternative text. E.g.
4095 * Image:one.jpg|The number "1"
4096 * Image:tree.jpg|A tree
4097 * given as text will return the HTML of a gallery with two images,
4098 * labeled 'The number "1"' and
4101 function renderImageGallery( $text, $params ) {
4102 $ig = new ImageGallery();
4103 $ig->setContextTitle( $this->mTitle
);
4104 $ig->setShowBytes( false );
4105 $ig->setShowFilename( false );
4106 $ig->setParser( $this );
4107 $ig->setHideBadImages();
4108 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4109 $ig->useSkin( $this->mOptions
->getSkin() );
4110 $ig->mRevisionId
= $this->mRevisionId
;
4112 if( isset( $params['caption'] ) ) {
4113 $caption = $params['caption'];
4114 $caption = htmlspecialchars( $caption );
4115 $caption = $this->replaceInternalLinks( $caption );
4116 $ig->setCaptionHtml( $caption );
4118 if( isset( $params['perrow'] ) ) {
4119 $ig->setPerRow( $params['perrow'] );
4121 if( isset( $params['widths'] ) ) {
4122 $ig->setWidths( $params['widths'] );
4124 if( isset( $params['heights'] ) ) {
4125 $ig->setHeights( $params['heights'] );
4128 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4130 $lines = StringUtils
::explode( "\n", $text );
4131 foreach ( $lines as $line ) {
4132 # match lines like these:
4133 # Image:someimage.jpg|This is some image
4135 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4137 if ( count( $matches ) == 0 ) {
4141 if ( strpos( $matches[0], '%' ) !== false )
4142 $matches[1] = urldecode( $matches[1] );
4143 $tp = Title
::newFromText( $matches[1]/*, NS_FILE*/ );
4145 if( is_null( $nt ) ) {
4146 # Bogus title. Ignore these so we don't bomb out later.
4149 if ( isset( $matches[3] ) ) {
4150 $label = $matches[3];
4155 $html = $this->recursiveTagParse( trim( $label ) );
4157 $ig->add( $nt, $html );
4159 # Only add real images (bug #5586)
4160 if ( $nt->getNamespace() == NS_FILE
) {
4161 $this->mOutput
->addImage( $nt->getDBkey() );
4164 return $ig->toHTML();
4167 function getImageParams( $handler ) {
4169 $handlerClass = get_class( $handler );
4173 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4174 // Initialise static lists
4175 static $internalParamNames = array(
4176 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4177 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4178 'bottom', 'text-bottom' ),
4179 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4180 'upright', 'border', 'link', 'alt' ),
4182 static $internalParamMap;
4183 if ( !$internalParamMap ) {
4184 $internalParamMap = array();
4185 foreach ( $internalParamNames as $type => $names ) {
4186 foreach ( $names as $name ) {
4187 $magicName = str_replace( '-', '_', "img_$name" );
4188 $internalParamMap[$magicName] = array( $type, $name );
4193 // Add handler params
4194 $paramMap = $internalParamMap;
4196 $handlerParamMap = $handler->getParamMap();
4197 foreach ( $handlerParamMap as $magic => $paramName ) {
4198 $paramMap[$magic] = array( 'handler', $paramName );
4201 $this->mImageParams
[$handlerClass] = $paramMap;
4202 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4204 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4208 * Parse image options text and use it to make an image
4209 * @param Title $title
4210 * @param string $options
4211 * @param LinkHolderArray $holders
4213 function makeImage( $title, $options, $holders = false ) {
4214 # Check if the options text is of the form "options|alt text"
4216 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4217 # * left no resizing, just left align. label is used for alt= only
4218 # * right same, but right aligned
4219 # * none same, but not aligned
4220 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4221 # * center center the image
4222 # * framed Keep original image size, no magnify-button.
4223 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4224 # * upright reduce width for upright images, rounded to full __0 px
4225 # * border draw a 1px border around the image
4226 # * alt Text for HTML alt attribute (defaults to empty)
4227 # vertical-align values (no % or length right now):
4237 $parts = StringUtils
::explode( "|", $options );
4238 $sk = $this->mOptions
->getSkin();
4240 # Give extensions a chance to select the file revision for us
4241 $skip = $time = $descQuery = false;
4242 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4245 return $sk->link( $title );
4249 $imagename = $title->getDBkey();
4250 if ( isset( $this->mFileCache
[$imagename][$time] ) ) {
4251 $file = $this->mFileCache
[$imagename][$time];
4253 $file = wfFindFile( $title, $time );
4254 if ( count( $this->mFileCache
) > 1000 ) {
4255 $this->mFileCache
= array();
4257 $this->mFileCache
[$imagename][$time] = $file;
4260 $handler = $file ?
$file->getHandler() : false;
4262 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4264 # Process the input parameters
4266 $params = array( 'frame' => array(), 'handler' => array(),
4267 'horizAlign' => array(), 'vertAlign' => array() );
4268 foreach( $parts as $part ) {
4269 $part = trim( $part );
4270 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4272 if( isset( $paramMap[$magicName] ) ) {
4273 list( $type, $paramName ) = $paramMap[$magicName];
4275 // Special case; width and height come in one variable together
4276 if( $type === 'handler' && $paramName === 'width' ) {
4278 # (bug 13500) In both cases (width/height and width only),
4279 # permit trailing "px" for backward compatibility.
4280 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4281 $width = intval( $m[1] );
4282 $height = intval( $m[2] );
4283 if ( $handler->validateParam( 'width', $width ) ) {
4284 $params[$type]['width'] = $width;
4287 if ( $handler->validateParam( 'height', $height ) ) {
4288 $params[$type]['height'] = $height;
4291 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4292 $width = intval( $value );
4293 if ( $handler->validateParam( 'width', $width ) ) {
4294 $params[$type]['width'] = $width;
4297 } // else no validation -- bug 13436
4299 if ( $type === 'handler' ) {
4300 # Validate handler parameter
4301 $validated = $handler->validateParam( $paramName, $value );
4303 # Validate internal parameters
4304 switch( $paramName ) {
4307 // @fixme - possibly check validity here for
4308 // manualthumb? downstream behavior seems odd with
4309 // missing manual thumbs.
4311 $value = $this->stripAltText( $value, $holders );
4314 $chars = self
::EXT_LINK_URL_CLASS
;
4315 $prots = $this->mUrlProtocols
;
4316 if ( $value === '' ) {
4317 $paramName = 'no-link';
4320 } elseif ( preg_match( "/^$prots/", $value ) ) {
4321 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4322 $paramName = 'link-url';
4323 $this->mOutput
->addExternalLink( $value );
4327 $linkTitle = Title
::newFromText( $value );
4329 $paramName = 'link-title';
4330 $value = $linkTitle;
4331 $this->mOutput
->addLink( $linkTitle );
4337 // Most other things appear to be empty or numeric...
4338 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4343 $params[$type][$paramName] = $value;
4347 if ( !$validated ) {
4352 # Process alignment parameters
4353 if ( $params['horizAlign'] ) {
4354 $params['frame']['align'] = key( $params['horizAlign'] );
4356 if ( $params['vertAlign'] ) {
4357 $params['frame']['valign'] = key( $params['vertAlign'] );
4360 $params['frame']['caption'] = $caption;
4362 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4364 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4365 # came to also set the caption, ordinary text after the image -- which
4366 # makes no sense, because that just repeats the text multiple times in
4367 # screen readers. It *also* came to set the title attribute.
4369 # Now that we have an alt attribute, we should not set the alt text to
4370 # equal the caption: that's worse than useless, it just repeats the
4371 # text. This is the framed/thumbnail case. If there's no caption, we
4372 # use the unnamed parameter for alt text as well, just for the time be-
4373 # ing, if the unnamed param is set and the alt param is not.
4375 # For the future, we need to figure out if we want to tweak this more,
4376 # e.g., introducing a title= parameter for the title; ignoring the un-
4377 # named parameter entirely for images without a caption; adding an ex-
4378 # plicit caption= parameter and preserving the old magic unnamed para-
4380 if( $caption !== '' && !isset( $params['frame']['alt'] )
4381 && !isset( $params['frame']['framed'] )
4382 && !isset( $params['frame']['thumbnail'] )
4383 && !isset( $params['frame']['manualthumb'] ) ) {
4384 $params['frame']['alt'] = $params['frame']['title'];
4387 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4389 # Linker does the rest
4390 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4392 # Give the handler a chance to modify the parser object
4394 $handler->parserTransformHook( $this, $file );
4400 protected function stripAltText( $caption, $holders ) {
4401 # Strip bad stuff out of the title (tooltip). We can't just use
4402 # replaceLinkHoldersText() here, because if this function is called
4403 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4405 $tooltip = $holders->replaceText( $caption );
4407 $tooltip = $this->replaceLinkHoldersText( $caption );
4410 # make sure there are no placeholders in thumbnail attributes
4411 # that are later expanded to html- so expand them now and
4413 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
4414 $tooltip = Sanitizer
::stripAllTags( $tooltip );
4420 * Set a flag in the output object indicating that the content is dynamic and
4421 * shouldn't be cached.
4423 function disableCache() {
4424 wfDebug( "Parser output marked as uncacheable.\n" );
4425 $this->mOutput
->mCacheTime
= -1;
4429 * Callback from the Sanitizer for expanding items found in HTML attribute
4430 * values, so they can be safely tested and escaped.
4431 * @param string $text
4432 * @param PPFrame $frame
4436 function attributeStripCallback( &$text, $frame = false ) {
4437 $text = $this->replaceVariables( $text, $frame );
4438 $text = $this->mStripState
->unstripBoth( $text );
4447 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4448 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4449 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4455 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4460 * Break wikitext input into sections, and either pull or replace
4461 * some particular section's text.
4463 * External callers should use the getSection and replaceSection methods.
4465 * @param string $text Page wikitext
4466 * @param string $section A section identifier string of the form:
4467 * <flag1> - <flag2> - ... - <section number>
4469 * Currently the only recognised flag is "T", which means the target section number
4470 * was derived during a template inclusion parse, in other words this is a template
4471 * section edit link. If no flags are given, it was an ordinary section edit link.
4472 * This flag is required to avoid a section numbering mismatch when a section is
4473 * enclosed by <includeonly> (bug 6563).
4475 * The section number 0 pulls the text before the first heading; other numbers will
4476 * pull the given section along with its lower-level subsections. If the section is
4477 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4479 * @param string $mode One of "get" or "replace"
4480 * @param string $newText Replacement text for section data.
4481 * @return string for "get", the extracted section text.
4482 * for "replace", the whole page with the section replaced.
4484 private function extractSections( $text, $section, $mode, $newText='' ) {
4486 $this->clearState();
4487 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4488 $this->mOptions
= new ParserOptions
;
4489 $this->setOutputType( self
::OT_WIKI
);
4491 $frame = $this->getPreprocessor()->newFrame();
4493 // Process section extraction flags
4495 $sectionParts = explode( '-', $section );
4496 $sectionIndex = array_pop( $sectionParts );
4497 foreach ( $sectionParts as $part ) {
4498 if ( $part === 'T' ) {
4499 $flags |
= self
::PTD_FOR_INCLUSION
;
4502 // Preprocess the text
4503 $root = $this->preprocessToDom( $text, $flags );
4505 // <h> nodes indicate section breaks
4506 // They can only occur at the top level, so we can find them by iterating the root's children
4507 $node = $root->getFirstChild();
4509 // Find the target section
4510 if ( $sectionIndex == 0 ) {
4511 // Section zero doesn't nest, level=big
4512 $targetLevel = 1000;
4515 if ( $node->getName() === 'h' ) {
4516 $bits = $node->splitHeading();
4517 if ( $bits['i'] == $sectionIndex ) {
4518 $targetLevel = $bits['level'];
4522 if ( $mode === 'replace' ) {
4523 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4525 $node = $node->getNextSibling();
4531 if ( $mode === 'get' ) {
4538 // Find the end of the section, including nested sections
4540 if ( $node->getName() === 'h' ) {
4541 $bits = $node->splitHeading();
4542 $curLevel = $bits['level'];
4543 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4547 if ( $mode === 'get' ) {
4548 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4550 $node = $node->getNextSibling();
4553 // Write out the remainder (in replace mode only)
4554 if ( $mode === 'replace' ) {
4555 // Output the replacement text
4556 // Add two newlines on -- trailing whitespace in $newText is conventionally
4557 // stripped by the editor, so we need both newlines to restore the paragraph gap
4558 // Only add trailing whitespace if there is newText
4559 if($newText != "") {
4560 $outText .= $newText . "\n\n";
4564 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4565 $node = $node->getNextSibling();
4569 if ( is_string( $outText ) ) {
4570 // Re-insert stripped tags
4571 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4578 * This function returns the text of a section, specified by a number ($section).
4579 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4580 * the first section before any such heading (section 0).
4582 * If a section contains subsections, these are also returned.
4584 * @param string $text text to look in
4585 * @param string $section section identifier
4586 * @param string $deftext default to return if section is not found
4587 * @return string text of the requested section
4589 public function getSection( $text, $section, $deftext='' ) {
4590 return $this->extractSections( $text, $section, "get", $deftext );
4593 public function replaceSection( $oldtext, $section, $text ) {
4594 return $this->extractSections( $oldtext, $section, "replace", $text );
4598 * Get the timestamp associated with the current revision, adjusted for
4599 * the default server-local timestamp
4601 function getRevisionTimestamp() {
4602 if ( is_null( $this->mRevisionTimestamp
) ) {
4603 wfProfileIn( __METHOD__
);
4605 $dbr = wfGetDB( DB_SLAVE
);
4606 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4607 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4609 // Normalize timestamp to internal MW format for timezone processing.
4610 // This has the added side-effect of replacing a null value with
4611 // the current time, which gives us more sensible behavior for
4613 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4615 // The cryptic '' timezone parameter tells to use the site-default
4616 // timezone offset instead of the user settings.
4618 // Since this value will be saved into the parser cache, served
4619 // to other users, and potentially even used inside links and such,
4620 // it needs to be consistent for all visitors.
4621 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4623 wfProfileOut( __METHOD__
);
4625 return $this->mRevisionTimestamp
;
4629 * Mutator for $mDefaultSort
4631 * @param $sort New value
4633 public function setDefaultSort( $sort ) {
4634 $this->mDefaultSort
= $sort;
4638 * Accessor for $mDefaultSort
4639 * Will use the title/prefixed title if none is set
4643 public function getDefaultSort() {
4644 global $wgCategoryPrefixedDefaultSortkey;
4645 if( $this->mDefaultSort
!== false ) {
4646 return $this->mDefaultSort
;
4647 } elseif ($this->mTitle
->getNamespace() == NS_CATEGORY ||
4648 !$wgCategoryPrefixedDefaultSortkey) {
4649 return $this->mTitle
->getText();
4651 return $this->mTitle
->getPrefixedText();
4656 * Accessor for $mDefaultSort
4657 * Unlike getDefaultSort(), will return false if none is set
4659 * @return string or false
4661 public function getCustomDefaultSort() {
4662 return $this->mDefaultSort
;
4666 * Try to guess the section anchor name based on a wikitext fragment
4667 * presumably extracted from a heading, for example "Header" from
4670 public function guessSectionNameFromWikiText( $text ) {
4671 # Strip out wikitext links(they break the anchor)
4672 $text = $this->stripSectionName( $text );
4673 $headline = Sanitizer
::decodeCharReferences( $text );
4675 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
4676 $headline = trim( $headline );
4677 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4678 $replacearray = array(
4683 array_keys( $replacearray ),
4684 array_values( $replacearray ),
4689 * Strips a text string of wikitext for use in a section anchor
4691 * Accepts a text string and then removes all wikitext from the
4692 * string and leaves only the resultant text (i.e. the result of
4693 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4694 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4695 * to create valid section anchors by mimicing the output of the
4696 * parser when headings are parsed.
4698 * @param $text string Text string to be stripped of wikitext
4699 * for use in a Section anchor
4700 * @return Filtered text string
4702 public function stripSectionName( $text ) {
4703 # Strip internal link markup
4704 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4705 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4707 # Strip external link markup (FIXME: Not Tolerant to blank link text
4708 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4709 # on how many empty links there are on the page - need to figure that out.
4710 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4712 # Parse wikitext quotes (italics & bold)
4713 $text = $this->doQuotes($text);
4716 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
4720 function srvus( $text ) {
4721 return $this->testSrvus( $text, $this->mOutputType
);
4725 * strip/replaceVariables/unstrip for preprocessor regression testing
4727 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
4728 $this->clearState();
4729 if ( ! ( $title instanceof Title
) ) {
4730 $title = Title
::newFromText( $title );
4732 $this->mTitle
= $title;
4733 $this->mOptions
= $options;
4734 $this->setOutputType( $outputType );
4735 $text = $this->replaceVariables( $text );
4736 $text = $this->mStripState
->unstripBoth( $text );
4737 $text = Sanitizer
::removeHTMLtags( $text );
4741 function testPst( $text, $title, $options ) {
4743 if ( ! ( $title instanceof Title
) ) {
4744 $title = Title
::newFromText( $title );
4746 return $this->preSaveTransform( $text, $title, $wgUser, $options );
4749 function testPreprocess( $text, $title, $options ) {
4750 if ( ! ( $title instanceof Title
) ) {
4751 $title = Title
::newFromText( $title );
4753 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
4756 function markerSkipCallback( $s, $callback ) {
4759 while ( $i < strlen( $s ) ) {
4760 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
4761 if ( $markerStart === false ) {
4762 $out .= call_user_func( $callback, substr( $s, $i ) );
4765 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
4766 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
4767 if ( $markerEnd === false ) {
4768 $out .= substr( $s, $markerStart );
4771 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
4772 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
4780 function serialiseHalfParsedText( $text ) {
4782 $data['text'] = $text;
4784 // First, find all strip markers, and store their
4785 // data in an array.
4786 $stripState = new StripState
;
4788 while( ( $start_pos = strpos( $text, $this->mUniqPrefix
, $pos ) ) && ( $end_pos = strpos( $text, self
::MARKER_SUFFIX
, $pos ) ) ) {
4789 $end_pos +
= strlen( self
::MARKER_SUFFIX
);
4790 $marker = substr( $text, $start_pos, $end_pos-$start_pos );
4792 if ( !empty( $this->mStripState
->general
->data
[$marker] ) ) {
4793 $replaceArray = $stripState->general
;
4794 $stripText = $this->mStripState
->general
->data
[$marker];
4795 } elseif ( !empty( $this->mStripState
->nowiki
->data
[$marker] ) ) {
4796 $replaceArray = $stripState->nowiki
;
4797 $stripText = $this->mStripState
->nowiki
->data
[$marker];
4799 throw new MWException( "Hanging strip marker: '$marker'." );
4802 $replaceArray->setPair( $marker, $stripText );
4805 $data['stripstate'] = $stripState;
4807 // Now, find all of our links, and store THEIR
4808 // data in an array! :)
4809 $links = array( 'internal' => array(), 'interwiki' => array() );
4813 while( ( $start_pos = strpos( $text, '<!--LINK ', $pos ) ) ) {
4814 list( $ns, $trail ) = explode( ':', substr( $text, $start_pos +
strlen( '<!--LINK ' ) ), 2 );
4817 if (empty( $links['internal'][$ns] )) {
4818 $links['internal'][$ns] = array();
4821 $key = trim( substr( $trail, 0, strpos( $trail, '-->' ) ) );
4822 $links['internal'][$ns][] = $this->mLinkHolders
->internals
[$ns][$key];
4823 $pos = $start_pos +
strlen( "<!--LINK $ns:$key-->" );
4829 while( ( $start_pos = strpos( $text, '<!--IWLINK ', $pos ) ) ) {
4830 $data = substr( $text, $start_pos );
4831 $key = trim( substr( $data, 0, strpos( $data, '-->' ) ) );
4832 $links['interwiki'][] = $this->mLinkHolders
->interwiki
[$key];
4833 $pos = $start_pos +
strlen( "<!--IWLINK $key-->" );
4836 $data['linkholder'] = $links;
4841 function unserialiseHalfParsedText( $data, $intPrefix = null /* Unique identifying prefix */ ) {
4843 $intPrefix = $this->getRandomString();
4845 // First, extract the strip state.
4846 $stripState = $data['stripstate'];
4847 $this->mStripState
->general
->merge( $stripState->general
);
4848 $this->mStripState
->nowiki
->merge( $stripState->nowiki
);
4850 // Now, extract the text, and renumber links
4851 $text = $data['text'];
4852 $links = $data['linkholder'];
4855 foreach( $links['internal'] as $ns => $nsLinks ) {
4856 foreach( $nsLinks as $key => $entry ) {
4857 $newKey = $intPrefix . '-' . $key;
4858 $this->mLinkHolders
->internals
[$ns][$newKey] = $entry;
4860 $text = str_replace( "<!--LINK $ns:$key-->", "<!--LINK $ns:$newKey-->", $text );
4865 foreach( $links['interwiki'] as $key => $entry ) {
4866 $newKey = "$intPrefix-$key";
4867 $this->mLinkHolders
->interwikis
[$newKey] = $entry;
4869 $text = str_replace( "<!--IWLINK $key-->", "<!--IWLINK $newKey-->", $text );
4872 // Should be good to go.
4878 * @todo document, briefly.
4882 var $general, $nowiki;
4884 function __construct() {
4885 $this->general
= new ReplacementArray
;
4886 $this->nowiki
= new ReplacementArray
;
4889 function unstripGeneral( $text ) {
4890 wfProfileIn( __METHOD__
);
4893 $text = $this->general
->replace( $text );
4894 } while ( $text !== $oldText );
4895 wfProfileOut( __METHOD__
);
4899 function unstripNoWiki( $text ) {
4900 wfProfileIn( __METHOD__
);
4903 $text = $this->nowiki
->replace( $text );
4904 } while ( $text !== $oldText );
4905 wfProfileOut( __METHOD__
);
4909 function unstripBoth( $text ) {
4910 wfProfileIn( __METHOD__
);
4913 $text = $this->general
->replace( $text );
4914 $text = $this->nowiki
->replace( $text );
4915 } while ( $text !== $oldText );
4916 wfProfileOut( __METHOD__
);
4922 * @todo document, briefly.
4925 class OnlyIncludeReplacer
{
4928 function replace( $matches ) {
4929 if ( substr( $matches[1], -1 ) === "\n" ) {
4930 $this->output
.= substr( $matches[1], 0, -1 );
4932 $this->output
.= $matches[1];