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,
99 # Cleared with clearState():
100 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
101 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
102 var $mLinkHolders, $mLinkID;
103 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
104 var $mTplExpandCache; // empty-frame expansion cache
105 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
106 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->mFunctionTagHooks
= array();
131 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
132 $this->mDefaultStripList
= $this->mStripList
= array( 'nowiki', 'gallery' );
133 $this->mUrlProtocols
= wfUrlProtocols();
134 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
135 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
136 $this->mVarCache
= array();
137 if ( isset( $conf['preprocessorClass'] ) ) {
138 $this->mPreprocessorClass
= $conf['preprocessorClass'];
139 } elseif ( extension_loaded( 'domxml' ) ) {
140 // PECL extension that conflicts with the core DOM extension (bug 13770)
141 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
142 $this->mPreprocessorClass
= 'Preprocessor_Hash';
143 } elseif ( extension_loaded( 'dom' ) ) {
144 $this->mPreprocessorClass
= 'Preprocessor_DOM';
146 $this->mPreprocessorClass
= 'Preprocessor_Hash';
148 $this->mMarkerIndex
= 0;
149 $this->mFirstCall
= true;
153 * Reduce memory usage to reduce the impact of circular references
155 function __destruct() {
156 if ( isset( $this->mLinkHolders
) ) {
157 $this->mLinkHolders
->__destruct();
159 foreach ( $this as $name => $value ) {
160 unset( $this->$name );
165 * Do various kinds of initialisation on the first call of the parser
167 function firstCallInit() {
168 if ( !$this->mFirstCall
) {
171 $this->mFirstCall
= false;
173 wfProfileIn( __METHOD__
);
175 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
176 CoreParserFunctions
::register( $this );
177 $this->initialiseVariables();
179 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
180 wfProfileOut( __METHOD__
);
188 function clearState() {
189 wfProfileIn( __METHOD__
);
190 if ( $this->mFirstCall
) {
191 $this->firstCallInit();
193 $this->mOutput
= new ParserOutput
;
194 $this->mAutonumber
= 0;
195 $this->mLastSection
= '';
196 $this->mDTopen
= false;
197 $this->mIncludeCount
= array();
198 $this->mStripState
= new StripState
;
199 $this->mArgStack
= false;
200 $this->mInPre
= false;
201 $this->mLinkHolders
= new LinkHolderArray( $this );
203 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
206 * Prefix for temporary replacement strings for the multipass parser.
207 * \x07 should never appear in input as it's disallowed in XML.
208 * Using it at the front also gives us a little extra robustness
209 * since it shouldn't match when butted up against identifier-like
212 * Must not consist of all title characters, or else it will change
213 * the behaviour of <nowiki> in a link.
215 #$this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
216 # Changed to \x7f to allow XML double-parsing -- TS
217 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
220 # Clear these on every parse, bug 4549
221 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
223 $this->mShowToc
= true;
224 $this->mForceTocPosition
= false;
225 $this->mIncludeSizes
= array(
229 $this->mPPNodeCount
= 0;
230 $this->mDefaultSort
= false;
231 $this->mHeadings
= array();
232 $this->mDoubleUnderscores
= array();
233 $this->mExpensiveFunctionCount
= 0;
236 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
237 $this->mPreprocessor
= null;
240 wfRunHooks( 'ParserClearState', array( &$this ) );
241 wfProfileOut( __METHOD__
);
244 function setOutputType( $ot ) {
245 $this->mOutputType
= $ot;
248 'html' => $ot == self
::OT_HTML
,
249 'wiki' => $ot == self
::OT_WIKI
,
250 'pre' => $ot == self
::OT_PREPROCESS
,
255 * Set the context title
257 function setTitle( $t ) {
258 if ( !$t ||
$t instanceof FakeTitle
) {
259 $t = Title
::newFromText( 'NO TITLE' );
261 if ( strval( $t->getFragment() ) !== '' ) {
262 # Strip the fragment to avoid various odd effects
263 $this->mTitle
= clone $t;
264 $this->mTitle
->setFragment( '' );
271 * Accessor for mUniqPrefix.
275 function uniqPrefix() {
276 if( !isset( $this->mUniqPrefix
) ) {
277 // @fixme this is probably *horribly wrong*
278 // LanguageConverter seems to want $wgParser's uniqPrefix, however
279 // if this is called for a parser cache hit, the parser may not
280 // have ever been initialized in the first place.
281 // Not really sure what the heck is supposed to be going on here.
283 //throw new MWException( "Accessing uninitialized mUniqPrefix" );
285 return $this->mUniqPrefix
;
289 * Convert wikitext to HTML
290 * Do not call this function recursively.
292 * @param $text String: text we want to parse
293 * @param $title A title object
294 * @param $options ParserOptions
295 * @param $linestart boolean
296 * @param $clearState boolean
297 * @param $revid Int: number to pass in {{REVISIONID}}
298 * @return ParserOutput a ParserOutput
300 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
302 * First pass--just handle <nowiki> sections, pass the rest off
303 * to internalParse() which does all the real work.
306 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
307 $fname = __METHOD__
.'-' . wfGetCaller();
308 wfProfileIn( __METHOD__
);
309 wfProfileIn( $fname );
315 $this->mOptions
= $options;
316 $this->setTitle( $title );
317 $oldRevisionId = $this->mRevisionId
;
318 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
319 if( $revid !== null ) {
320 $this->mRevisionId
= $revid;
321 $this->mRevisionTimestamp
= null;
323 $this->setOutputType( self
::OT_HTML
);
324 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
326 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
327 $text = $this->internalParse( $text );
328 $text = $this->mStripState
->unstripGeneral( $text );
330 # Clean up special characters, only run once, next-to-last before doBlockLevels
332 # french spaces, last one Guillemet-left
333 # only if there is something before the space
334 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
335 # french spaces, Guillemet-right
336 '/(\\302\\253) /' => '\\1 ',
337 '/ (!\s*important)/' => ' \\1', #Beware of CSS magic word !important, bug #11874.
339 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
341 $text = $this->doBlockLevels( $text, $linestart );
343 $this->replaceLinkHolders( $text );
345 # the position of the parserConvert() call should not be changed. it
346 # assumes that the links are all replaced and the only thing left
347 # is the <nowiki> mark.
348 # Side-effects: this calls $this->mOutput->setTitleText()
349 $text = $wgContLang->parserConvert( $text, $this );
351 $text = $this->mStripState
->unstripNoWiki( $text );
353 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
355 //!JF Move to its own function
357 $uniq_prefix = $this->mUniqPrefix
;
359 $elements = array_keys( $this->mTransparentTagHooks
);
360 $text = self
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
362 foreach( $matches as $marker => $data ) {
363 list( $element, $content, $params, $tag ) = $data;
364 $tagName = strtolower( $element );
365 if( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
366 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName],
367 array( $content, $params, $this ) );
371 $this->mStripState
->general
->setPair( $marker, $output );
373 $text = $this->mStripState
->unstripGeneral( $text );
375 $text = Sanitizer
::normalizeCharReferences( $text );
377 if ( ( $wgUseTidy && $this->mOptions
->mTidy
) ||
$wgAlwaysUseTidy ) {
378 $text = MWTidy
::tidy( $text );
380 # attempt to sanitize at least some nesting problems
381 # (bug #2702 and quite a few others)
383 # ''Something [http://www.cool.com cool''] -->
384 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
385 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
386 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
387 # fix up an anchor inside another anchor, only
388 # at least for a single single nested link (bug 3695)
389 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
390 '\\1\\2</a>\\3</a>\\1\\4</a>',
391 # fix div inside inline elements- doBlockLevels won't wrap a line which
392 # contains a div, so fix it up here; replace
393 # div with escaped text
394 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
395 '\\1\\3<div\\5>\\6</div>\\8\\9',
396 # remove empty italic or bold tag pairs, some
397 # introduced by rules above
398 '/<([bi])><\/\\1>/' => '',
401 $text = preg_replace(
402 array_keys( $tidyregs ),
403 array_values( $tidyregs ),
406 global $wgExpensiveParserFunctionLimit;
407 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
408 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
411 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
413 # Information on include size limits, for the benefit of users who try to skirt them
414 if ( $this->mOptions
->getEnableLimitReport() ) {
415 global $wgExpensiveParserFunctionLimit;
416 $max = $this->mOptions
->getMaxIncludeSize();
417 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
419 "NewPP limit report\n" .
420 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
421 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
422 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
424 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
425 $text .= "\n<!-- \n$limitReport-->\n";
427 $this->mOutput
->setText( $text );
428 $this->mRevisionId
= $oldRevisionId;
429 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
430 wfProfileOut( $fname );
431 wfProfileOut( __METHOD__
);
433 return $this->mOutput
;
437 * Recursive parser entry point that can be called from an extension tag
440 function recursiveTagParse( $text ) {
441 wfProfileIn( __METHOD__
);
442 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
443 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
444 $text = $this->internalParse( $text, false );
445 wfProfileOut( __METHOD__
);
450 * Expand templates and variables in the text, producing valid, static wikitext.
451 * Also removes comments.
453 function preprocess( $text, $title, $options, $revid = null ) {
454 wfProfileIn( __METHOD__
);
456 $this->setOutputType( self
::OT_PREPROCESS
);
457 $this->mOptions
= $options;
458 $this->setTitle( $title );
459 if( $revid !== null ) {
460 $this->mRevisionId
= $revid;
462 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
463 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
464 $text = $this->replaceVariables( $text );
465 $text = $this->mStripState
->unstripBoth( $text );
466 wfProfileOut( __METHOD__
);
471 * Get a random string
476 function getRandomString() {
477 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
480 function &getTitle() { return $this->mTitle
; }
481 function getOptions() { return $this->mOptions
; }
482 function getRevisionId() { return $this->mRevisionId
; }
483 function getOutput() { return $this->mOutput
; }
484 function nextLinkID() { return $this->mLinkID++
; }
486 function getFunctionLang() {
487 global $wgLang, $wgContLang;
489 $target = $this->mOptions
->getTargetLanguage();
490 if ( $target !== null ) {
493 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
498 * Get a preprocessor object
500 function getPreprocessor() {
501 if ( !isset( $this->mPreprocessor
) ) {
502 $class = $this->mPreprocessorClass
;
503 $this->mPreprocessor
= new $class( $this );
505 return $this->mPreprocessor
;
509 * Replaces all occurrences of HTML-style comments and the given tags
510 * in the text with a random marker and returns the next text. The output
511 * parameter $matches will be an associative array filled with data in
513 * 'UNIQ-xxxxx' => array(
516 * array( 'param' => 'x' ),
517 * '<element param="x">tag content</element>' ) )
519 * @param $elements list of element names. Comments are always extracted.
520 * @param $text Source text string.
521 * @param $uniq_prefix
526 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
531 $taglist = implode( '|', $elements );
532 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
534 while ( '' != $text ) {
535 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
537 if( count( $p ) < 5 ) {
540 if( count( $p ) > 5 ) {
554 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . self
::MARKER_SUFFIX
;
555 $stripped .= $marker;
557 if ( $close === '/>' ) {
558 // Empty element tag, <tag />
563 if( $element === '!--' ) {
566 $end = "/(<\\/$element\\s*>)/i";
568 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
570 if( count( $q ) < 3 ) {
571 # No end tag -- let it run out to the end of the text.
580 $matches[$marker] = array( $element,
582 Sanitizer
::decodeTagAttributes( $attributes ),
583 "<$element$attributes$close$content$tail" );
589 * Get a list of strippable XML-like elements
591 function getStripList() {
593 $elements = $this->mStripList
;
595 $elements[] = 'html';
597 if( $this->mOptions
->getUseTeX() ) {
598 $elements[] = 'math';
604 * @deprecated use replaceVariables
606 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
611 * Restores pre, math, and other extensions removed by strip()
613 * always call unstripNoWiki() after this one
615 * @deprecated use $this->mStripState->unstrip()
617 function unstrip( $text, $state ) {
618 return $state->unstripGeneral( $text );
622 * Always call this after unstrip() to preserve the order
625 * @deprecated use $this->mStripState->unstrip()
627 function unstripNoWiki( $text, $state ) {
628 return $state->unstripNoWiki( $text );
632 * @deprecated use $this->mStripState->unstripBoth()
634 function unstripForHTML( $text ) {
635 return $this->mStripState
->unstripBoth( $text );
639 * Add an item to the strip state
640 * Returns the unique tag which must be inserted into the stripped text
641 * The tag will be replaced with the original text in unstrip()
645 function insertStripItem( $text ) {
646 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
647 $this->mMarkerIndex++
;
648 $this->mStripState
->general
->setPair( $rnd, $text );
653 * Interface with html tidy
654 * @deprecated Use MWTidy::tidy()
656 public static function tidy( $text ) {
657 wfDeprecated( __METHOD__
);
658 return MWTidy
::tidy( $text );
662 * parse the wiki syntax used to render tables
666 function doTableStuff ( $text ) {
667 wfProfileIn( __METHOD__
);
669 $lines = StringUtils
::explode( "\n", $text );
671 $td_history = array (); // Is currently a td tag open?
672 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
673 $tr_history = array (); // Is currently a tr tag open?
674 $tr_attributes = array (); // history of tr attributes
675 $has_opened_tr = array(); // Did this table open a <tr> element?
676 $indent_level = 0; // indent level of the table
678 foreach ( $lines as $outLine ) {
679 $line = trim( $outLine );
681 if( $line == '' ) { // empty line, go to next line
682 $out .= $outLine."\n";
685 $first_character = $line[0];
688 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
689 // First check if we are starting a new table
690 $indent_level = strlen( $matches[1] );
692 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
693 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
695 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
696 array_push ( $td_history , false );
697 array_push ( $last_tag_history , '' );
698 array_push ( $tr_history , false );
699 array_push ( $tr_attributes , '' );
700 array_push ( $has_opened_tr , false );
701 } else if ( count ( $td_history ) == 0 ) {
702 // Don't do any of the following
703 $out .= $outLine."\n";
705 } else if ( substr ( $line , 0 , 2 ) === '|}' ) {
706 // We are ending a table
707 $line = '</table>' . substr ( $line , 2 );
708 $last_tag = array_pop ( $last_tag_history );
710 if ( !array_pop ( $has_opened_tr ) ) {
711 $line = "<tr><td></td></tr>{$line}";
714 if ( array_pop ( $tr_history ) ) {
715 $line = "</tr>{$line}";
718 if ( array_pop ( $td_history ) ) {
719 $line = "</{$last_tag}>{$line}";
721 array_pop ( $tr_attributes );
722 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
723 } else if ( substr ( $line , 0 , 2 ) === '|-' ) {
724 // Now we have a table row
725 $line = preg_replace( '#^\|-+#', '', $line );
727 // Whats after the tag is now only attributes
728 $attributes = $this->mStripState
->unstripBoth( $line );
729 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
730 array_pop ( $tr_attributes );
731 array_push ( $tr_attributes , $attributes );
734 $last_tag = array_pop ( $last_tag_history );
735 array_pop ( $has_opened_tr );
736 array_push ( $has_opened_tr , true );
738 if ( array_pop ( $tr_history ) ) {
742 if ( array_pop ( $td_history ) ) {
743 $line = "</{$last_tag}>{$line}";
747 array_push ( $tr_history , false );
748 array_push ( $td_history , false );
749 array_push ( $last_tag_history , '' );
751 else if ( $first_character === '|' ||
$first_character === '!' ||
substr ( $line , 0 , 2 ) === '|+' ) {
752 // This might be cell elements, td, th or captions
753 if ( substr ( $line , 0 , 2 ) === '|+' ) {
754 $first_character = '+';
755 $line = substr ( $line , 1 );
758 $line = substr ( $line , 1 );
760 if ( $first_character === '!' ) {
761 $line = str_replace ( '!!' , '||' , $line );
764 // Split up multiple cells on the same line.
765 // FIXME : This can result in improper nesting of tags processed
766 // by earlier parser steps, but should avoid splitting up eg
767 // attribute values containing literal "||".
768 $cells = StringUtils
::explodeMarkup( '||' , $line );
772 // Loop through each table cell
773 foreach ( $cells as $cell )
776 if ( $first_character !== '+' )
778 $tr_after = array_pop ( $tr_attributes );
779 if ( !array_pop ( $tr_history ) ) {
780 $previous = "<tr{$tr_after}>\n";
782 array_push ( $tr_history , true );
783 array_push ( $tr_attributes , '' );
784 array_pop ( $has_opened_tr );
785 array_push ( $has_opened_tr , true );
788 $last_tag = array_pop ( $last_tag_history );
790 if ( array_pop ( $td_history ) ) {
791 $previous = "</{$last_tag}>{$previous}";
794 if ( $first_character === '|' ) {
796 } else if ( $first_character === '!' ) {
798 } else if ( $first_character === '+' ) {
799 $last_tag = 'caption';
804 array_push ( $last_tag_history , $last_tag );
806 // A cell could contain both parameters and data
807 $cell_data = explode ( '|' , $cell , 2 );
809 // Bug 553: Note that a '|' inside an invalid link should not
810 // be mistaken as delimiting cell parameters
811 if ( strpos( $cell_data[0], '[[' ) !== false ) {
812 $cell = "{$previous}<{$last_tag}>{$cell}";
813 } else if ( count ( $cell_data ) == 1 )
814 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
816 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
817 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
818 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
822 array_push ( $td_history , true );
825 $out .= $outLine . "\n";
828 // Closing open td, tr && table
829 while ( count ( $td_history ) > 0 )
831 if ( array_pop ( $td_history ) ) {
834 if ( array_pop ( $tr_history ) ) {
837 if ( !array_pop ( $has_opened_tr ) ) {
838 $out .= "<tr><td></td></tr>\n" ;
841 $out .= "</table>\n";
844 // Remove trailing line-ending (b/c)
845 if ( substr( $out, -1 ) === "\n" ) {
846 $out = substr( $out, 0, -1 );
849 // special case: don't return empty table
850 if( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
854 wfProfileOut( __METHOD__
);
860 * Helper function for parse() that transforms wiki markup into
861 * HTML. Only called for $mOutputType == self::OT_HTML.
865 function internalParse( $text, $isMain = true ) {
866 wfProfileIn( __METHOD__
);
870 # Hook to suspend the parser in this state
871 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
872 wfProfileOut( __METHOD__
);
876 $text = $this->replaceVariables( $text );
877 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
878 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
880 // Tables need to come after variable replacement for things to work
881 // properly; putting them before other transformations should keep
882 // exciting things like link expansions from showing up in surprising
884 $text = $this->doTableStuff( $text );
886 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
888 $text = $this->doDoubleUnderscore( $text );
889 $text = $this->doHeadings( $text );
890 if( $this->mOptions
->getUseDynamicDates() ) {
891 $df = DateFormatter
::getInstance();
892 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
894 $text = $this->doAllQuotes( $text );
895 $text = $this->replaceInternalLinks( $text );
896 $text = $this->replaceExternalLinks( $text );
898 # replaceInternalLinks may sometimes leave behind
899 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
900 $text = str_replace($this->mUniqPrefix
.'NOPARSE', '', $text);
902 $text = $this->doMagicLinks( $text );
903 $text = $this->formatHeadings( $text, $origText, $isMain );
905 wfProfileOut( __METHOD__
);
910 * Replace special strings like "ISBN xxx" and "RFC xxx" with
911 * magic external links.
916 function doMagicLinks( $text ) {
917 wfProfileIn( __METHOD__
);
918 $prots = $this->mUrlProtocols
;
919 $urlChar = self
::EXT_LINK_URL_CLASS
;
920 $text = preg_replace_callback(
922 (<a.*?</a>) | # m[1]: Skip link text
923 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
924 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
925 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
926 ISBN\s+(\b # m[5]: ISBN, capture number
927 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
928 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
929 [0-9Xx] # check digit
931 )!x', array( &$this, 'magicLinkCallback' ), $text );
932 wfProfileOut( __METHOD__
);
936 function magicLinkCallback( $m ) {
937 if ( isset( $m[1] ) && $m[1] !== '' ) {
940 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
943 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
945 return $this->makeFreeExternalLink( $m[0] );
946 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
949 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
952 $CssClass = 'mw-magiclink-rfc';
954 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
956 $urlmsg = 'pubmedurl';
957 $CssClass = 'mw-magiclink-pmid';
960 throw new MWException( __METHOD__
.': unrecognised match type "' .
961 substr($m[0], 0, 20 ) . '"' );
963 $url = wfMsg( $urlmsg, $id);
964 $sk = $this->mOptions
->getSkin();
965 $la = $sk->getExternalLinkAttributes( "external $CssClass" );
966 return "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
967 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
970 $num = strtr( $isbn, array(
975 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
977 $titleObj->escapeLocalUrl() .
978 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
985 * Make a free external link, given a user-supplied URL
989 function makeFreeExternalLink( $url ) {
991 wfProfileIn( __METHOD__
);
993 $sk = $this->mOptions
->getSkin();
996 # The characters '<' and '>' (which were escaped by
997 # removeHTMLtags()) should not be included in
998 # URLs, per RFC 2396.
1000 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1001 $trail = substr($url, $m2[0][1]) . $trail;
1002 $url = substr($url, 0, $m2[0][1]);
1005 # Move trailing punctuation to $trail
1007 # If there is no left bracket, then consider right brackets fair game too
1008 if ( strpos( $url, '(' ) === false ) {
1012 $numSepChars = strspn( strrev( $url ), $sep );
1013 if ( $numSepChars ) {
1014 $trail = substr( $url, -$numSepChars ) . $trail;
1015 $url = substr( $url, 0, -$numSepChars );
1018 $url = Sanitizer
::cleanUrl( $url );
1020 # Is this an external image?
1021 $text = $this->maybeMakeExternalImage( $url );
1022 if ( $text === false ) {
1023 # Not an image, make a link
1024 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1025 $this->getExternalLinkAttribs( $url ) );
1026 # Register it in the output object...
1027 # Replace unnecessary URL escape codes with their equivalent characters
1028 $pasteurized = self
::replaceUnusualEscapes( $url );
1029 $this->mOutput
->addExternalLink( $pasteurized );
1031 wfProfileOut( __METHOD__
);
1032 return $text . $trail;
1037 * Parse headers and return html
1041 function doHeadings( $text ) {
1042 wfProfileIn( __METHOD__
);
1043 for ( $i = 6; $i >= 1; --$i ) {
1044 $h = str_repeat( '=', $i );
1045 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1046 "<h$i>\\1</h$i>", $text );
1048 wfProfileOut( __METHOD__
);
1053 * Replace single quotes with HTML markup
1055 * @return string the altered text
1057 function doAllQuotes( $text ) {
1058 wfProfileIn( __METHOD__
);
1060 $lines = StringUtils
::explode( "\n", $text );
1061 foreach ( $lines as $line ) {
1062 $outtext .= $this->doQuotes( $line ) . "\n";
1064 $outtext = substr($outtext, 0,-1);
1065 wfProfileOut( __METHOD__
);
1070 * Helper function for doAllQuotes()
1072 public function doQuotes( $text ) {
1073 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1074 if ( count( $arr ) == 1 )
1078 # First, do some preliminary work. This may shift some apostrophes from
1079 # being mark-up to being text. It also counts the number of occurrences
1080 # of bold and italics mark-ups.
1084 foreach ( $arr as $r )
1086 if ( ( $i %
2 ) == 1 )
1088 # If there are ever four apostrophes, assume the first is supposed to
1089 # be text, and the remaining three constitute mark-up for bold text.
1090 if ( strlen( $arr[$i] ) == 4 )
1095 # If there are more than 5 apostrophes in a row, assume they're all
1096 # text except for the last 5.
1097 else if ( strlen( $arr[$i] ) > 5 )
1099 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1102 # Count the number of occurrences of bold and italics mark-ups.
1103 # We are not counting sequences of five apostrophes.
1104 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1105 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1106 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1111 # If there is an odd number of both bold and italics, it is likely
1112 # that one of the bold ones was meant to be an apostrophe followed
1113 # by italics. Which one we cannot know for certain, but it is more
1114 # likely to be one that has a single-letter word before it.
1115 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1118 $firstsingleletterword = -1;
1119 $firstmultiletterword = -1;
1121 foreach ( $arr as $r )
1123 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1125 $x1 = substr ($arr[$i-1], -1);
1126 $x2 = substr ($arr[$i-1], -2, 1);
1128 if ($firstspace == -1) $firstspace = $i;
1129 } else if ($x2 === ' ') {
1130 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1132 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1138 # If there is a single-letter word, use it!
1139 if ($firstsingleletterword > -1)
1141 $arr [ $firstsingleletterword ] = "''";
1142 $arr [ $firstsingleletterword-1 ] .= "'";
1144 # If not, but there's a multi-letter word, use that one.
1145 else if ($firstmultiletterword > -1)
1147 $arr [ $firstmultiletterword ] = "''";
1148 $arr [ $firstmultiletterword-1 ] .= "'";
1150 # ... otherwise use the first one that has neither.
1151 # (notice that it is possible for all three to be -1 if, for example,
1152 # there is only one pentuple-apostrophe in the line)
1153 else if ($firstspace > -1)
1155 $arr [ $firstspace ] = "''";
1156 $arr [ $firstspace-1 ] .= "'";
1160 # Now let's actually convert our apostrophic mush to HTML!
1165 foreach ($arr as $r)
1169 if ($state === 'both')
1176 if (strlen ($r) == 2)
1179 { $output .= '</i>'; $state = ''; }
1180 else if ($state === 'bi')
1181 { $output .= '</i>'; $state = 'b'; }
1182 else if ($state === 'ib')
1183 { $output .= '</b></i><b>'; $state = 'b'; }
1184 else if ($state === 'both')
1185 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1186 else # $state can be 'b' or ''
1187 { $output .= '<i>'; $state .= 'i'; }
1189 else if (strlen ($r) == 3)
1192 { $output .= '</b>'; $state = ''; }
1193 else if ($state === 'bi')
1194 { $output .= '</i></b><i>'; $state = 'i'; }
1195 else if ($state === 'ib')
1196 { $output .= '</b>'; $state = 'i'; }
1197 else if ($state === 'both')
1198 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1199 else # $state can be 'i' or ''
1200 { $output .= '<b>'; $state .= 'b'; }
1202 else if (strlen ($r) == 5)
1205 { $output .= '</b><i>'; $state = 'i'; }
1206 else if ($state === 'i')
1207 { $output .= '</i><b>'; $state = 'b'; }
1208 else if ($state === 'bi')
1209 { $output .= '</i></b>'; $state = ''; }
1210 else if ($state === 'ib')
1211 { $output .= '</b></i>'; $state = ''; }
1212 else if ($state === 'both')
1213 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1214 else # ($state == '')
1215 { $buffer = ''; $state = 'both'; }
1220 # Now close all remaining tags. Notice that the order is important.
1221 if ($state === 'b' ||
$state === 'ib')
1223 if ($state === 'i' ||
$state === 'bi' ||
$state === 'ib')
1225 if ($state === 'bi')
1227 # There might be lonely ''''', so make sure we have a buffer
1228 if ($state === 'both' && $buffer)
1229 $output .= '<b><i>'.$buffer.'</i></b>';
1235 * Replace external links (REL)
1237 * Note: this is all very hackish and the order of execution matters a lot.
1238 * Make sure to run maintenance/parserTests.php if you change this code.
1242 function replaceExternalLinks( $text ) {
1244 wfProfileIn( __METHOD__
);
1246 $sk = $this->mOptions
->getSkin();
1248 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1249 $s = array_shift( $bits );
1252 while ( $i<count( $bits ) ) {
1254 $protocol = $bits[$i++
];
1255 $text = $bits[$i++
];
1256 $trail = $bits[$i++
];
1258 # The characters '<' and '>' (which were escaped by
1259 # removeHTMLtags()) should not be included in
1260 # URLs, per RFC 2396.
1262 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1263 $text = substr($url, $m2[0][1]) . ' ' . $text;
1264 $url = substr($url, 0, $m2[0][1]);
1267 # If the link text is an image URL, replace it with an <img> tag
1268 # This happened by accident in the original parser, but some people used it extensively
1269 $img = $this->maybeMakeExternalImage( $text );
1270 if ( $img !== false ) {
1276 # Set linktype for CSS - if URL==text, link is essentially free
1277 $linktype = ($text === $url) ?
'free' : 'text';
1279 # No link text, e.g. [http://domain.tld/some.link]
1280 if ( $text == '' ) {
1281 # Autonumber if allowed. See bug #5918
1282 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1283 $langObj = $this->getFunctionLang();
1284 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1285 $linktype = 'autonumber';
1287 # Otherwise just use the URL
1288 $text = htmlspecialchars( $url );
1292 # Have link text, e.g. [http://domain.tld/some.link text]s
1294 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1297 $text = $wgContLang->markNoConversion($text);
1299 $url = Sanitizer
::cleanUrl( $url );
1301 # Use the encoded URL
1302 # This means that users can paste URLs directly into the text
1303 # Funny characters like ö aren't valid in URLs anyway
1304 # This was changed in August 2004
1305 $s .= $sk->makeExternalLink( $url, $text, false, $linktype,
1306 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1308 # Register link in the output object.
1309 # Replace unnecessary URL escape codes with the referenced character
1310 # This prevents spammers from hiding links from the filters
1311 $pasteurized = self
::replaceUnusualEscapes( $url );
1312 $this->mOutput
->addExternalLink( $pasteurized );
1315 wfProfileOut( __METHOD__
);
1320 * Get an associative array of additional HTML attributes appropriate for a
1321 * particular external link. This currently may include rel => nofollow
1322 * (depending on configuration, namespace, and the URL's domain) and/or a
1323 * target attribute (depending on configuration).
1325 * @param string $url Optional URL, to extract the domain from for rel =>
1326 * nofollow if appropriate
1327 * @return array Associative array of HTML attributes
1329 function getExternalLinkAttribs( $url = false ) {
1331 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1332 $ns = $this->mTitle
->getNamespace();
1333 if( $wgNoFollowLinks && !in_array($ns, $wgNoFollowNsExceptions) ) {
1334 $attribs['rel'] = 'nofollow';
1336 global $wgNoFollowDomainExceptions;
1337 if ( $wgNoFollowDomainExceptions ) {
1338 $bits = wfParseUrl( $url );
1339 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1340 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1341 if( substr( $bits['host'], -strlen( $domain ) )
1343 unset( $attribs['rel'] );
1350 if ( $this->mOptions
->getExternalLinkTarget() ) {
1351 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1358 * Replace unusual URL escape codes with their equivalent characters
1362 * @todo This can merge genuinely required bits in the path or query string,
1363 * breaking legit URLs. A proper fix would treat the various parts of
1364 * the URL differently; as a workaround, just use the output for
1365 * statistical records, not for actual linking/output.
1367 static function replaceUnusualEscapes( $url ) {
1368 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1369 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1373 * Callback function used in replaceUnusualEscapes().
1374 * Replaces unusual URL escape codes with their equivalent character
1378 private static function replaceUnusualEscapesCallback( $matches ) {
1379 $char = urldecode( $matches[0] );
1380 $ord = ord( $char );
1381 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1382 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1383 // No, shouldn't be escaped
1386 // Yes, leave it escaped
1392 * make an image if it's allowed, either through the global
1393 * option, through the exception, or through the on-wiki whitelist
1396 function maybeMakeExternalImage( $url ) {
1397 $sk = $this->mOptions
->getSkin();
1398 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1399 $imagesexception = !empty($imagesfrom);
1401 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1402 if( $imagesexception && is_array( $imagesfrom ) ) {
1403 $imagematch = false;
1404 foreach( $imagesfrom as $match ) {
1405 if( strpos( $url, $match ) === 0 ) {
1410 } elseif( $imagesexception ) {
1411 $imagematch = (strpos( $url, $imagesfrom ) === 0);
1413 $imagematch = false;
1415 if ( $this->mOptions
->getAllowExternalImages()
1416 ||
( $imagesexception && $imagematch ) ) {
1417 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1419 $text = $sk->makeExternalImage( $url );
1422 if( !$text && $this->mOptions
->getEnableImageWhitelist()
1423 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1424 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1425 foreach( $whitelist as $entry ) {
1426 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1427 if( strpos( $entry, '#' ) === 0 ||
$entry === '' )
1429 if( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1430 # Image matches a whitelist entry
1431 $text = $sk->makeExternalImage( $url );
1440 * Process [[ ]] wikilinks
1441 * @return processed text
1445 function replaceInternalLinks( $s ) {
1446 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1451 * Process [[ ]] wikilinks (RIL)
1452 * @return LinkHolderArray
1456 function replaceInternalLinks2( &$s ) {
1459 wfProfileIn( __METHOD__
);
1461 wfProfileIn( __METHOD__
.'-setup' );
1462 static $tc = FALSE, $e1, $e1_img;
1463 # the % is needed to support urlencoded titles as well
1465 $tc = Title
::legalChars() . '#%';
1466 # Match a link having the form [[namespace:link|alternate]]trail
1467 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1468 # Match cases where there is no "]]", which might still be images
1469 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1472 $sk = $this->mOptions
->getSkin();
1473 $holders = new LinkHolderArray( $this );
1475 #split the entire text string on occurences of [[
1476 $a = StringUtils
::explode( '[[', ' ' . $s );
1477 #get the first element (all text up to first [[), and remove the space we added
1480 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1481 $s = substr( $s, 1 );
1483 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1485 if ( $useLinkPrefixExtension ) {
1486 # Match the end of a line for a word that's not followed by whitespace,
1487 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1488 $e2 = wfMsgForContent( 'linkprefix' );
1491 if( is_null( $this->mTitle
) ) {
1492 wfProfileOut( __METHOD__
.'-setup' );
1493 wfProfileOut( __METHOD__
);
1494 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1496 $nottalk = !$this->mTitle
->isTalkPage();
1498 if ( $useLinkPrefixExtension ) {
1500 if ( preg_match( $e2, $s, $m ) ) {
1501 $first_prefix = $m[2];
1503 $first_prefix = false;
1509 if($wgContLang->hasVariants()) {
1510 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1512 $selflink = array($this->mTitle
->getPrefixedText());
1514 $useSubpages = $this->areSubpagesAllowed();
1515 wfProfileOut( __METHOD__
.'-setup' );
1517 # Loop for each link
1518 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1519 # Check for excessive memory usage
1520 if ( $holders->isBig() ) {
1522 # Do the existence check, replace the link holders and clear the array
1523 $holders->replace( $s );
1527 if ( $useLinkPrefixExtension ) {
1528 wfProfileIn( __METHOD__
.'-prefixhandling' );
1529 if ( preg_match( $e2, $s, $m ) ) {
1537 $prefix = $first_prefix;
1538 $first_prefix = false;
1540 wfProfileOut( __METHOD__
.'-prefixhandling' );
1543 $might_be_img = false;
1545 wfProfileIn( __METHOD__
."-e1" );
1546 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1548 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1549 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1550 # the real problem is with the $e1 regex
1553 # Still some problems for cases where the ] is meant to be outside punctuation,
1554 # and no image is in sight. See bug 2095.
1557 substr( $m[3], 0, 1 ) === ']' &&
1558 strpos($text, '[') !== false
1561 $text .= ']'; # so that replaceExternalLinks($text) works later
1562 $m[3] = substr( $m[3], 1 );
1564 # fix up urlencoded title texts
1565 if( strpos( $m[1], '%' ) !== false ) {
1566 # Should anchors '#' also be rejected?
1567 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1570 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1571 $might_be_img = true;
1573 if ( strpos( $m[1], '%' ) !== false ) {
1574 $m[1] = urldecode($m[1]);
1577 } else { # Invalid form; output directly
1578 $s .= $prefix . '[[' . $line ;
1579 wfProfileOut( __METHOD__
."-e1" );
1582 wfProfileOut( __METHOD__
."-e1" );
1583 wfProfileIn( __METHOD__
."-misc" );
1585 # Don't allow internal links to pages containing
1586 # PROTO: where PROTO is a valid URL protocol; these
1587 # should be external links.
1588 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1589 $s .= $prefix . '[[' . $line ;
1590 wfProfileOut( __METHOD__
."-misc" );
1594 # Make subpage if necessary
1595 if ( $useSubpages ) {
1596 $link = $this->maybeDoSubpageLink( $m[1], $text );
1601 $noforce = (substr( $m[1], 0, 1 ) !== ':');
1603 # Strip off leading ':'
1604 $link = substr( $link, 1 );
1607 wfProfileOut( __METHOD__
."-misc" );
1608 wfProfileIn( __METHOD__
."-title" );
1609 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1610 if ( $nt === NULL ) {
1611 $s .= $prefix . '[[' . $line;
1612 wfProfileOut( __METHOD__
."-title" );
1616 $ns = $nt->getNamespace();
1617 $iw = $nt->getInterWiki();
1618 wfProfileOut( __METHOD__
."-title" );
1620 if ( $might_be_img ) { # if this is actually an invalid link
1621 wfProfileIn( __METHOD__
."-might_be_img" );
1622 if ( $ns == NS_FILE
&& $noforce ) { #but might be an image
1625 #look at the next 'line' to see if we can close it there
1627 $next_line = $a->current();
1628 if ( $next_line === false ||
$next_line === null ) {
1631 $m = explode( ']]', $next_line, 3 );
1632 if ( count( $m ) == 3 ) {
1633 # the first ]] closes the inner link, the second the image
1635 $text .= "[[{$m[0]}]]{$m[1]}";
1638 } elseif ( count( $m ) == 2 ) {
1639 #if there's exactly one ]] that's fine, we'll keep looking
1640 $text .= "[[{$m[0]}]]{$m[1]}";
1642 #if $next_line is invalid too, we need look no further
1643 $text .= '[[' . $next_line;
1648 # we couldn't find the end of this imageLink, so output it raw
1649 #but don't ignore what might be perfectly normal links in the text we've examined
1650 $holders->merge( $this->replaceInternalLinks2( $text ) );
1651 $s .= "{$prefix}[[$link|$text";
1652 # note: no $trail, because without an end, there *is* no trail
1653 wfProfileOut( __METHOD__
."-might_be_img" );
1656 } else { #it's not an image, so output it raw
1657 $s .= "{$prefix}[[$link|$text";
1658 # note: no $trail, because without an end, there *is* no trail
1659 wfProfileOut( __METHOD__
."-might_be_img" );
1662 wfProfileOut( __METHOD__
."-might_be_img" );
1665 $wasblank = ( '' == $text );
1666 if ( $wasblank ) $text = $link;
1668 # Link not escaped by : , create the various objects
1672 wfProfileIn( __METHOD__
."-interwiki" );
1673 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1674 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1675 $s = rtrim($s . $prefix);
1676 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1677 wfProfileOut( __METHOD__
."-interwiki" );
1680 wfProfileOut( __METHOD__
."-interwiki" );
1682 if ( $ns == NS_FILE
) {
1683 wfProfileIn( __METHOD__
."-image" );
1684 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1686 # if no parameters were passed, $text
1687 # becomes something like "File:Foo.png",
1688 # which we don't want to pass on to the
1692 # recursively parse links inside the image caption
1693 # actually, this will parse them in any other parameters, too,
1694 # but it might be hard to fix that, and it doesn't matter ATM
1695 $text = $this->replaceExternalLinks($text);
1696 $holders->merge( $this->replaceInternalLinks2( $text ) );
1698 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1699 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1701 $this->mOutput
->addImage( $nt->getDBkey() );
1702 wfProfileOut( __METHOD__
."-image" );
1707 if ( $ns == NS_CATEGORY
) {
1708 wfProfileIn( __METHOD__
."-category" );
1709 $s = preg_replace( "/(\s*\n)+\s*$/D", '', $s ); # bug 87
1712 $sortkey = $this->getDefaultSort();
1716 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1717 $sortkey = str_replace( "\n", '', $sortkey );
1718 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1719 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1722 * Strip the whitespace Category links produce, see bug 87
1723 * @todo We might want to use trim($tmp, "\n") here.
1725 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'' : $prefix . $trail;
1727 wfProfileOut( __METHOD__
."-category" );
1732 # Self-link checking
1733 if( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1734 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1735 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1740 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1741 # FIXME: Should do batch file existence checks, see comment below
1742 if( $ns == NS_MEDIA
) {
1743 wfProfileIn( __METHOD__
."-media" );
1744 # Give extensions a chance to select the file revision for us
1745 $skip = $time = false;
1746 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1748 $link = $sk->link( $nt );
1750 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1752 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1753 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1754 $this->mOutput
->addImage( $nt->getDBkey() );
1755 wfProfileOut( __METHOD__
."-media" );
1759 wfProfileIn( __METHOD__
."-always_known" );
1760 # Some titles, such as valid special pages or files in foreign repos, should
1761 # be shown as bluelinks even though they're not included in the page table
1763 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1764 # batch file existence checks for NS_FILE and NS_MEDIA
1765 if( $iw == '' && $nt->isAlwaysKnown() ) {
1766 $this->mOutput
->addLink( $nt );
1767 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1769 # Links will be added to the output link list after checking
1770 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1772 wfProfileOut( __METHOD__
."-always_known" );
1774 wfProfileOut( __METHOD__
);
1779 * Make a link placeholder. The text returned can be later resolved to a real link with
1780 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1781 * parsing of interwiki links, and secondly to allow all existence checks and
1782 * article length checks (for stub links) to be bundled into a single query.
1786 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1787 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1791 * Render a forced-blue link inline; protect against double expansion of
1792 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1793 * Since this little disaster has to split off the trail text to avoid
1794 * breaking URLs in the following text without breaking trails on the
1795 * wiki links, it's been made into a horrible function.
1798 * @param string $text
1799 * @param string $query
1800 * @param string $trail
1801 * @param string $prefix
1802 * @return string HTML-wikitext mix oh yuck
1804 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1805 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1806 $sk = $this->mOptions
->getSkin();
1807 // FIXME: use link() instead of deprecated makeKnownLinkObj()
1808 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1809 return $this->armorLinks( $link ) . $trail;
1813 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1814 * going to go through further parsing steps before inline URL expansion.
1816 * Not needed quite as much as it used to be since free links are a bit
1817 * more sensible these days. But bracketed links are still an issue.
1819 * @param string more-or-less HTML
1820 * @return string less-or-more HTML with NOPARSE bits
1822 function armorLinks( $text ) {
1823 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1824 "{$this->mUniqPrefix}NOPARSE$1", $text );
1828 * Return true if subpage links should be expanded on this page.
1831 function areSubpagesAllowed() {
1832 # Some namespaces don't allow subpages
1833 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
1837 * Handle link to subpage if necessary
1838 * @param string $target the source of the link
1839 * @param string &$text the link text, modified as necessary
1840 * @return string the full name of the link
1843 function maybeDoSubpageLink($target, &$text) {
1844 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
1848 * Used by doBlockLevels()
1851 /* private */ function closeParagraph() {
1853 if ( '' != $this->mLastSection
) {
1854 $result = '</' . $this->mLastSection
. ">\n";
1856 $this->mInPre
= false;
1857 $this->mLastSection
= '';
1860 # getCommon() returns the length of the longest common substring
1861 # of both arguments, starting at the beginning of both.
1863 /* private */ function getCommon( $st1, $st2 ) {
1864 $fl = strlen( $st1 );
1865 $shorter = strlen( $st2 );
1866 if ( $fl < $shorter ) { $shorter = $fl; }
1868 for ( $i = 0; $i < $shorter; ++
$i ) {
1869 if ( $st1{$i} != $st2{$i} ) { break; }
1873 # These next three functions open, continue, and close the list
1874 # element appropriate to the prefix character passed into them.
1876 /* private */ function openList( $char ) {
1877 $result = $this->closeParagraph();
1879 if ( '*' === $char ) { $result .= '<ul><li>'; }
1880 elseif ( '#' === $char ) { $result .= '<ol><li>'; }
1881 elseif ( ':' === $char ) { $result .= '<dl><dd>'; }
1882 elseif ( ';' === $char ) {
1883 $result .= '<dl><dt>';
1884 $this->mDTopen
= true;
1886 else { $result = '<!-- ERR 1 -->'; }
1891 /* private */ function nextItem( $char ) {
1892 if ( '*' === $char ||
'#' === $char ) { return '</li><li>'; }
1893 elseif ( ':' === $char ||
';' === $char ) {
1895 if ( $this->mDTopen
) { $close = '</dt>'; }
1896 if ( ';' === $char ) {
1897 $this->mDTopen
= true;
1898 return $close . '<dt>';
1900 $this->mDTopen
= false;
1901 return $close . '<dd>';
1904 return '<!-- ERR 2 -->';
1907 /* private */ function closeList( $char ) {
1908 if ( '*' === $char ) { $text = '</li></ul>'; }
1909 elseif ( '#' === $char ) { $text = '</li></ol>'; }
1910 elseif ( ':' === $char ) {
1911 if ( $this->mDTopen
) {
1912 $this->mDTopen
= false;
1913 $text = '</dt></dl>';
1915 $text = '</dd></dl>';
1918 else { return '<!-- ERR 3 -->'; }
1924 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
1926 * @param $linestart bool whether or not this is at the start of a line.
1928 * @return string the lists rendered as HTML
1930 function doBlockLevels( $text, $linestart ) {
1931 wfProfileIn( __METHOD__
);
1933 # Parsing through the text line by line. The main thing
1934 # happening here is handling of block-level elements p, pre,
1935 # and making lists from lines starting with * # : etc.
1937 $textLines = StringUtils
::explode( "\n", $text );
1939 $lastPrefix = $output = '';
1940 $this->mDTopen
= $inBlockElem = false;
1942 $paragraphStack = false;
1944 foreach ( $textLines as $oLine ) {
1946 if ( !$linestart ) {
1956 $lastPrefixLength = strlen( $lastPrefix );
1957 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1958 $preOpenMatch = preg_match('/<pre/i', $oLine );
1959 // If not in a <pre> element, scan for and figure out what prefixes are there.
1960 if ( !$this->mInPre
) {
1961 # Multiple prefixes may abut each other for nested lists.
1962 $prefixLength = strspn( $oLine, '*#:;' );
1963 $prefix = substr( $oLine, 0, $prefixLength );
1966 // ; and : are both from definition-lists, so they're equivalent
1967 // for the purposes of determining whether or not we need to open/close
1969 $prefix2 = str_replace( ';', ':', $prefix );
1970 $t = substr( $oLine, $prefixLength );
1971 $this->mInPre
= (bool)$preOpenMatch;
1973 # Don't interpret any other prefixes in preformatted text
1975 $prefix = $prefix2 = '';
1980 if( $prefixLength && $lastPrefix === $prefix2 ) {
1981 # Same as the last item, so no need to deal with nesting or opening stuff
1982 $output .= $this->nextItem( substr( $prefix, -1 ) );
1983 $paragraphStack = false;
1985 if ( substr( $prefix, -1 ) === ';') {
1986 # The one nasty exception: definition lists work like this:
1987 # ; title : definition text
1988 # So we check for : in the remainder text to split up the
1989 # title and definition, without b0rking links.
1991 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
1993 $output .= $term . $this->nextItem( ':' );
1996 } elseif( $prefixLength ||
$lastPrefixLength ) {
1997 // We need to open or close prefixes, or both.
1999 # Either open or close a level...
2000 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2001 $paragraphStack = false;
2003 // Close all the prefixes which aren't shared.
2004 while( $commonPrefixLength < $lastPrefixLength ) {
2005 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2006 --$lastPrefixLength;
2009 // Continue the current prefix if appropriate.
2010 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2011 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2014 // Open prefixes where appropriate.
2015 while ( $prefixLength > $commonPrefixLength ) {
2016 $char = substr( $prefix, $commonPrefixLength, 1 );
2017 $output .= $this->openList( $char );
2019 if ( ';' === $char ) {
2020 # FIXME: This is dupe of code above
2021 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2023 $output .= $term . $this->nextItem( ':' );
2026 ++
$commonPrefixLength;
2028 $lastPrefix = $prefix2;
2031 // If we have no prefixes, go to paragraph mode.
2032 if( 0 == $prefixLength ) {
2033 wfProfileIn( __METHOD__
."-paragraph" );
2034 # No prefix (not in list)--go to paragraph mode
2035 // XXX: use a stack for nestable elements like span, table and div
2036 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2037 $closematch = preg_match(
2038 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2039 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2040 if ( $openmatch or $closematch ) {
2041 $paragraphStack = false;
2042 #Â TODO bug 5718: paragraph closed
2043 $output .= $this->closeParagraph();
2044 if ( $preOpenMatch and !$preCloseMatch ) {
2045 $this->mInPre
= true;
2047 if ( $closematch ) {
2048 $inBlockElem = false;
2050 $inBlockElem = true;
2052 } else if ( !$inBlockElem && !$this->mInPre
) {
2053 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' or trim($t) != '' ) ) {
2055 if ($this->mLastSection
!== 'pre') {
2056 $paragraphStack = false;
2057 $output .= $this->closeParagraph().'<pre>';
2058 $this->mLastSection
= 'pre';
2060 $t = substr( $t, 1 );
2063 if ( '' == trim($t) ) {
2064 if ( $paragraphStack ) {
2065 $output .= $paragraphStack.'<br />';
2066 $paragraphStack = false;
2067 $this->mLastSection
= 'p';
2069 if ($this->mLastSection
!== 'p' ) {
2070 $output .= $this->closeParagraph();
2071 $this->mLastSection
= '';
2072 $paragraphStack = '<p>';
2074 $paragraphStack = '</p><p>';
2078 if ( $paragraphStack ) {
2079 $output .= $paragraphStack;
2080 $paragraphStack = false;
2081 $this->mLastSection
= 'p';
2082 } else if ($this->mLastSection
!== 'p') {
2083 $output .= $this->closeParagraph().'<p>';
2084 $this->mLastSection
= 'p';
2089 wfProfileOut( __METHOD__
."-paragraph" );
2091 // somewhere above we forget to get out of pre block (bug 785)
2092 if($preCloseMatch && $this->mInPre
) {
2093 $this->mInPre
= false;
2095 if ($paragraphStack === false) {
2099 while ( $prefixLength ) {
2100 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2103 if ( '' != $this->mLastSection
) {
2104 $output .= '</' . $this->mLastSection
. '>';
2105 $this->mLastSection
= '';
2108 wfProfileOut( __METHOD__
);
2113 * Split up a string on ':', ignoring any occurences inside tags
2114 * to prevent illegal overlapping.
2115 * @param string $str the string to split
2116 * @param string &$before set to everything before the ':'
2117 * @param string &$after set to everything after the ':'
2118 * return string the position of the ':', or false if none found
2120 function findColonNoLinks($str, &$before, &$after) {
2121 wfProfileIn( __METHOD__
);
2123 $pos = strpos( $str, ':' );
2124 if( $pos === false ) {
2126 wfProfileOut( __METHOD__
);
2130 $lt = strpos( $str, '<' );
2131 if( $lt === false ||
$lt > $pos ) {
2132 // Easy; no tag nesting to worry about
2133 $before = substr( $str, 0, $pos );
2134 $after = substr( $str, $pos+
1 );
2135 wfProfileOut( __METHOD__
);
2139 // Ugly state machine to walk through avoiding tags.
2140 $state = self
::COLON_STATE_TEXT
;
2142 $len = strlen( $str );
2143 for( $i = 0; $i < $len; $i++
) {
2147 // (Using the number is a performance hack for common cases)
2148 case 0: // self::COLON_STATE_TEXT:
2151 // Could be either a <start> tag or an </end> tag
2152 $state = self
::COLON_STATE_TAGSTART
;
2157 $before = substr( $str, 0, $i );
2158 $after = substr( $str, $i +
1 );
2159 wfProfileOut( __METHOD__
);
2162 // Embedded in a tag; don't break it.
2165 // Skip ahead looking for something interesting
2166 $colon = strpos( $str, ':', $i );
2167 if( $colon === false ) {
2168 // Nothing else interesting
2169 wfProfileOut( __METHOD__
);
2172 $lt = strpos( $str, '<', $i );
2173 if( $stack === 0 ) {
2174 if( $lt === false ||
$colon < $lt ) {
2176 $before = substr( $str, 0, $colon );
2177 $after = substr( $str, $colon +
1 );
2178 wfProfileOut( __METHOD__
);
2182 if( $lt === false ) {
2183 // Nothing else interesting to find; abort!
2184 // We're nested, but there's no close tags left. Abort!
2187 // Skip ahead to next tag start
2189 $state = self
::COLON_STATE_TAGSTART
;
2192 case 1: // self::COLON_STATE_TAG:
2197 $state = self
::COLON_STATE_TEXT
;
2200 // Slash may be followed by >?
2201 $state = self
::COLON_STATE_TAGSLASH
;
2207 case 2: // self::COLON_STATE_TAGSTART:
2210 $state = self
::COLON_STATE_CLOSETAG
;
2213 $state = self
::COLON_STATE_COMMENT
;
2216 // Illegal early close? This shouldn't happen D:
2217 $state = self
::COLON_STATE_TEXT
;
2220 $state = self
::COLON_STATE_TAG
;
2223 case 3: // self::COLON_STATE_CLOSETAG:
2228 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2229 wfProfileOut( __METHOD__
);
2232 $state = self
::COLON_STATE_TEXT
;
2235 case self
::COLON_STATE_TAGSLASH
:
2237 // Yes, a self-closed tag <blah/>
2238 $state = self
::COLON_STATE_TEXT
;
2240 // Probably we're jumping the gun, and this is an attribute
2241 $state = self
::COLON_STATE_TAG
;
2244 case 5: // self::COLON_STATE_COMMENT:
2246 $state = self
::COLON_STATE_COMMENTDASH
;
2249 case self
::COLON_STATE_COMMENTDASH
:
2251 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2253 $state = self
::COLON_STATE_COMMENT
;
2256 case self
::COLON_STATE_COMMENTDASHDASH
:
2258 $state = self
::COLON_STATE_TEXT
;
2260 $state = self
::COLON_STATE_COMMENT
;
2264 throw new MWException( "State machine error in " . __METHOD__
);
2268 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2271 wfProfileOut( __METHOD__
);
2276 * Return value of a magic variable (like PAGENAME)
2280 function getVariableValue( $index ) {
2281 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2284 * Some of these require message or data lookups and can be
2285 * expensive to check many times.
2287 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2288 if ( isset( $this->mVarCache
[$index] ) ) {
2289 return $this->mVarCache
[$index];
2293 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2294 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2297 global $wgLocaltimezone;
2298 if ( isset( $wgLocaltimezone ) ) {
2299 $oldtz = getenv( 'TZ' );
2300 putenv( 'TZ='.$wgLocaltimezone );
2303 wfSuppressWarnings(); // E_STRICT system time bitching
2304 $localTimestamp = date( 'YmdHis', $ts );
2305 $localMonth = date( 'm', $ts );
2306 $localMonth1 = date( 'n', $ts );
2307 $localMonthName = date( 'n', $ts );
2308 $localDay = date( 'j', $ts );
2309 $localDay2 = date( 'd', $ts );
2310 $localDayOfWeek = date( 'w', $ts );
2311 $localWeek = date( 'W', $ts );
2312 $localYear = date( 'Y', $ts );
2313 $localHour = date( 'H', $ts );
2314 if ( isset( $wgLocaltimezone ) ) {
2315 putenv( 'TZ='.$oldtz );
2317 wfRestoreWarnings();
2320 case 'currentmonth':
2321 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2322 case 'currentmonth1':
2323 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2324 case 'currentmonthname':
2325 return $this->mVarCache
[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2326 case 'currentmonthnamegen':
2327 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2328 case 'currentmonthabbrev':
2329 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2331 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2333 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2335 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localMonth );
2337 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localMonth1 );
2338 case 'localmonthname':
2339 return $this->mVarCache
[$index] = $wgContLang->getMonthName( $localMonthName );
2340 case 'localmonthnamegen':
2341 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2342 case 'localmonthabbrev':
2343 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2345 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay );
2347 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay2 );
2349 return wfEscapeWikiText( $this->mTitle
->getText() );
2351 return $this->mTitle
->getPartialURL();
2352 case 'fullpagename':
2353 return wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2354 case 'fullpagenamee':
2355 return $this->mTitle
->getPrefixedURL();
2357 return wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2358 case 'subpagenamee':
2359 return $this->mTitle
->getSubpageUrlForm();
2360 case 'basepagename':
2361 return wfEscapeWikiText( $this->mTitle
->getBaseText() );
2362 case 'basepagenamee':
2363 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2364 case 'talkpagename':
2365 if( $this->mTitle
->canTalk() ) {
2366 $talkPage = $this->mTitle
->getTalkPage();
2367 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2371 case 'talkpagenamee':
2372 if( $this->mTitle
->canTalk() ) {
2373 $talkPage = $this->mTitle
->getTalkPage();
2374 return $talkPage->getPrefixedUrl();
2378 case 'subjectpagename':
2379 $subjPage = $this->mTitle
->getSubjectPage();
2380 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2381 case 'subjectpagenamee':
2382 $subjPage = $this->mTitle
->getSubjectPage();
2383 return $subjPage->getPrefixedUrl();
2385 // Let the edit saving system know we should parse the page
2386 // *after* a revision ID has been assigned.
2387 $this->mOutput
->setFlag( 'vary-revision' );
2388 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2389 return $this->mRevisionId
;
2391 // Let the edit saving system know we should parse the page
2392 // *after* a revision ID has been assigned. This is for null edits.
2393 $this->mOutput
->setFlag( 'vary-revision' );
2394 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2395 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2396 case 'revisionday2':
2397 // Let the edit saving system know we should parse the page
2398 // *after* a revision ID has been assigned. This is for null edits.
2399 $this->mOutput
->setFlag( 'vary-revision' );
2400 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2401 return substr( $this->getRevisionTimestamp(), 6, 2 );
2402 case 'revisionmonth':
2403 // Let the edit saving system know we should parse the page
2404 // *after* a revision ID has been assigned. This is for null edits.
2405 $this->mOutput
->setFlag( 'vary-revision' );
2406 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2407 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2408 case 'revisionyear':
2409 // Let the edit saving system know we should parse the page
2410 // *after* a revision ID has been assigned. This is for null edits.
2411 $this->mOutput
->setFlag( 'vary-revision' );
2412 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2413 return substr( $this->getRevisionTimestamp(), 0, 4 );
2414 case 'revisiontimestamp':
2415 // Let the edit saving system know we should parse the page
2416 // *after* a revision ID has been assigned. This is for null edits.
2417 $this->mOutput
->setFlag( 'vary-revision' );
2418 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2419 return $this->getRevisionTimestamp();
2420 case 'revisionuser':
2421 // Let the edit saving system know we should parse the page
2422 // *after* a revision ID has been assigned. This is for null edits.
2423 $this->mOutput
->setFlag( 'vary-revision' );
2424 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2425 return $this->getRevisionUser();
2427 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2429 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2431 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2433 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2434 case 'subjectspace':
2435 return $this->mTitle
->getSubjectNsText();
2436 case 'subjectspacee':
2437 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2438 case 'currentdayname':
2439 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2441 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2443 return $this->mVarCache
[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2445 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2447 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2448 // int to remove the padding
2449 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2451 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2452 case 'localdayname':
2453 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2455 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localYear, true );
2457 return $this->mVarCache
[$index] = $wgContLang->time( $localTimestamp, false, false );
2459 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localHour, true );
2461 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2462 // int to remove the padding
2463 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)$localWeek );
2465 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDayOfWeek );
2466 case 'numberofarticles':
2467 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2468 case 'numberoffiles':
2469 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::images() );
2470 case 'numberofusers':
2471 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::users() );
2472 case 'numberofactiveusers':
2473 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::activeUsers() );
2474 case 'numberofpages':
2475 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2476 case 'numberofadmins':
2477 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::numberingroup('sysop') );
2478 case 'numberofedits':
2479 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2480 case 'numberofviews':
2481 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::views() );
2482 case 'currenttimestamp':
2483 return $this->mVarCache
[$index] = wfTimestamp( TS_MW
, $ts );
2484 case 'localtimestamp':
2485 return $this->mVarCache
[$index] = $localTimestamp;
2486 case 'currentversion':
2487 return $this->mVarCache
[$index] = SpecialVersion
::getVersion();
2493 return $wgServerName;
2495 return $wgScriptPath;
2496 case 'directionmark':
2497 return $wgContLang->getDirMark();
2498 case 'contentlanguage':
2499 global $wgContLanguageCode;
2500 return $wgContLanguageCode;
2503 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret ) ) )
2511 * initialise the magic variables (like CURRENTMONTHNAME)
2515 function initialiseVariables() {
2516 wfProfileIn( __METHOD__
);
2517 $variableIDs = MagicWord
::getVariableIDs();
2519 $this->mVariables
= new MagicWordArray( $variableIDs );
2520 wfProfileOut( __METHOD__
);
2524 * Preprocess some wikitext and return the document tree.
2525 * This is the ghost of replace_variables().
2527 * @param string $text The text to parse
2528 * @param integer flags Bitwise combination of:
2529 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2530 * included. Default is to assume a direct page view.
2532 * The generated DOM tree must depend only on the input text and the flags.
2533 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2535 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2536 * change in the DOM tree for a given text, must be passed through the section identifier
2537 * in the section edit link and thus back to extractSections().
2539 * The output of this function is currently only cached in process memory, but a persistent
2540 * cache may be implemented at a later date which takes further advantage of these strict
2541 * dependency requirements.
2545 function preprocessToDom ( $text, $flags = 0 ) {
2546 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2551 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2553 public static function splitWhitespace( $s ) {
2554 $ltrimmed = ltrim( $s );
2555 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2556 $trimmed = rtrim( $ltrimmed );
2557 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2559 $w2 = substr( $ltrimmed, -$diff );
2563 return array( $w1, $trimmed, $w2 );
2567 * Replace magic variables, templates, and template arguments
2568 * with the appropriate text. Templates are substituted recursively,
2569 * taking care to avoid infinite loops.
2571 * Note that the substitution depends on value of $mOutputType:
2572 * self::OT_WIKI: only {{subst:}} templates
2573 * self::OT_PREPROCESS: templates but not extension tags
2574 * self::OT_HTML: all templates and extension tags
2576 * @param string $tex The text to transform
2577 * @param PPFrame $frame Object describing the arguments passed to the template.
2578 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2579 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2580 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2583 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2584 # Is there any text? Also, Prevent too big inclusions!
2585 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2588 wfProfileIn( __METHOD__
);
2590 if ( $frame === false ) {
2591 $frame = $this->getPreprocessor()->newFrame();
2592 } elseif ( !( $frame instanceof PPFrame
) ) {
2593 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2594 $frame = $this->getPreprocessor()->newCustomFrame($frame);
2597 $dom = $this->preprocessToDom( $text );
2598 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2599 $text = $frame->expand( $dom, $flags );
2601 wfProfileOut( __METHOD__
);
2605 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2606 static function createAssocArgs( $args ) {
2607 $assocArgs = array();
2609 foreach( $args as $arg ) {
2610 $eqpos = strpos( $arg, '=' );
2611 if ( $eqpos === false ) {
2612 $assocArgs[$index++
] = $arg;
2614 $name = trim( substr( $arg, 0, $eqpos ) );
2615 $value = trim( substr( $arg, $eqpos+
1 ) );
2616 if ( $value === false ) {
2619 if ( $name !== false ) {
2620 $assocArgs[$name] = $value;
2629 * Warn the user when a parser limitation is reached
2630 * Will warn at most once the user per limitation type
2632 * @param string $limitationType, should be one of:
2633 * 'expensive-parserfunction' (corresponding messages: 'expensive-parserfunction-warning', 'expensive-parserfunction-category')
2634 * 'post-expand-template-argument' (corresponding messages: 'post-expand-template-argument-warning', 'post-expand-template-argument-category')
2635 * 'post-expand-template-inclusion' (corresponding messages: 'post-expand-template-inclusion-warning', 'post-expand-template-inclusion-category')
2636 * @params int $current, $max When an explicit limit has been
2637 * exceeded, provide the values (optional)
2639 function limitationWarn( $limitationType, $current=null, $max=null) {
2640 $msgName = $limitationType . '-warning';
2641 //does no harm if $current and $max are present but are unnecessary for the message
2642 $warning = wfMsgExt( $msgName, array( 'parsemag', 'escape' ), $current, $max );
2643 $this->mOutput
->addWarning( $warning );
2644 $cat = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( $limitationType . '-category' ) );
2646 $this->mOutput
->addCategory( $cat->getDBkey(), $this->getDefaultSort() );
2651 * Return the text of a template, after recursively
2652 * replacing any variables or templates within the template.
2654 * @param array $piece The parts of the template
2655 * $piece['title']: the title, i.e. the part before the |
2656 * $piece['parts']: the parameter array
2657 * $piece['lineStart']: whether the brace was at the start of a line
2658 * @param PPFrame The current frame, contains template arguments
2659 * @return string the text of the template
2662 function braceSubstitution( $piece, $frame ) {
2663 global $wgContLang, $wgNonincludableNamespaces;
2664 wfProfileIn( __METHOD__
);
2665 wfProfileIn( __METHOD__
.'-setup' );
2668 $found = false; # $text has been filled
2669 $nowiki = false; # wiki markup in $text should be escaped
2670 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2671 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2672 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2673 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2675 # Title object, where $text came from
2678 # $part1 is the bit before the first |, and must contain only title characters.
2679 # Various prefixes will be stripped from it later.
2680 $titleWithSpaces = $frame->expand( $piece['title'] );
2681 $part1 = trim( $titleWithSpaces );
2684 # Original title text preserved for various purposes
2685 $originalTitle = $part1;
2687 # $args is a list of argument nodes, starting from index 0, not including $part1
2688 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2689 wfProfileOut( __METHOD__
.'-setup' );
2692 wfProfileIn( __METHOD__
.'-modifiers' );
2694 $mwSubst = MagicWord
::get( 'subst' );
2695 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2696 # One of two possibilities is true:
2697 # 1) Found SUBST but not in the PST phase
2698 # 2) Didn't find SUBST and in the PST phase
2699 # In either case, return without further processing
2700 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2707 if ( !$found && $args->getLength() == 0 ) {
2708 $id = $this->mVariables
->matchStartToEnd( $part1 );
2709 if ( $id !== false ) {
2710 $text = $this->getVariableValue( $id );
2711 if (MagicWord
::getCacheTTL($id)>-1)
2712 $this->mOutput
->mContainsOldMagic
= true;
2717 # MSG, MSGNW and RAW
2720 $mwMsgnw = MagicWord
::get( 'msgnw' );
2721 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2724 # Remove obsolete MSG:
2725 $mwMsg = MagicWord
::get( 'msg' );
2726 $mwMsg->matchStartAndRemove( $part1 );
2730 $mwRaw = MagicWord
::get( 'raw' );
2731 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2732 $forceRawInterwiki = true;
2735 wfProfileOut( __METHOD__
.'-modifiers' );
2739 wfProfileIn( __METHOD__
. '-pfunc' );
2741 $colonPos = strpos( $part1, ':' );
2742 if ( $colonPos !== false ) {
2743 # Case sensitive functions
2744 $function = substr( $part1, 0, $colonPos );
2745 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2746 $function = $this->mFunctionSynonyms
[1][$function];
2748 # Case insensitive functions
2749 $function = $wgContLang->lc( $function );
2750 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2751 $function = $this->mFunctionSynonyms
[0][$function];
2757 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2758 $initialArgs = array( &$this );
2759 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2760 if ( $flags & SFH_OBJECT_ARGS
) {
2761 # Add a frame parameter, and pass the arguments as an array
2762 $allArgs = $initialArgs;
2763 $allArgs[] = $frame;
2764 for ( $i = 0; $i < $args->getLength(); $i++
) {
2765 $funcArgs[] = $args->item( $i );
2767 $allArgs[] = $funcArgs;
2769 # Convert arguments to plain text
2770 for ( $i = 0; $i < $args->getLength(); $i++
) {
2771 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2773 $allArgs = array_merge( $initialArgs, $funcArgs );
2776 # Workaround for PHP bug 35229 and similar
2777 if ( !is_callable( $callback ) ) {
2778 wfProfileOut( __METHOD__
. '-pfunc' );
2779 wfProfileOut( __METHOD__
);
2780 throw new MWException( "Tag hook for $function is not callable\n" );
2782 $result = call_user_func_array( $callback, $allArgs );
2785 $preprocessFlags = 0;
2787 if ( is_array( $result ) ) {
2788 if ( isset( $result[0] ) ) {
2790 unset( $result[0] );
2793 // Extract flags into the local scope
2794 // This allows callers to set flags such as nowiki, found, etc.
2800 $text = $this->preprocessToDom( $text, $preprocessFlags );
2805 wfProfileOut( __METHOD__
. '-pfunc' );
2808 # Finish mangling title and then check for loops.
2809 # Set $title to a Title object and $titleText to the PDBK
2812 # Split the title into page and subpage
2814 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2815 if ($subpage !== '') {
2816 $ns = $this->mTitle
->getNamespace();
2818 $title = Title
::newFromText( $part1, $ns );
2820 $titleText = $title->getPrefixedText();
2821 # Check for language variants if the template is not found
2822 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2823 $wgContLang->findVariantLink( $part1, $title, true );
2825 # Do recursion depth check
2826 $limit = $this->mOptions
->getMaxTemplateDepth();
2827 if ( $frame->depth
>= $limit ) {
2829 $text = '<span class="error">' . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit ) . '</span>';
2834 # Load from database
2835 if ( !$found && $title ) {
2836 wfProfileIn( __METHOD__
. '-loadtpl' );
2837 if ( !$title->isExternal() ) {
2838 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2839 $text = SpecialPage
::capturePath( $title );
2840 if ( is_string( $text ) ) {
2843 $this->disableCache();
2845 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2846 $found = false; //access denied
2847 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
2849 list( $text, $title ) = $this->getTemplateDom( $title );
2850 if ( $text !== false ) {
2856 # If the title is valid but undisplayable, make a link to it
2857 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2858 $text = "[[:$titleText]]";
2861 } elseif ( $title->isTrans() ) {
2862 // Interwiki transclusion
2863 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
2864 $text = $this->interwikiTransclude( $title, 'render' );
2867 $text = $this->interwikiTransclude( $title, 'raw' );
2868 // Preprocess it like a template
2869 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
2875 # Do infinite loop check
2876 # This has to be done after redirect resolution to avoid infinite loops via redirects
2877 if ( !$frame->loopCheck( $title ) ) {
2879 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
2880 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
2882 wfProfileOut( __METHOD__
. '-loadtpl' );
2885 # If we haven't found text to substitute by now, we're done
2886 # Recover the source wikitext and return it
2888 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2889 wfProfileOut( __METHOD__
);
2890 return array( 'object' => $text );
2893 # Expand DOM-style return values in a child frame
2894 if ( $isChildObj ) {
2895 # Clean up argument array
2896 $newFrame = $frame->newChild( $args, $title );
2899 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
2900 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
2901 # Expansion is eligible for the empty-frame cache
2902 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
2903 $text = $this->mTplExpandCache
[$titleText];
2905 $text = $newFrame->expand( $text );
2906 $this->mTplExpandCache
[$titleText] = $text;
2909 # Uncached expansion
2910 $text = $newFrame->expand( $text );
2913 if ( $isLocalObj && $nowiki ) {
2914 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
2915 $isLocalObj = false;
2918 # Replace raw HTML by a placeholder
2919 # Add a blank line preceding, to prevent it from mucking up
2920 # immediately preceding headings
2922 $text = "\n\n" . $this->insertStripItem( $text );
2924 # Escape nowiki-style return values
2925 elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2926 $text = wfEscapeWikiText( $text );
2928 # Bug 529: if the template begins with a table or block-level
2929 # element, it should be treated as beginning a new line.
2930 # This behaviour is somewhat controversial.
2931 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
2932 $text = "\n" . $text;
2935 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
2936 # Error, oversize inclusion
2937 $text = "[[$originalTitle]]" .
2938 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
2939 $this->limitationWarn( 'post-expand-template-inclusion' );
2942 if ( $isLocalObj ) {
2943 $ret = array( 'object' => $text );
2945 $ret = array( 'text' => $text );
2948 wfProfileOut( __METHOD__
);
2953 * Get the semi-parsed DOM representation of a template with a given title,
2954 * and its redirect destination title. Cached.
2956 function getTemplateDom( $title ) {
2957 $cacheTitle = $title;
2958 $titleText = $title->getPrefixedDBkey();
2960 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
2961 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
2962 $title = Title
::makeTitle( $ns, $dbk );
2963 $titleText = $title->getPrefixedDBkey();
2965 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
2966 return array( $this->mTplDomCache
[$titleText], $title );
2969 // Cache miss, go to the database
2970 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
2972 if ( $text === false ) {
2973 $this->mTplDomCache
[$titleText] = false;
2974 return array( false, $title );
2977 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
2978 $this->mTplDomCache
[ $titleText ] = $dom;
2980 if (! $title->equals($cacheTitle)) {
2981 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
2982 array( $title->getNamespace(),$cdb = $title->getDBkey() );
2985 return array( $dom, $title );
2989 * Fetch the unparsed text of a template and register a reference to it.
2991 function fetchTemplateAndTitle( $title ) {
2992 $templateCb = $this->mOptions
->getTemplateCallback();
2993 $stuff = call_user_func( $templateCb, $title, $this );
2994 $text = $stuff['text'];
2995 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
2996 if ( isset( $stuff['deps'] ) ) {
2997 foreach ( $stuff['deps'] as $dep ) {
2998 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3001 return array($text,$finalTitle);
3004 function fetchTemplate( $title ) {
3005 $rv = $this->fetchTemplateAndTitle($title);
3010 * Static function to get a template
3011 * Can be overridden via ParserOptions::setTemplateCallback().
3013 static function statelessFetchTemplate( $title, $parser=false ) {
3014 $text = $skip = false;
3015 $finalTitle = $title;
3018 // Loop to fetch the article, with up to 1 redirect
3019 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3020 # Give extensions a chance to select the revision instead
3021 $id = false; // Assume current
3022 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3028 'page_id' => $title->getArticleID(),
3032 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3033 $rev_id = $rev ?
$rev->getId() : 0;
3034 // If there is no current revision, there is no page
3035 if( $id === false && !$rev ) {
3036 $linkCache = LinkCache
::singleton();
3037 $linkCache->addBadLinkObj( $title );
3042 'page_id' => $title->getArticleID(),
3043 'rev_id' => $rev_id );
3046 $text = $rev->getText();
3047 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3049 $message = $wgContLang->lcfirst( $title->getText() );
3050 $text = wfMsgForContentNoTrans( $message );
3051 if( wfEmptyMsg( $message, $text ) ) {
3058 if ( $text === false ) {
3062 $finalTitle = $title;
3063 $title = Title
::newFromRedirect( $text );
3067 'finalTitle' => $finalTitle,
3072 * Transclude an interwiki link.
3074 function interwikiTransclude( $title, $action ) {
3075 global $wgEnableScaryTranscluding;
3077 if (!$wgEnableScaryTranscluding)
3078 return wfMsg('scarytranscludedisabled');
3080 $url = $title->getFullUrl( "action=$action" );
3082 if (strlen($url) > 255)
3083 return wfMsg('scarytranscludetoolong');
3084 return $this->fetchScaryTemplateMaybeFromCache($url);
3087 function fetchScaryTemplateMaybeFromCache($url) {
3088 global $wgTranscludeCacheExpiry;
3089 $dbr = wfGetDB(DB_SLAVE
);
3090 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3091 array('tc_url' => $url));
3093 $time = $obj->tc_time
;
3094 $text = $obj->tc_contents
;
3095 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3100 $text = Http
::get($url);
3102 return wfMsg('scarytranscludefailed', $url);
3104 $dbw = wfGetDB(DB_MASTER
);
3105 $dbw->replace('transcache', array('tc_url'), array(
3107 'tc_time' => time(),
3108 'tc_contents' => $text));
3114 * Triple brace replacement -- used for template arguments
3117 function argSubstitution( $piece, $frame ) {
3118 wfProfileIn( __METHOD__
);
3121 $parts = $piece['parts'];
3122 $nameWithSpaces = $frame->expand( $piece['title'] );
3123 $argName = trim( $nameWithSpaces );
3125 $text = $frame->getArgument( $argName );
3126 if ( $text === false && $parts->getLength() > 0
3130 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3133 # No match in frame, use the supplied default
3134 $object = $parts->item( 0 )->getChildren();
3136 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3137 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3138 $this->limitationWarn( 'post-expand-template-argument' );
3141 if ( $text === false && $object === false ) {
3143 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3145 if ( $error !== false ) {
3148 if ( $object !== false ) {
3149 $ret = array( 'object' => $object );
3151 $ret = array( 'text' => $text );
3154 wfProfileOut( __METHOD__
);
3159 * Return the text to be used for a given extension tag.
3160 * This is the ghost of strip().
3162 * @param array $params Associative array of parameters:
3163 * name PPNode for the tag name
3164 * attr PPNode for unparsed text where tag attributes are thought to be
3165 * attributes Optional associative array of parsed attributes
3166 * inner Contents of extension element
3167 * noClose Original text did not have a close tag
3168 * @param PPFrame $frame
3170 function extensionSubstitution( $params, $frame ) {
3171 global $wgRawHtml, $wgContLang;
3173 $name = $frame->expand( $params['name'] );
3174 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3175 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3177 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3179 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3180 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3181 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3182 $name = strtolower( $name );
3183 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3184 if ( isset( $params['attributes'] ) ) {
3185 $attributes = $attributes +
$params['attributes'];
3193 throw new MWException( '<html> extension tag encountered unexpectedly' );
3196 $content = strtr($content, array('-{' => '-{', '}-' => '}-'));
3197 $output = Xml
::escapeTagsOnly( $content );
3200 $output = $wgContLang->armourMath(
3201 MathRenderer
::renderMath( $content, $attributes ) );
3204 $output = $this->renderImageGallery( $content, $attributes );
3207 if( isset( $this->mTagHooks
[$name] ) ) {
3208 # Workaround for PHP bug 35229 and similar
3209 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3210 throw new MWException( "Tag hook for $name is not callable\n" );
3212 $output = call_user_func_array( $this->mTagHooks
[$name],
3213 array( $content, $attributes, $this ) );
3214 } elseif( isset( $this->mFunctionTagHooks
[$name] ) ) {
3215 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3216 if( !is_callable( $callback ) )
3217 throw new MWException( "Tag hook for $name is not callable\n" );
3219 $output = call_user_func_array( $callback,
3220 array( &$this, $frame, $content, $attributes ) );
3222 $output = '<span class="error">Invalid tag extension name: ' .
3223 htmlspecialchars( $name ) . '</span>';
3227 if ( is_null( $attrText ) ) {
3230 if ( isset( $params['attributes'] ) ) {
3231 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3232 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3233 htmlspecialchars( $attrValue ) . '"';
3236 if ( $content === null ) {
3237 $output = "<$name$attrText/>";
3239 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3240 $output = "<$name$attrText>$content$close";
3244 if( $isFunctionTag ) {
3246 } elseif ( $name === 'html' ||
$name === 'nowiki' ) {
3247 $this->mStripState
->nowiki
->setPair( $marker, $output );
3249 $this->mStripState
->general
->setPair( $marker, $output );
3255 * Increment an include size counter
3257 * @param string $type The type of expansion
3258 * @param integer $size The size of the text
3259 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3261 function incrementIncludeSize( $type, $size ) {
3262 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3265 $this->mIncludeSizes
[$type] +
= $size;
3271 * Increment the expensive function count
3273 * @return boolean False if the limit has been exceeded
3275 function incrementExpensiveFunctionCount() {
3276 global $wgExpensiveParserFunctionLimit;
3277 $this->mExpensiveFunctionCount++
;
3278 if($this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit) {
3285 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3286 * Fills $this->mDoubleUnderscores, returns the modified text
3288 function doDoubleUnderscore( $text ) {
3289 wfProfileIn( __METHOD__
);
3290 // The position of __TOC__ needs to be recorded
3291 $mw = MagicWord
::get( 'toc' );
3292 if( $mw->match( $text ) ) {
3293 $this->mShowToc
= true;
3294 $this->mForceTocPosition
= true;
3296 // Set a placeholder. At the end we'll fill it in with the TOC.
3297 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3299 // Only keep the first one.
3300 $text = $mw->replace( '', $text );
3303 // Now match and remove the rest of them
3304 $mwa = MagicWord
::getDoubleUnderscoreArray();
3305 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3307 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3308 $this->mOutput
->mNoGallery
= true;
3310 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3311 $this->mShowToc
= false;
3313 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3314 $this->mOutput
->setProperty( 'hiddencat', 'y' );
3316 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( 'hidden-category-category' ) );
3317 if ( $containerCategory ) {
3318 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3320 wfDebug( __METHOD__
.": [[MediaWiki:hidden-category-category]] is not a valid title!\n" );
3323 # (bug 8068) Allow control over whether robots index a page.
3325 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3326 # is not desirable, the last one on the page should win.
3327 if( isset( $this->mDoubleUnderscores
['noindex'] ) ) {
3328 $this->mOutput
->setIndexPolicy( 'noindex' );
3329 } elseif( isset( $this->mDoubleUnderscores
['index'] ) ) {
3330 $this->mOutput
->setIndexPolicy( 'index' );
3332 wfProfileOut( __METHOD__
);
3337 * This function accomplishes several tasks:
3338 * 1) Auto-number headings if that option is enabled
3339 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3340 * 3) Add a Table of contents on the top for users who have enabled the option
3341 * 4) Auto-anchor headings
3343 * It loops through all headlines, collects the necessary data, then splits up the
3344 * string and re-inserts the newly formatted headlines.
3346 * @param string $text
3347 * @param string $origText Original, untouched wikitext
3348 * @param boolean $isMain
3351 function formatHeadings( $text, $origText, $isMain=true ) {
3352 global $wgMaxTocLevel, $wgContLang, $wgEnforceHtmlIds;
3354 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3355 $showEditLink = $this->mOptions
->getEditSection();
3357 // Do not call quickUserCan unless necessary
3358 if( $showEditLink && !$this->mTitle
->quickUserCan( 'edit' ) ) {
3362 # Inhibit editsection links if requested in the page
3363 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ||
$this->mOptions
->getIsPrintable() ) {
3367 # Get all headlines for numbering them and adding funky stuff like [edit]
3368 # links - this is for later, but we need the number of headlines right now
3370 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3372 # if there are fewer than 4 headlines in the article, do not show TOC
3373 # unless it's been explicitly enabled.
3374 $enoughToc = $this->mShowToc
&&
3375 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3377 # Allow user to stipulate that a page should have a "new section"
3378 # link added via __NEWSECTIONLINK__
3379 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3380 $this->mOutput
->setNewSection( true );
3383 # Allow user to remove the "new section"
3384 # link via __NONEWSECTIONLINK__
3385 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3386 $this->mOutput
->hideNewSection( true );
3389 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3390 # override above conditions and always show TOC above first header
3391 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3392 $this->mShowToc
= true;
3396 # We need this to perform operations on the HTML
3397 $sk = $this->mOptions
->getSkin();
3403 # Ugh .. the TOC should have neat indentation levels which can be
3404 # passed to the skin functions. These are determined here
3408 $sublevelCount = array();
3409 $levelCount = array();
3415 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3416 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3417 $oldType = $this->mOutputType
;
3418 $this->setOutputType( self
::OT_WIKI
);
3419 $frame = $this->getPreprocessor()->newFrame();
3420 $root = $this->preprocessToDom( $origText );
3421 $node = $root->getFirstChild();
3425 foreach( $matches[3] as $headline ) {
3426 $isTemplate = false;
3428 $sectionIndex = false;
3430 $markerMatches = array();
3431 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3432 $serial = $markerMatches[1];
3433 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3434 $isTemplate = ($titleText != $baseTitleText);
3435 $headline = preg_replace("/^$markerRegex/", "", $headline);
3439 $prevlevel = $level;
3440 $prevtoclevel = $toclevel;
3442 $level = $matches[1][$headlineCount];
3444 if ( $level > $prevlevel ) {
3445 # Increase TOC level
3447 $sublevelCount[$toclevel] = 0;
3448 if( $toclevel<$wgMaxTocLevel ) {
3449 $prevtoclevel = $toclevel;
3450 $toc .= $sk->tocIndent();
3454 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3455 # Decrease TOC level, find level to jump to
3457 for ($i = $toclevel; $i > 0; $i--) {
3458 if ( $levelCount[$i] == $level ) {
3459 # Found last matching level
3463 elseif ( $levelCount[$i] < $level ) {
3464 # Found first matching level below current level
3469 if( $i == 0 ) $toclevel = 1;
3470 if( $toclevel<$wgMaxTocLevel ) {
3471 if($prevtoclevel < $wgMaxTocLevel) {
3472 # Unindent only if the previous toc level was shown :p
3473 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3474 $prevtoclevel = $toclevel;
3476 $toc .= $sk->tocLineEnd();
3481 # No change in level, end TOC line
3482 if( $toclevel<$wgMaxTocLevel ) {
3483 $toc .= $sk->tocLineEnd();
3487 $levelCount[$toclevel] = $level;
3489 # count number of headlines for each level
3490 @$sublevelCount[$toclevel]++
;
3492 for( $i = 1; $i <= $toclevel; $i++
) {
3493 if( !empty( $sublevelCount[$i] ) ) {
3497 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3502 # The safe header is a version of the header text safe to use for links
3503 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3504 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3506 # Remove link placeholders by the link text.
3507 # <!--LINK number-->
3509 # link text with suffix
3510 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3512 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3513 $tocline = preg_replace(
3514 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3518 $tocline = trim( $tocline );
3520 # For the anchor, strip out HTML-y stuff period
3521 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3522 $safeHeadline = preg_replace( '/[ _]+/', ' ', $safeHeadline );
3523 $safeHeadline = trim( $safeHeadline );
3525 # Save headline for section edit hint before it's escaped
3526 $headlineHint = $safeHeadline;
3528 if ( $wgEnforceHtmlIds ) {
3529 $legacyHeadline = false;
3530 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
3533 # For reverse compatibility, provide an id that's
3534 # HTML4-compatible, like we used to.
3536 # It may be worth noting, academically, that it's possible for
3537 # the legacy anchor to conflict with a non-legacy headline
3538 # anchor on the page. In this case likely the "correct" thing
3539 # would be to either drop the legacy anchors or make sure
3540 # they're numbered first. However, this would require people
3541 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3542 # manually, so let's not bother worrying about it.
3543 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
3545 $safeHeadline = Sanitizer
::escapeId( $safeHeadline, 'xml' );
3547 if ( $legacyHeadline == $safeHeadline ) {
3548 # No reason to have both (in fact, we can't)
3549 $legacyHeadline = false;
3550 } elseif ( $legacyHeadline != Sanitizer
::escapeId(
3551 $legacyHeadline, 'xml' ) ) {
3552 # The legacy id is invalid XML. We used to allow this, but
3553 # there's no reason to do so anymore. Backward
3554 # compatibility will fail slightly in this case, but it's
3556 $legacyHeadline = false;
3560 # HTML names must be case-insensitively unique (bug 10721). FIXME:
3561 # Does this apply to Unicode characters? Because we aren't
3562 # handling those here.
3563 $arrayKey = strtolower( $safeHeadline );
3564 if ( $legacyHeadline === false ) {
3565 $legacyArrayKey = false;
3567 $legacyArrayKey = strtolower( $legacyHeadline );
3570 # count how many in assoc. array so we can track dupes in anchors
3571 if ( isset( $refers[$arrayKey] ) ) {
3572 $refers[$arrayKey]++
;
3574 $refers[$arrayKey] = 1;
3576 if ( isset( $refers[$legacyArrayKey] ) ) {
3577 $refers[$legacyArrayKey]++
;
3579 $refers[$legacyArrayKey] = 1;
3582 # Don't number the heading if it is the only one (looks silly)
3583 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3584 # the two are different if the line contains a link
3585 $headline=$numbering . ' ' . $headline;
3588 # Create the anchor for linking from the TOC to the section
3589 $anchor = $safeHeadline;
3590 $legacyAnchor = $legacyHeadline;
3591 if ( $refers[$arrayKey] > 1 ) {
3592 $anchor .= '_' . $refers[$arrayKey];
3594 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3595 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3597 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3598 $toc .= $sk->tocLine($anchor, $tocline,
3599 $numbering, $toclevel, ($isTemplate ?
false : $sectionIndex));
3602 # Add the section to the section tree
3603 # Find the DOM node for this header
3604 while ( $node && !$isTemplate ) {
3605 if ( $node->getName() === 'h' ) {
3606 $bits = $node->splitHeading();
3607 if ( $bits['i'] == $sectionIndex )
3610 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
3611 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
3612 $node = $node->getNextSibling();
3615 'toclevel' => $toclevel,
3618 'number' => $numbering,
3619 'index' => ($isTemplate ?
'T-' : '' ) . $sectionIndex,
3620 'fromtitle' => $titleText,
3621 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
3622 'anchor' => $anchor,
3625 # give headline the correct <h#> tag
3626 if( $showEditLink && $sectionIndex !== false ) {
3628 # Put a T flag in the section identifier, to indicate to extractSections()
3629 # that sections inside <includeonly> should be counted.
3630 $editlink = $sk->doEditSectionLink(Title
::newFromText( $titleText ), "T-$sectionIndex");
3632 $editlink = $sk->doEditSectionLink($this->mTitle
, $sectionIndex, $headlineHint);
3637 $head[$headlineCount] = $sk->makeHeadline( $level,
3638 $matches['attrib'][$headlineCount], $anchor, $headline,
3639 $editlink, $legacyAnchor );
3644 $this->setOutputType( $oldType );
3646 # Never ever show TOC if no headers
3647 if( $numVisible < 1 ) {
3652 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3653 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3655 $toc = $sk->tocList( $toc );
3656 $this->mOutput
->setTOCHTML( $toc );
3660 $this->mOutput
->setSections( $tocraw );
3663 # split up and insert constructed headlines
3665 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3668 foreach( $blocks as $block ) {
3669 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3670 # This is the [edit] link that appears for the top block of text when
3671 # section editing is enabled
3673 # Disabled because it broke block formatting
3674 # For example, a bullet point in the top line
3675 # $full .= $sk->editSectionLink(0);
3678 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3679 # Top anchor now in skin
3683 if( !empty( $head[$i] ) ) {
3688 if( $this->mForceTocPosition
) {
3689 return str_replace( '<!--MWTOC-->', $toc, $full );
3696 * Merge $tree2 into $tree1 by replacing the section with index
3697 * $section in $tree1 and its descendants with the sections in $tree2.
3698 * Note that in the returned section tree, only the 'index' and
3699 * 'byteoffset' fields are guaranteed to be correct.
3700 * @param $tree1 array Section tree from ParserOutput::getSectons()
3701 * @param $tree2 array Section tree
3702 * @param $section int Section index
3703 * @param $title Title Title both section trees come from
3704 * @param $len2 int Length of the original wikitext for $tree2
3705 * @return array Merged section tree
3707 public static function mergeSectionTrees( $tree1, $tree2, $section, $title, $len2 ) {
3710 $targetLevel = false;
3714 $numbering = array( 0 );
3715 $titletext = $title->getPrefixedDBkey();
3716 foreach ( $tree1 as $s ) {
3717 if ( $targetLevel !== false ) {
3718 if ( $s['level'] <= $targetLevel )
3719 // We've skipped enough
3720 $targetLevel = false;
3724 if ( $s['index'] != $section ||
3725 $s['fromtitle'] != $titletext ) {
3726 self
::incrementNumbering( $numbering,
3727 $s['toclevel'], $lastLevel );
3729 // Rewrite index, byteoffset and number
3730 if ( $s['fromtitle'] == $titletext ) {
3731 $s['index'] = $nextIndex++
;
3733 $s['byteoffset'] +
= $len2;
3735 $s['number'] = implode( '.', array_map(
3736 array( $wgContLang, 'formatnum' ),
3738 $lastLevel = $s['toclevel'];
3741 // We're at $section
3742 // Insert sections from $tree2 here
3743 foreach ( $tree2 as $s2 ) {
3744 // Rewrite the fields in $s2
3745 // before inserting it
3746 $s2['toclevel'] +
= $s['toclevel'] - 1;
3747 $s2['level'] +
= $s['level'] - 1;
3748 $s2['index'] = $nextIndex++
;
3749 $s2['byteoffset'] +
= $s['byteoffset'];
3751 self
::incrementNumbering( $numbering,
3752 $s2['toclevel'], $lastLevel );
3753 $s2['number'] = implode( '.', array_map(
3754 array( $wgContLang, 'formatnum' ),
3756 $lastLevel = $s2['toclevel'];
3759 // Skip all descendants of $section in $tree1
3760 $targetLevel = $s['level'];
3768 * Increment a section number. Helper function for mergeSectionTrees()
3769 * @param $number array Array representing a section number
3770 * @param $level int Current TOC level (depth)
3771 * @param $lastLevel int Level of previous TOC entry
3773 private static function incrementNumbering( &$number, $level, $lastLevel ) {
3774 if ( $level > $lastLevel )
3775 $number[$level - 1] = 1;
3776 else if ( $level < $lastLevel ) {
3777 foreach ( $number as $key => $unused )
3778 if ( $key >= $level )
3779 unset( $number[$key] );
3780 $number[$level - 1]++
;
3782 $number[$level - 1]++
;
3786 * Transform wiki markup when saving a page by doing \r\n -> \n
3787 * conversion, substitting signatures, {{subst:}} templates, etc.
3789 * @param string $text the text to transform
3790 * @param Title &$title the Title object for the current article
3791 * @param User $user the User object describing the current user
3792 * @param ParserOptions $options parsing options
3793 * @param bool $clearState whether to clear the parser state first
3794 * @return string the altered wiki markup
3797 function preSaveTransform( $text, Title
$title, $user, $options, $clearState = true ) {
3798 $this->mOptions
= $options;
3799 $this->setTitle( $title );
3800 $this->setOutputType( self
::OT_WIKI
);
3802 if ( $clearState ) {
3803 $this->clearState();
3809 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3810 $text = $this->pstPass2( $text, $user );
3811 $text = $this->mStripState
->unstripBoth( $text );
3816 * Pre-save transform helper function
3819 function pstPass2( $text, $user ) {
3820 global $wgContLang, $wgLocaltimezone;
3822 /* Note: This is the timestamp saved as hardcoded wikitext to
3823 * the database, we use $wgContLang here in order to give
3824 * everyone the same signature and use the default one rather
3825 * than the one selected in each user's preferences.
3827 * (see also bug 12815)
3829 $ts = $this->mOptions
->getTimestamp();
3830 $tz = wfMsgForContent( 'timezone-utc' );
3831 if ( isset( $wgLocaltimezone ) ) {
3832 $unixts = wfTimestamp( TS_UNIX
, $ts );
3833 $oldtz = getenv( 'TZ' );
3834 putenv( 'TZ='.$wgLocaltimezone );
3835 $ts = date( 'YmdHis', $unixts );
3836 $tz = date( 'T', $unixts ); # might vary on DST changeover!
3838 /* Allow translation of timezones trough wiki. date() can return
3839 * whatever crap the system uses, localised or not, so we cannot
3840 * ship premade translations.
3842 $key = 'timezone-' . strtolower( trim( $tz ) );
3843 $value = wfMsgForContent( $key );
3844 if ( !wfEmptyMsg( $key, $value ) ) $tz = $value;
3846 putenv( 'TZ='.$oldtz );
3849 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tz)";
3851 # Variable replacement
3852 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3853 $text = $this->replaceVariables( $text );
3856 $sigText = $this->getUserSig( $user );
3857 $text = strtr( $text, array(
3859 '~~~~' => "$sigText $d",
3863 # Context links: [[|name]] and [[name (context)|]]
3865 global $wgLegalTitleChars;
3866 $tc = "[$wgLegalTitleChars]";
3867 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
3869 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3870 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
3871 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3872 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3874 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3875 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3876 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
3877 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3879 $t = $this->mTitle
->getText();
3881 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3882 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3883 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3884 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3886 # if there's no context, don't bother duplicating the title
3887 $text = preg_replace( $p2, '[[\\1]]', $text );
3890 # Trim trailing whitespace
3891 $text = rtrim( $text );
3897 * Fetch the user's signature text, if any, and normalize to
3898 * validated, ready-to-insert wikitext.
3904 function getUserSig( &$user ) {
3905 global $wgMaxSigChars;
3907 $username = $user->getName();
3908 $nickname = $user->getOption( 'nickname' );
3909 $nickname = $nickname === null ?
$username : $nickname;
3911 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3912 $nickname = $username;
3913 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
3914 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3915 # Sig. might contain markup; validate this
3916 if( $this->validateSig( $nickname ) !== false ) {
3917 # Validated; clean up (if needed) and return it
3918 return $this->cleanSig( $nickname, true );
3920 # Failed to validate; fall back to the default
3921 $nickname = $username;
3922 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
3926 // Make sure nickname doesnt get a sig in a sig
3927 $nickname = $this->cleanSigInSig( $nickname );
3929 # If we're still here, make it a link to the user page
3930 $userText = wfEscapeWikiText( $username );
3931 $nickText = wfEscapeWikiText( $nickname );
3932 if ( $user->isAnon() ) {
3933 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
3935 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
3940 * Check that the user's signature contains no bad XML
3942 * @param string $text
3943 * @return mixed An expanded string, or false if invalid.
3945 function validateSig( $text ) {
3946 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
3950 * Clean up signature text
3952 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3953 * 2) Substitute all transclusions
3955 * @param string $text
3956 * @param $parsing Whether we're cleaning (preferences save) or parsing
3957 * @return string Signature text
3959 function cleanSig( $text, $parsing = false ) {
3962 $this->clearState();
3963 $this->setTitle( $wgTitle );
3964 $this->mOptions
= new ParserOptions
;
3965 $this->setOutputType
= self
::OT_PREPROCESS
;
3968 # Option to disable this feature
3969 if ( !$this->mOptions
->getCleanSignatures() ) {
3973 # FIXME: regex doesn't respect extension tags or nowiki
3974 # => Move this logic to braceSubstitution()
3975 $substWord = MagicWord
::get( 'subst' );
3976 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3977 $substText = '{{' . $substWord->getSynonym( 0 );
3979 $text = preg_replace( $substRegex, $substText, $text );
3980 $text = $this->cleanSigInSig( $text );
3981 $dom = $this->preprocessToDom( $text );
3982 $frame = $this->getPreprocessor()->newFrame();
3983 $text = $frame->expand( $dom );
3986 $text = $this->mStripState
->unstripBoth( $text );
3993 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
3994 * @param string $text
3995 * @return string Signature text with /~{3,5}/ removed
3997 function cleanSigInSig( $text ) {
3998 $text = preg_replace( '/~{3,5}/', '', $text );
4003 * Set up some variables which are usually set up in parse()
4004 * so that an external function can call some class members with confidence
4007 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
4008 $this->setTitle( $title );
4009 $this->mOptions
= $options;
4010 $this->setOutputType( $outputType );
4011 if ( $clearState ) {
4012 $this->clearState();
4017 * Wrapper for preprocess()
4019 * @param string $text the text to preprocess
4020 * @param ParserOptions $options options
4024 function transformMsg( $text, $options ) {
4026 static $executing = false;
4028 # Guard against infinite recursion
4034 wfProfileIn(__METHOD__
);
4035 $text = $this->preprocess( $text, $wgTitle, $options );
4038 wfProfileOut(__METHOD__
);
4043 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4044 * The callback should have the following form:
4045 * function myParserHook( $text, $params, &$parser ) { ... }
4047 * Transform and return $text. Use $parser for any required context, e.g. use
4048 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4052 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
4053 * @param mixed $callback The callback function (and object) to use for the tag
4055 * @return The old value of the mTagHooks array associated with the hook
4057 function setHook( $tag, $callback ) {
4058 $tag = strtolower( $tag );
4059 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4060 $this->mTagHooks
[$tag] = $callback;
4061 if( !in_array( $tag, $this->mStripList
) ) {
4062 $this->mStripList
[] = $tag;
4068 function setTransparentTagHook( $tag, $callback ) {
4069 $tag = strtolower( $tag );
4070 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4071 $this->mTransparentTagHooks
[$tag] = $callback;
4077 * Remove all tag hooks
4079 function clearTagHooks() {
4080 $this->mTagHooks
= array();
4081 $this->mStripList
= $this->mDefaultStripList
;
4085 * Create a function, e.g. {{sum:1|2|3}}
4086 * The callback function should have the form:
4087 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4089 * Or with SFH_OBJECT_ARGS:
4090 * function myParserFunction( $parser, $frame, $args ) { ... }
4092 * The callback may either return the text result of the function, or an array with the text
4093 * in element 0, and a number of flags in the other elements. The names of the flags are
4094 * specified in the keys. Valid flags are:
4095 * found The text returned is valid, stop processing the template. This
4097 * nowiki Wiki markup in the return value should be escaped
4098 * isHTML The returned text is HTML, armour it against wikitext transformation
4102 * @param string $id The magic word ID
4103 * @param mixed $callback The callback function (and object) to use
4104 * @param integer $flags a combination of the following flags:
4105 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4107 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4108 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4109 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4110 * the arguments, and to control the way they are expanded.
4112 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4113 * arguments, for instance:
4114 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4116 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4117 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4118 * working if/when this is changed.
4120 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4123 * Please read the documentation in includes/parser/Preprocessor.php for more information
4124 * about the methods available in PPFrame and PPNode.
4126 * @return The old callback function for this name, if any
4128 function setFunctionHook( $id, $callback, $flags = 0 ) {
4131 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4132 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4134 # Add to function cache
4135 $mw = MagicWord
::get( $id );
4137 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4139 $synonyms = $mw->getSynonyms();
4140 $sensitive = intval( $mw->isCaseSensitive() );
4142 foreach ( $synonyms as $syn ) {
4144 if ( !$sensitive ) {
4145 $syn = $wgContLang->lc( $syn );
4148 if ( !( $flags & SFH_NO_HASH
) ) {
4151 # Remove trailing colon
4152 if ( substr( $syn, -1, 1 ) === ':' ) {
4153 $syn = substr( $syn, 0, -1 );
4155 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4161 * Get all registered function hook identifiers
4165 function getFunctionHooks() {
4166 return array_keys( $this->mFunctionHooks
);
4170 * Create a tag function, e.g. <test>some stuff</test>.
4171 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4172 * Unlike parser functions, their content is not preprocessed.
4174 function setFunctionTagHook( $tag, $callback, $flags ) {
4175 $tag = strtolower( $tag );
4176 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4177 $this->mFunctionTagHooks
[$tag] : null;
4178 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4180 if( !in_array( $tag, $this->mStripList
) ) {
4181 $this->mStripList
[] = $tag;
4188 * FIXME: update documentation. makeLinkObj() is deprecated.
4189 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4190 * Placeholders created in Skin::makeLinkObj()
4191 * Returns an array of link CSS classes, indexed by PDBK.
4193 function replaceLinkHolders( &$text, $options = 0 ) {
4194 return $this->mLinkHolders
->replace( $text );
4198 * Replace <!--LINK--> link placeholders with plain text of links
4199 * (not HTML-formatted).
4200 * @param string $text
4203 function replaceLinkHoldersText( $text ) {
4204 return $this->mLinkHolders
->replaceText( $text );
4208 * Tag hook handler for 'pre'.
4210 function renderPreTag( $text, $attribs ) {
4211 // Backwards-compatibility hack
4212 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4214 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4215 return Xml
::openElement( 'pre', $attribs ) .
4216 Xml
::escapeTagsOnly( $content ) .
4221 * Renders an image gallery from a text with one line per image.
4222 * text labels may be given by using |-style alternative text. E.g.
4223 * Image:one.jpg|The number "1"
4224 * Image:tree.jpg|A tree
4225 * given as text will return the HTML of a gallery with two images,
4226 * labeled 'The number "1"' and
4229 function renderImageGallery( $text, $params ) {
4230 $ig = new ImageGallery();
4231 $ig->setContextTitle( $this->mTitle
);
4232 $ig->setShowBytes( false );
4233 $ig->setShowFilename( false );
4234 $ig->setParser( $this );
4235 $ig->setHideBadImages();
4236 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4237 $ig->useSkin( $this->mOptions
->getSkin() );
4238 $ig->mRevisionId
= $this->mRevisionId
;
4240 if( isset( $params['caption'] ) ) {
4241 $caption = $params['caption'];
4242 $caption = htmlspecialchars( $caption );
4243 $caption = $this->replaceInternalLinks( $caption );
4244 $ig->setCaptionHtml( $caption );
4246 if( isset( $params['perrow'] ) ) {
4247 $ig->setPerRow( $params['perrow'] );
4249 if( isset( $params['widths'] ) ) {
4250 $ig->setWidths( $params['widths'] );
4252 if( isset( $params['heights'] ) ) {
4253 $ig->setHeights( $params['heights'] );
4256 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4258 $lines = StringUtils
::explode( "\n", $text );
4259 foreach ( $lines as $line ) {
4260 # match lines like these:
4261 # Image:someimage.jpg|This is some image
4263 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4265 if ( count( $matches ) == 0 ) {
4269 if ( strpos( $matches[0], '%' ) !== false )
4270 $matches[1] = urldecode( $matches[1] );
4271 $tp = Title
::newFromText( $matches[1]/*, NS_FILE*/ );
4273 if( is_null( $nt ) ) {
4274 # Bogus title. Ignore these so we don't bomb out later.
4277 if ( isset( $matches[3] ) ) {
4278 $label = $matches[3];
4283 $html = $this->recursiveTagParse( trim( $label ) );
4285 $ig->add( $nt, $html );
4287 # Only add real images (bug #5586)
4288 if ( $nt->getNamespace() == NS_FILE
) {
4289 $this->mOutput
->addImage( $nt->getDBkey() );
4292 return $ig->toHTML();
4295 function getImageParams( $handler ) {
4297 $handlerClass = get_class( $handler );
4301 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4302 // Initialise static lists
4303 static $internalParamNames = array(
4304 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4305 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4306 'bottom', 'text-bottom' ),
4307 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4308 'upright', 'border', 'link', 'alt' ),
4310 static $internalParamMap;
4311 if ( !$internalParamMap ) {
4312 $internalParamMap = array();
4313 foreach ( $internalParamNames as $type => $names ) {
4314 foreach ( $names as $name ) {
4315 $magicName = str_replace( '-', '_', "img_$name" );
4316 $internalParamMap[$magicName] = array( $type, $name );
4321 // Add handler params
4322 $paramMap = $internalParamMap;
4324 $handlerParamMap = $handler->getParamMap();
4325 foreach ( $handlerParamMap as $magic => $paramName ) {
4326 $paramMap[$magic] = array( 'handler', $paramName );
4329 $this->mImageParams
[$handlerClass] = $paramMap;
4330 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4332 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4336 * Parse image options text and use it to make an image
4337 * @param Title $title
4338 * @param string $options
4339 * @param LinkHolderArray $holders
4341 function makeImage( $title, $options, $holders = false ) {
4342 # Check if the options text is of the form "options|alt text"
4344 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4345 # * left no resizing, just left align. label is used for alt= only
4346 # * right same, but right aligned
4347 # * none same, but not aligned
4348 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4349 # * center center the image
4350 # * frame Keep original image size, no magnify-button.
4351 # * framed Same as "frame"
4352 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4353 # * upright reduce width for upright images, rounded to full __0 px
4354 # * border draw a 1px border around the image
4355 # * alt Text for HTML alt attribute (defaults to empty)
4356 # * link Set the target of the image link. Can be external, interwiki, or local
4357 # vertical-align values (no % or length right now):
4367 $parts = StringUtils
::explode( "|", $options );
4368 $sk = $this->mOptions
->getSkin();
4370 # Give extensions a chance to select the file revision for us
4371 $skip = $time = $descQuery = false;
4372 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4375 return $sk->link( $title );
4379 $imagename = $title->getDBkey();
4380 $file = wfFindFile( $title, array( 'time' => $time ) );
4382 $handler = $file ?
$file->getHandler() : false;
4384 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4386 # Process the input parameters
4388 $params = array( 'frame' => array(), 'handler' => array(),
4389 'horizAlign' => array(), 'vertAlign' => array() );
4390 foreach( $parts as $part ) {
4391 $part = trim( $part );
4392 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4394 if( isset( $paramMap[$magicName] ) ) {
4395 list( $type, $paramName ) = $paramMap[$magicName];
4397 // Special case; width and height come in one variable together
4398 if( $type === 'handler' && $paramName === 'width' ) {
4400 # (bug 13500) In both cases (width/height and width only),
4401 # permit trailing "px" for backward compatibility.
4402 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4403 $width = intval( $m[1] );
4404 $height = intval( $m[2] );
4405 if ( $handler->validateParam( 'width', $width ) ) {
4406 $params[$type]['width'] = $width;
4409 if ( $handler->validateParam( 'height', $height ) ) {
4410 $params[$type]['height'] = $height;
4413 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4414 $width = intval( $value );
4415 if ( $handler->validateParam( 'width', $width ) ) {
4416 $params[$type]['width'] = $width;
4419 } // else no validation -- bug 13436
4421 if ( $type === 'handler' ) {
4422 # Validate handler parameter
4423 $validated = $handler->validateParam( $paramName, $value );
4425 # Validate internal parameters
4426 switch( $paramName ) {
4429 // @fixme - possibly check validity here for
4430 // manualthumb? downstream behavior seems odd with
4431 // missing manual thumbs.
4433 $value = $this->stripAltText( $value, $holders );
4436 $chars = self
::EXT_LINK_URL_CLASS
;
4437 $prots = $this->mUrlProtocols
;
4438 if ( $value === '' ) {
4439 $paramName = 'no-link';
4442 } elseif ( preg_match( "/^$prots/", $value ) ) {
4443 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4444 $paramName = 'link-url';
4445 $this->mOutput
->addExternalLink( $value );
4449 $linkTitle = Title
::newFromText( $value );
4451 $paramName = 'link-title';
4452 $value = $linkTitle;
4453 $this->mOutput
->addLink( $linkTitle );
4459 // Most other things appear to be empty or numeric...
4460 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4465 $params[$type][$paramName] = $value;
4469 if ( !$validated ) {
4474 # Process alignment parameters
4475 if ( $params['horizAlign'] ) {
4476 $params['frame']['align'] = key( $params['horizAlign'] );
4478 if ( $params['vertAlign'] ) {
4479 $params['frame']['valign'] = key( $params['vertAlign'] );
4482 $params['frame']['caption'] = $caption;
4484 # Will the image be presented in a frame, with the caption below?
4485 $imageIsFramed = isset( $params['frame']['frame'] ) ||
4486 isset( $params['frame']['framed'] ) ||
4487 isset( $params['frame']['thumbnail'] ) ||
4488 isset( $params['frame']['manualthumb'] );
4490 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4491 # came to also set the caption, ordinary text after the image -- which
4492 # makes no sense, because that just repeats the text multiple times in
4493 # screen readers. It *also* came to set the title attribute.
4495 # Now that we have an alt attribute, we should not set the alt text to
4496 # equal the caption: that's worse than useless, it just repeats the
4497 # text. This is the framed/thumbnail case. If there's no caption, we
4498 # use the unnamed parameter for alt text as well, just for the time be-
4499 # ing, if the unnamed param is set and the alt param is not.
4501 # For the future, we need to figure out if we want to tweak this more,
4502 # e.g., introducing a title= parameter for the title; ignoring the un-
4503 # named parameter entirely for images without a caption; adding an ex-
4504 # plicit caption= parameter and preserving the old magic unnamed para-
4506 if ( $imageIsFramed ) { # Framed image
4507 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
4508 # No caption or alt text, add the filename as the alt text so
4509 # that screen readers at least get some description of the image
4510 $params['frame']['alt'] = $title->getText();
4512 # Do not set $params['frame']['title'] because tooltips don't make sense
4514 } else { # Inline image
4515 if ( !isset( $params['frame']['alt'] ) ) {
4516 # No alt text, use the "caption" for the alt text
4517 if ( $caption !== '') {
4518 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
4520 # No caption, fall back to using the filename for the
4522 $params['frame']['alt'] = $title->getText();
4525 # Use the "caption" for the tooltip text
4526 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4529 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4531 # Linker does the rest
4532 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4534 # Give the handler a chance to modify the parser object
4536 $handler->parserTransformHook( $this, $file );
4542 protected function stripAltText( $caption, $holders ) {
4543 # Strip bad stuff out of the title (tooltip). We can't just use
4544 # replaceLinkHoldersText() here, because if this function is called
4545 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4547 $tooltip = $holders->replaceText( $caption );
4549 $tooltip = $this->replaceLinkHoldersText( $caption );
4552 # make sure there are no placeholders in thumbnail attributes
4553 # that are later expanded to html- so expand them now and
4555 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
4556 $tooltip = Sanitizer
::stripAllTags( $tooltip );
4562 * Set a flag in the output object indicating that the content is dynamic and
4563 * shouldn't be cached.
4565 function disableCache() {
4566 wfDebug( "Parser output marked as uncacheable.\n" );
4567 $this->mOutput
->mCacheTime
= -1;
4571 * Callback from the Sanitizer for expanding items found in HTML attribute
4572 * values, so they can be safely tested and escaped.
4573 * @param string $text
4574 * @param PPFrame $frame
4578 function attributeStripCallback( &$text, $frame = false ) {
4579 $text = $this->replaceVariables( $text, $frame );
4580 $text = $this->mStripState
->unstripBoth( $text );
4589 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4590 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4591 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4597 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4602 * Break wikitext input into sections, and either pull or replace
4603 * some particular section's text.
4605 * External callers should use the getSection and replaceSection methods.
4607 * @param string $text Page wikitext
4608 * @param string $section A section identifier string of the form:
4609 * <flag1> - <flag2> - ... - <section number>
4611 * Currently the only recognised flag is "T", which means the target section number
4612 * was derived during a template inclusion parse, in other words this is a template
4613 * section edit link. If no flags are given, it was an ordinary section edit link.
4614 * This flag is required to avoid a section numbering mismatch when a section is
4615 * enclosed by <includeonly> (bug 6563).
4617 * The section number 0 pulls the text before the first heading; other numbers will
4618 * pull the given section along with its lower-level subsections. If the section is
4619 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4621 * @param string $mode One of "get" or "replace"
4622 * @param string $newText Replacement text for section data.
4623 * @return string for "get", the extracted section text.
4624 * for "replace", the whole page with the section replaced.
4626 private function extractSections( $text, $section, $mode, $newText='' ) {
4628 $this->clearState();
4629 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4630 $this->mOptions
= new ParserOptions
;
4631 $this->setOutputType( self
::OT_WIKI
);
4633 $frame = $this->getPreprocessor()->newFrame();
4635 // Process section extraction flags
4637 $sectionParts = explode( '-', $section );
4638 $sectionIndex = array_pop( $sectionParts );
4639 foreach ( $sectionParts as $part ) {
4640 if ( $part === 'T' ) {
4641 $flags |
= self
::PTD_FOR_INCLUSION
;
4644 // Preprocess the text
4645 $root = $this->preprocessToDom( $text, $flags );
4647 // <h> nodes indicate section breaks
4648 // They can only occur at the top level, so we can find them by iterating the root's children
4649 $node = $root->getFirstChild();
4651 // Find the target section
4652 if ( $sectionIndex == 0 ) {
4653 // Section zero doesn't nest, level=big
4654 $targetLevel = 1000;
4657 if ( $node->getName() === 'h' ) {
4658 $bits = $node->splitHeading();
4659 if ( $bits['i'] == $sectionIndex ) {
4660 $targetLevel = $bits['level'];
4664 if ( $mode === 'replace' ) {
4665 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4667 $node = $node->getNextSibling();
4673 if ( $mode === 'get' ) {
4680 // Find the end of the section, including nested sections
4682 if ( $node->getName() === 'h' ) {
4683 $bits = $node->splitHeading();
4684 $curLevel = $bits['level'];
4685 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4689 if ( $mode === 'get' ) {
4690 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4692 $node = $node->getNextSibling();
4695 // Write out the remainder (in replace mode only)
4696 if ( $mode === 'replace' ) {
4697 // Output the replacement text
4698 // Add two newlines on -- trailing whitespace in $newText is conventionally
4699 // stripped by the editor, so we need both newlines to restore the paragraph gap
4700 // Only add trailing whitespace if there is newText
4701 if($newText != "") {
4702 $outText .= $newText . "\n\n";
4706 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4707 $node = $node->getNextSibling();
4711 if ( is_string( $outText ) ) {
4712 // Re-insert stripped tags
4713 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4720 * This function returns the text of a section, specified by a number ($section).
4721 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4722 * the first section before any such heading (section 0).
4724 * If a section contains subsections, these are also returned.
4726 * @param string $text text to look in
4727 * @param string $section section identifier
4728 * @param string $deftext default to return if section is not found
4729 * @return string text of the requested section
4731 public function getSection( $text, $section, $deftext='' ) {
4732 return $this->extractSections( $text, $section, "get", $deftext );
4735 public function replaceSection( $oldtext, $section, $text ) {
4736 return $this->extractSections( $oldtext, $section, "replace", $text );
4740 * Get the timestamp associated with the current revision, adjusted for
4741 * the default server-local timestamp
4743 function getRevisionTimestamp() {
4744 if ( is_null( $this->mRevisionTimestamp
) ) {
4745 wfProfileIn( __METHOD__
);
4747 $dbr = wfGetDB( DB_SLAVE
);
4748 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4749 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4751 // Normalize timestamp to internal MW format for timezone processing.
4752 // This has the added side-effect of replacing a null value with
4753 // the current time, which gives us more sensible behavior for
4755 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4757 // The cryptic '' timezone parameter tells to use the site-default
4758 // timezone offset instead of the user settings.
4760 // Since this value will be saved into the parser cache, served
4761 // to other users, and potentially even used inside links and such,
4762 // it needs to be consistent for all visitors.
4763 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4765 wfProfileOut( __METHOD__
);
4767 return $this->mRevisionTimestamp
;
4771 * Get the name of the user that edited the last revision
4773 function getRevisionUser() {
4774 // if this template is subst: the revision id will be blank,
4775 // so just use the current user's name
4776 if( $this->mRevisionId
) {
4777 $revision = Revision
::newFromId( $this->mRevisionId
);
4778 $revuser = $revision->getUserText();
4781 $revuser = $wgUser->getName();
4787 * Mutator for $mDefaultSort
4789 * @param $sort New value
4791 public function setDefaultSort( $sort ) {
4792 $this->mDefaultSort
= $sort;
4796 * Accessor for $mDefaultSort
4797 * Will use the title/prefixed title if none is set
4801 public function getDefaultSort() {
4802 global $wgCategoryPrefixedDefaultSortkey;
4803 if( $this->mDefaultSort
!== false ) {
4804 return $this->mDefaultSort
;
4805 } elseif ($this->mTitle
->getNamespace() == NS_CATEGORY ||
4806 !$wgCategoryPrefixedDefaultSortkey) {
4807 return $this->mTitle
->getText();
4809 return $this->mTitle
->getPrefixedText();
4814 * Accessor for $mDefaultSort
4815 * Unlike getDefaultSort(), will return false if none is set
4817 * @return string or false
4819 public function getCustomDefaultSort() {
4820 return $this->mDefaultSort
;
4824 * Try to guess the section anchor name based on a wikitext fragment
4825 * presumably extracted from a heading, for example "Header" from
4828 public function guessSectionNameFromWikiText( $text ) {
4829 # Strip out wikitext links(they break the anchor)
4830 $text = $this->stripSectionName( $text );
4831 $headline = Sanitizer
::decodeCharReferences( $text );
4833 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
4834 $headline = trim( $headline );
4835 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4836 $replacearray = array(
4841 array_keys( $replacearray ),
4842 array_values( $replacearray ),
4847 * Strips a text string of wikitext for use in a section anchor
4849 * Accepts a text string and then removes all wikitext from the
4850 * string and leaves only the resultant text (i.e. the result of
4851 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4852 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4853 * to create valid section anchors by mimicing the output of the
4854 * parser when headings are parsed.
4856 * @param $text string Text string to be stripped of wikitext
4857 * for use in a Section anchor
4858 * @return Filtered text string
4860 public function stripSectionName( $text ) {
4861 # Strip internal link markup
4862 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4863 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4865 # Strip external link markup (FIXME: Not Tolerant to blank link text
4866 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4867 # on how many empty links there are on the page - need to figure that out.
4868 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4870 # Parse wikitext quotes (italics & bold)
4871 $text = $this->doQuotes($text);
4874 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
4878 function srvus( $text ) {
4879 return $this->testSrvus( $text, $this->mOutputType
);
4883 * strip/replaceVariables/unstrip for preprocessor regression testing
4885 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
4886 $this->clearState();
4887 if ( ! ( $title instanceof Title
) ) {
4888 $title = Title
::newFromText( $title );
4890 $this->mTitle
= $title;
4891 $this->mOptions
= $options;
4892 $this->setOutputType( $outputType );
4893 $text = $this->replaceVariables( $text );
4894 $text = $this->mStripState
->unstripBoth( $text );
4895 $text = Sanitizer
::removeHTMLtags( $text );
4899 function testPst( $text, $title, $options ) {
4901 if ( ! ( $title instanceof Title
) ) {
4902 $title = Title
::newFromText( $title );
4904 return $this->preSaveTransform( $text, $title, $wgUser, $options );
4907 function testPreprocess( $text, $title, $options ) {
4908 if ( ! ( $title instanceof Title
) ) {
4909 $title = Title
::newFromText( $title );
4911 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
4914 function markerSkipCallback( $s, $callback ) {
4917 while ( $i < strlen( $s ) ) {
4918 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
4919 if ( $markerStart === false ) {
4920 $out .= call_user_func( $callback, substr( $s, $i ) );
4923 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
4924 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
4925 if ( $markerEnd === false ) {
4926 $out .= substr( $s, $markerStart );
4929 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
4930 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
4938 function serialiseHalfParsedText( $text ) {
4940 $data['text'] = $text;
4942 // First, find all strip markers, and store their
4943 // data in an array.
4944 $stripState = new StripState
;
4946 while( ( $start_pos = strpos( $text, $this->mUniqPrefix
, $pos ) ) && ( $end_pos = strpos( $text, self
::MARKER_SUFFIX
, $pos ) ) ) {
4947 $end_pos +
= strlen( self
::MARKER_SUFFIX
);
4948 $marker = substr( $text, $start_pos, $end_pos-$start_pos );
4950 if ( !empty( $this->mStripState
->general
->data
[$marker] ) ) {
4951 $replaceArray = $stripState->general
;
4952 $stripText = $this->mStripState
->general
->data
[$marker];
4953 } elseif ( !empty( $this->mStripState
->nowiki
->data
[$marker] ) ) {
4954 $replaceArray = $stripState->nowiki
;
4955 $stripText = $this->mStripState
->nowiki
->data
[$marker];
4957 throw new MWException( "Hanging strip marker: '$marker'." );
4960 $replaceArray->setPair( $marker, $stripText );
4963 $data['stripstate'] = $stripState;
4965 // Now, find all of our links, and store THEIR
4966 // data in an array! :)
4967 $links = array( 'internal' => array(), 'interwiki' => array() );
4971 while( ( $start_pos = strpos( $text, '<!--LINK ', $pos ) ) ) {
4972 list( $ns, $trail ) = explode( ':', substr( $text, $start_pos +
strlen( '<!--LINK ' ) ), 2 );
4975 if (empty( $links['internal'][$ns] )) {
4976 $links['internal'][$ns] = array();
4979 $key = trim( substr( $trail, 0, strpos( $trail, '-->' ) ) );
4980 $links['internal'][$ns][] = $this->mLinkHolders
->internals
[$ns][$key];
4981 $pos = $start_pos +
strlen( "<!--LINK $ns:$key-->" );
4987 while( ( $start_pos = strpos( $text, '<!--IWLINK ', $pos ) ) ) {
4988 $data = substr( $text, $start_pos );
4989 $key = trim( substr( $data, 0, strpos( $data, '-->' ) ) );
4990 $links['interwiki'][] = $this->mLinkHolders
->interwiki
[$key];
4991 $pos = $start_pos +
strlen( "<!--IWLINK $key-->" );
4994 $data['linkholder'] = $links;
4999 function unserialiseHalfParsedText( $data, $intPrefix = null /* Unique identifying prefix */ ) {
5001 $intPrefix = $this->getRandomString();
5003 // First, extract the strip state.
5004 $stripState = $data['stripstate'];
5005 $this->mStripState
->general
->merge( $stripState->general
);
5006 $this->mStripState
->nowiki
->merge( $stripState->nowiki
);
5008 // Now, extract the text, and renumber links
5009 $text = $data['text'];
5010 $links = $data['linkholder'];
5013 foreach( $links['internal'] as $ns => $nsLinks ) {
5014 foreach( $nsLinks as $key => $entry ) {
5015 $newKey = $intPrefix . '-' . $key;
5016 $this->mLinkHolders
->internals
[$ns][$newKey] = $entry;
5018 $text = str_replace( "<!--LINK $ns:$key-->", "<!--LINK $ns:$newKey-->", $text );
5023 foreach( $links['interwiki'] as $key => $entry ) {
5024 $newKey = "$intPrefix-$key";
5025 $this->mLinkHolders
->interwikis
[$newKey] = $entry;
5027 $text = str_replace( "<!--IWLINK $key-->", "<!--IWLINK $newKey-->", $text );
5030 // Should be good to go.
5036 * @todo document, briefly.
5040 var $general, $nowiki;
5042 function __construct() {
5043 $this->general
= new ReplacementArray
;
5044 $this->nowiki
= new ReplacementArray
;
5047 function unstripGeneral( $text ) {
5048 wfProfileIn( __METHOD__
);
5051 $text = $this->general
->replace( $text );
5052 } while ( $text !== $oldText );
5053 wfProfileOut( __METHOD__
);
5057 function unstripNoWiki( $text ) {
5058 wfProfileIn( __METHOD__
);
5061 $text = $this->nowiki
->replace( $text );
5062 } while ( $text !== $oldText );
5063 wfProfileOut( __METHOD__
);
5067 function unstripBoth( $text ) {
5068 wfProfileIn( __METHOD__
);
5071 $text = $this->general
->replace( $text );
5072 $text = $this->nowiki
->replace( $text );
5073 } while ( $text !== $oldText );
5074 wfProfileOut( __METHOD__
);
5080 * @todo document, briefly.
5083 class OnlyIncludeReplacer
{
5086 function replace( $matches ) {
5087 if ( substr( $matches[1], -1 ) === "\n" ) {
5088 $this->output
.= substr( $matches[1], 0, -1 );
5090 $this->output
.= $matches[1];