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
110 # These are variables reset at least once per parse regardless of $clearState
111 var $mOptions, // ParserOptions object
112 $mTitle, // Title context, used for self-link rendering and similar things
113 $mOutputType, // Output type, one of the OT_xxx constants
114 $ot, // Shortcut alias, see setOutputType()
115 $mRevisionId, // ID to display in {{REVISIONID}} tags
116 $mRevisionTimestamp, // The timestamp of the specified revision ID
117 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
126 function __construct( $conf = array() ) {
127 $this->mConf
= $conf;
128 $this->mTagHooks
= array();
129 $this->mTransparentTagHooks
= array();
130 $this->mFunctionHooks
= array();
131 $this->mFunctionTagHooks
= array();
132 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
133 $this->mDefaultStripList
= $this->mStripList
= array( 'nowiki', 'gallery' );
134 $this->mUrlProtocols
= wfUrlProtocols();
135 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
136 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
137 $this->mVarCache
= array();
138 if ( isset( $conf['preprocessorClass'] ) ) {
139 $this->mPreprocessorClass
= $conf['preprocessorClass'];
140 } elseif ( extension_loaded( 'domxml' ) ) {
141 // PECL extension that conflicts with the core DOM extension (bug 13770)
142 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
143 $this->mPreprocessorClass
= 'Preprocessor_Hash';
144 } elseif ( extension_loaded( 'dom' ) ) {
145 $this->mPreprocessorClass
= 'Preprocessor_DOM';
147 $this->mPreprocessorClass
= 'Preprocessor_Hash';
149 $this->mMarkerIndex
= 0;
150 $this->mFirstCall
= true;
154 * Reduce memory usage to reduce the impact of circular references
156 function __destruct() {
157 if ( isset( $this->mLinkHolders
) ) {
158 $this->mLinkHolders
->__destruct();
160 foreach ( $this as $name => $value ) {
161 unset( $this->$name );
166 * Do various kinds of initialisation on the first call of the parser
168 function firstCallInit() {
169 if ( !$this->mFirstCall
) {
172 $this->mFirstCall
= false;
174 wfProfileIn( __METHOD__
);
176 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
177 CoreParserFunctions
::register( $this );
178 $this->initialiseVariables();
180 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
181 wfProfileOut( __METHOD__
);
189 function clearState() {
190 wfProfileIn( __METHOD__
);
191 if ( $this->mFirstCall
) {
192 $this->firstCallInit();
194 $this->mOutput
= new ParserOutput
;
195 $this->mAutonumber
= 0;
196 $this->mLastSection
= '';
197 $this->mDTopen
= false;
198 $this->mIncludeCount
= array();
199 $this->mStripState
= new StripState
;
200 $this->mArgStack
= false;
201 $this->mInPre
= false;
202 $this->mLinkHolders
= new LinkHolderArray( $this );
204 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
207 * Prefix for temporary replacement strings for the multipass parser.
208 * \x07 should never appear in input as it's disallowed in XML.
209 * Using it at the front also gives us a little extra robustness
210 * since it shouldn't match when butted up against identifier-like
213 * Must not consist of all title characters, or else it will change
214 * the behaviour of <nowiki> in a link.
216 #$this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
217 # Changed to \x7f to allow XML double-parsing -- TS
218 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
221 # Clear these on every parse, bug 4549
222 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
224 $this->mShowToc
= true;
225 $this->mForceTocPosition
= false;
226 $this->mIncludeSizes
= array(
230 $this->mPPNodeCount
= 0;
231 $this->mDefaultSort
= false;
232 $this->mHeadings
= array();
233 $this->mDoubleUnderscores
= array();
234 $this->mExpensiveFunctionCount
= 0;
235 $this->mFileCache
= array();
238 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
239 $this->mPreprocessor
= null;
242 wfRunHooks( 'ParserClearState', array( &$this ) );
243 wfProfileOut( __METHOD__
);
246 function setOutputType( $ot ) {
247 $this->mOutputType
= $ot;
250 'html' => $ot == self
::OT_HTML
,
251 'wiki' => $ot == self
::OT_WIKI
,
252 'pre' => $ot == self
::OT_PREPROCESS
,
257 * Set the context title
259 function setTitle( $t ) {
260 if ( !$t ||
$t instanceof FakeTitle
) {
261 $t = Title
::newFromText( 'NO TITLE' );
263 if ( strval( $t->getFragment() ) !== '' ) {
264 # Strip the fragment to avoid various odd effects
265 $this->mTitle
= clone $t;
266 $this->mTitle
->setFragment( '' );
273 * Accessor for mUniqPrefix.
277 function uniqPrefix() {
278 if( !isset( $this->mUniqPrefix
) ) {
279 // @fixme this is probably *horribly wrong*
280 // LanguageConverter seems to want $wgParser's uniqPrefix, however
281 // if this is called for a parser cache hit, the parser may not
282 // have ever been initialized in the first place.
283 // Not really sure what the heck is supposed to be going on here.
285 //throw new MWException( "Accessing uninitialized mUniqPrefix" );
287 return $this->mUniqPrefix
;
291 * Convert wikitext to HTML
292 * Do not call this function recursively.
294 * @param $text String: text we want to parse
295 * @param $title A title object
296 * @param $options ParserOptions
297 * @param $linestart boolean
298 * @param $clearState boolean
299 * @param $revid Int: number to pass in {{REVISIONID}}
300 * @return ParserOutput a ParserOutput
302 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
304 * First pass--just handle <nowiki> sections, pass the rest off
305 * to internalParse() which does all the real work.
308 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
309 $fname = __METHOD__
.'-' . wfGetCaller();
310 wfProfileIn( __METHOD__
);
311 wfProfileIn( $fname );
317 $this->mOptions
= $options;
318 $this->setTitle( $title );
319 $oldRevisionId = $this->mRevisionId
;
320 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
321 if( $revid !== null ) {
322 $this->mRevisionId
= $revid;
323 $this->mRevisionTimestamp
= null;
325 $this->setOutputType( self
::OT_HTML
);
326 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
328 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
329 $text = $this->internalParse( $text );
330 $text = $this->mStripState
->unstripGeneral( $text );
332 # Clean up special characters, only run once, next-to-last before doBlockLevels
334 # french spaces, last one Guillemet-left
335 # only if there is something before the space
336 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
337 # french spaces, Guillemet-right
338 '/(\\302\\253) /' => '\\1 ',
339 '/ (!\s*important)/' => ' \\1', #Beware of CSS magic word !important, bug #11874.
341 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
343 $text = $this->doBlockLevels( $text, $linestart );
345 $this->replaceLinkHolders( $text );
347 # the position of the parserConvert() call should not be changed. it
348 # assumes that the links are all replaced and the only thing left
349 # is the <nowiki> mark.
350 # Side-effects: this calls $this->mOutput->setTitleText()
351 $text = $wgContLang->parserConvert( $text, $this );
353 $text = $this->mStripState
->unstripNoWiki( $text );
355 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
357 //!JF Move to its own function
359 $uniq_prefix = $this->mUniqPrefix
;
361 $elements = array_keys( $this->mTransparentTagHooks
);
362 $text = self
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
364 foreach( $matches as $marker => $data ) {
365 list( $element, $content, $params, $tag ) = $data;
366 $tagName = strtolower( $element );
367 if( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
368 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName],
369 array( $content, $params, $this ) );
373 $this->mStripState
->general
->setPair( $marker, $output );
375 $text = $this->mStripState
->unstripGeneral( $text );
377 $text = Sanitizer
::normalizeCharReferences( $text );
379 if ( ( $wgUseTidy && $this->mOptions
->mTidy
) ||
$wgAlwaysUseTidy ) {
380 $text = MWTidy
::tidy( $text );
382 # attempt to sanitize at least some nesting problems
383 # (bug #2702 and quite a few others)
385 # ''Something [http://www.cool.com cool''] -->
386 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
387 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
388 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
389 # fix up an anchor inside another anchor, only
390 # at least for a single single nested link (bug 3695)
391 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
392 '\\1\\2</a>\\3</a>\\1\\4</a>',
393 # fix div inside inline elements- doBlockLevels won't wrap a line which
394 # contains a div, so fix it up here; replace
395 # div with escaped text
396 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
397 '\\1\\3<div\\5>\\6</div>\\8\\9',
398 # remove empty italic or bold tag pairs, some
399 # introduced by rules above
400 '/<([bi])><\/\\1>/' => '',
403 $text = preg_replace(
404 array_keys( $tidyregs ),
405 array_values( $tidyregs ),
408 global $wgExpensiveParserFunctionLimit;
409 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
410 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
413 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
415 # Information on include size limits, for the benefit of users who try to skirt them
416 if ( $this->mOptions
->getEnableLimitReport() ) {
417 global $wgExpensiveParserFunctionLimit;
418 $max = $this->mOptions
->getMaxIncludeSize();
419 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
421 "NewPP limit report\n" .
422 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
423 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
424 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
426 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
427 $text .= "\n<!-- \n$limitReport-->\n";
429 $this->mOutput
->setText( $text );
430 $this->mRevisionId
= $oldRevisionId;
431 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
432 wfProfileOut( $fname );
433 wfProfileOut( __METHOD__
);
435 return $this->mOutput
;
439 * Recursive parser entry point that can be called from an extension tag
442 function recursiveTagParse( $text ) {
443 wfProfileIn( __METHOD__
);
444 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
445 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
446 $text = $this->internalParse( $text, false );
447 wfProfileOut( __METHOD__
);
452 * Expand templates and variables in the text, producing valid, static wikitext.
453 * Also removes comments.
455 function preprocess( $text, $title, $options, $revid = null ) {
456 wfProfileIn( __METHOD__
);
458 $this->setOutputType( self
::OT_PREPROCESS
);
459 $this->mOptions
= $options;
460 $this->setTitle( $title );
461 if( $revid !== null ) {
462 $this->mRevisionId
= $revid;
464 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
465 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
466 $text = $this->replaceVariables( $text );
467 $text = $this->mStripState
->unstripBoth( $text );
468 wfProfileOut( __METHOD__
);
473 * Get a random string
478 function getRandomString() {
479 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
482 function &getTitle() { return $this->mTitle
; }
483 function getOptions() { return $this->mOptions
; }
484 function getRevisionId() { return $this->mRevisionId
; }
485 function getOutput() { return $this->mOutput
; }
486 function nextLinkID() { return $this->mLinkID++
; }
488 function getFunctionLang() {
489 global $wgLang, $wgContLang;
491 $target = $this->mOptions
->getTargetLanguage();
492 if ( $target !== null ) {
495 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
500 * Get a preprocessor object
502 function getPreprocessor() {
503 if ( !isset( $this->mPreprocessor
) ) {
504 $class = $this->mPreprocessorClass
;
505 $this->mPreprocessor
= new $class( $this );
507 return $this->mPreprocessor
;
511 * Replaces all occurrences of HTML-style comments and the given tags
512 * in the text with a random marker and returns the next text. The output
513 * parameter $matches will be an associative array filled with data in
515 * 'UNIQ-xxxxx' => array(
518 * array( 'param' => 'x' ),
519 * '<element param="x">tag content</element>' ) )
521 * @param $elements list of element names. Comments are always extracted.
522 * @param $text Source text string.
523 * @param $uniq_prefix
528 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
533 $taglist = implode( '|', $elements );
534 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?>)|<(!--)/i";
536 while ( '' != $text ) {
537 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
539 if( count( $p ) < 5 ) {
542 if( count( $p ) > 5 ) {
556 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . self
::MARKER_SUFFIX
;
557 $stripped .= $marker;
559 if ( $close === '/>' ) {
560 // Empty element tag, <tag />
565 if( $element === '!--' ) {
568 $end = "/(<\\/$element\\s*>)/i";
570 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
572 if( count( $q ) < 3 ) {
573 # No end tag -- let it run out to the end of the text.
582 $matches[$marker] = array( $element,
584 Sanitizer
::decodeTagAttributes( $attributes ),
585 "<$element$attributes$close$content$tail" );
591 * Get a list of strippable XML-like elements
593 function getStripList() {
595 $elements = $this->mStripList
;
597 $elements[] = 'html';
599 if( $this->mOptions
->getUseTeX() ) {
600 $elements[] = 'math';
606 * @deprecated use replaceVariables
608 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
613 * Restores pre, math, and other extensions removed by strip()
615 * always call unstripNoWiki() after this one
617 * @deprecated use $this->mStripState->unstrip()
619 function unstrip( $text, $state ) {
620 return $state->unstripGeneral( $text );
624 * Always call this after unstrip() to preserve the order
627 * @deprecated use $this->mStripState->unstrip()
629 function unstripNoWiki( $text, $state ) {
630 return $state->unstripNoWiki( $text );
634 * @deprecated use $this->mStripState->unstripBoth()
636 function unstripForHTML( $text ) {
637 return $this->mStripState
->unstripBoth( $text );
641 * Add an item to the strip state
642 * Returns the unique tag which must be inserted into the stripped text
643 * The tag will be replaced with the original text in unstrip()
647 function insertStripItem( $text ) {
648 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
649 $this->mMarkerIndex++
;
650 $this->mStripState
->general
->setPair( $rnd, $text );
655 * Interface with html tidy
656 * @deprecated Use MWTidy::tidy()
658 public static function tidy( $text ) {
659 wfDeprecated( __METHOD__
);
660 return MWTidy
::tidy( $text );
664 * parse the wiki syntax used to render tables
668 function doTableStuff ( $text ) {
669 wfProfileIn( __METHOD__
);
671 $lines = StringUtils
::explode( "\n", $text );
673 $td_history = array (); // Is currently a td tag open?
674 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
675 $tr_history = array (); // Is currently a tr tag open?
676 $tr_attributes = array (); // history of tr attributes
677 $has_opened_tr = array(); // Did this table open a <tr> element?
678 $indent_level = 0; // indent level of the table
680 foreach ( $lines as $outLine ) {
681 $line = trim( $outLine );
683 if( $line == '' ) { // empty line, go to next line
684 $out .= $outLine."\n";
687 $first_character = $line[0];
690 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
691 // First check if we are starting a new table
692 $indent_level = strlen( $matches[1] );
694 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
695 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
697 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
698 array_push ( $td_history , false );
699 array_push ( $last_tag_history , '' );
700 array_push ( $tr_history , false );
701 array_push ( $tr_attributes , '' );
702 array_push ( $has_opened_tr , false );
703 } else if ( count ( $td_history ) == 0 ) {
704 // Don't do any of the following
705 $out .= $outLine."\n";
707 } else if ( substr ( $line , 0 , 2 ) === '|}' ) {
708 // We are ending a table
709 $line = '</table>' . substr ( $line , 2 );
710 $last_tag = array_pop ( $last_tag_history );
712 if ( !array_pop ( $has_opened_tr ) ) {
713 $line = "<tr><td></td></tr>{$line}";
716 if ( array_pop ( $tr_history ) ) {
717 $line = "</tr>{$line}";
720 if ( array_pop ( $td_history ) ) {
721 $line = "</{$last_tag}>{$line}";
723 array_pop ( $tr_attributes );
724 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
725 } else if ( substr ( $line , 0 , 2 ) === '|-' ) {
726 // Now we have a table row
727 $line = preg_replace( '#^\|-+#', '', $line );
729 // Whats after the tag is now only attributes
730 $attributes = $this->mStripState
->unstripBoth( $line );
731 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
732 array_pop ( $tr_attributes );
733 array_push ( $tr_attributes , $attributes );
736 $last_tag = array_pop ( $last_tag_history );
737 array_pop ( $has_opened_tr );
738 array_push ( $has_opened_tr , true );
740 if ( array_pop ( $tr_history ) ) {
744 if ( array_pop ( $td_history ) ) {
745 $line = "</{$last_tag}>{$line}";
749 array_push ( $tr_history , false );
750 array_push ( $td_history , false );
751 array_push ( $last_tag_history , '' );
753 else if ( $first_character === '|' ||
$first_character === '!' ||
substr ( $line , 0 , 2 ) === '|+' ) {
754 // This might be cell elements, td, th or captions
755 if ( substr ( $line , 0 , 2 ) === '|+' ) {
756 $first_character = '+';
757 $line = substr ( $line , 1 );
760 $line = substr ( $line , 1 );
762 if ( $first_character === '!' ) {
763 $line = str_replace ( '!!' , '||' , $line );
766 // Split up multiple cells on the same line.
767 // FIXME : This can result in improper nesting of tags processed
768 // by earlier parser steps, but should avoid splitting up eg
769 // attribute values containing literal "||".
770 $cells = StringUtils
::explodeMarkup( '||' , $line );
774 // Loop through each table cell
775 foreach ( $cells as $cell )
778 if ( $first_character !== '+' )
780 $tr_after = array_pop ( $tr_attributes );
781 if ( !array_pop ( $tr_history ) ) {
782 $previous = "<tr{$tr_after}>\n";
784 array_push ( $tr_history , true );
785 array_push ( $tr_attributes , '' );
786 array_pop ( $has_opened_tr );
787 array_push ( $has_opened_tr , true );
790 $last_tag = array_pop ( $last_tag_history );
792 if ( array_pop ( $td_history ) ) {
793 $previous = "</{$last_tag}>{$previous}";
796 if ( $first_character === '|' ) {
798 } else if ( $first_character === '!' ) {
800 } else if ( $first_character === '+' ) {
801 $last_tag = 'caption';
806 array_push ( $last_tag_history , $last_tag );
808 // A cell could contain both parameters and data
809 $cell_data = explode ( '|' , $cell , 2 );
811 // Bug 553: Note that a '|' inside an invalid link should not
812 // be mistaken as delimiting cell parameters
813 if ( strpos( $cell_data[0], '[[' ) !== false ) {
814 $cell = "{$previous}<{$last_tag}>{$cell}";
815 } else if ( count ( $cell_data ) == 1 )
816 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
818 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
819 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
820 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
824 array_push ( $td_history , true );
827 $out .= $outLine . "\n";
830 // Closing open td, tr && table
831 while ( count ( $td_history ) > 0 )
833 if ( array_pop ( $td_history ) ) {
836 if ( array_pop ( $tr_history ) ) {
839 if ( !array_pop ( $has_opened_tr ) ) {
840 $out .= "<tr><td></td></tr>\n" ;
843 $out .= "</table>\n";
846 // Remove trailing line-ending (b/c)
847 if ( substr( $out, -1 ) === "\n" ) {
848 $out = substr( $out, 0, -1 );
851 // special case: don't return empty table
852 if( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
856 wfProfileOut( __METHOD__
);
862 * Helper function for parse() that transforms wiki markup into
863 * HTML. Only called for $mOutputType == self::OT_HTML.
867 function internalParse( $text, $isMain = true ) {
868 wfProfileIn( __METHOD__
);
872 # Hook to suspend the parser in this state
873 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
874 wfProfileOut( __METHOD__
);
878 $text = $this->replaceVariables( $text );
879 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
880 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
882 // Tables need to come after variable replacement for things to work
883 // properly; putting them before other transformations should keep
884 // exciting things like link expansions from showing up in surprising
886 $text = $this->doTableStuff( $text );
888 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
890 $text = $this->doDoubleUnderscore( $text );
891 $text = $this->doHeadings( $text );
892 if( $this->mOptions
->getUseDynamicDates() ) {
893 $df = DateFormatter
::getInstance();
894 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
896 $text = $this->doAllQuotes( $text );
897 $text = $this->replaceInternalLinks( $text );
898 $text = $this->replaceExternalLinks( $text );
900 # replaceInternalLinks may sometimes leave behind
901 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
902 $text = str_replace($this->mUniqPrefix
.'NOPARSE', '', $text);
904 $text = $this->doMagicLinks( $text );
905 $text = $this->formatHeadings( $text, $origText, $isMain );
907 wfProfileOut( __METHOD__
);
912 * Replace special strings like "ISBN xxx" and "RFC xxx" with
913 * magic external links.
918 function doMagicLinks( $text ) {
919 wfProfileIn( __METHOD__
);
920 $prots = $this->mUrlProtocols
;
921 $urlChar = self
::EXT_LINK_URL_CLASS
;
922 $text = preg_replace_callback(
924 (<a.*?</a>) | # m[1]: Skip link text
925 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
926 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
927 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
928 ISBN\s+(\b # m[5]: ISBN, capture number
929 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
930 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
931 [0-9Xx] # check digit
933 )!x', array( &$this, 'magicLinkCallback' ), $text );
934 wfProfileOut( __METHOD__
);
938 function magicLinkCallback( $m ) {
939 if ( isset( $m[1] ) && $m[1] !== '' ) {
942 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
945 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
947 return $this->makeFreeExternalLink( $m[0] );
948 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
950 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
954 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
956 $urlmsg = 'pubmedurl';
959 throw new MWException( __METHOD__
.': unrecognised match type "' .
960 substr($m[0], 0, 20 ) . '"' );
962 $url = wfMsg( $urlmsg, $id);
963 $sk = $this->mOptions
->getSkin();
964 $la = $sk->getExternalLinkAttributes();
965 return "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
966 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
969 $num = strtr( $isbn, array(
974 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
976 $titleObj->escapeLocalUrl() .
977 "\" class=\"internal\">ISBN $isbn</a>";
984 * Make a free external link, given a user-supplied URL
988 function makeFreeExternalLink( $url ) {
990 wfProfileIn( __METHOD__
);
992 $sk = $this->mOptions
->getSkin();
995 # The characters '<' and '>' (which were escaped by
996 # removeHTMLtags()) should not be included in
997 # URLs, per RFC 2396.
999 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1000 $trail = substr($url, $m2[0][1]) . $trail;
1001 $url = substr($url, 0, $m2[0][1]);
1004 # Move trailing punctuation to $trail
1006 # If there is no left bracket, then consider right brackets fair game too
1007 if ( strpos( $url, '(' ) === false ) {
1011 $numSepChars = strspn( strrev( $url ), $sep );
1012 if ( $numSepChars ) {
1013 $trail = substr( $url, -$numSepChars ) . $trail;
1014 $url = substr( $url, 0, -$numSepChars );
1017 $url = Sanitizer
::cleanUrl( $url );
1019 # Is this an external image?
1020 $text = $this->maybeMakeExternalImage( $url );
1021 if ( $text === false ) {
1022 # Not an image, make a link
1023 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1024 $this->getExternalLinkAttribs( $url ) );
1025 # Register it in the output object...
1026 # Replace unnecessary URL escape codes with their equivalent characters
1027 $pasteurized = self
::replaceUnusualEscapes( $url );
1028 $this->mOutput
->addExternalLink( $pasteurized );
1030 wfProfileOut( __METHOD__
);
1031 return $text . $trail;
1036 * Parse headers and return html
1040 function doHeadings( $text ) {
1041 wfProfileIn( __METHOD__
);
1042 for ( $i = 6; $i >= 1; --$i ) {
1043 $h = str_repeat( '=', $i );
1044 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1045 "<h$i>\\1</h$i>", $text );
1047 wfProfileOut( __METHOD__
);
1052 * Replace single quotes with HTML markup
1054 * @return string the altered text
1056 function doAllQuotes( $text ) {
1057 wfProfileIn( __METHOD__
);
1059 $lines = StringUtils
::explode( "\n", $text );
1060 foreach ( $lines as $line ) {
1061 $outtext .= $this->doQuotes( $line ) . "\n";
1063 $outtext = substr($outtext, 0,-1);
1064 wfProfileOut( __METHOD__
);
1069 * Helper function for doAllQuotes()
1071 public function doQuotes( $text ) {
1072 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1073 if ( count( $arr ) == 1 )
1077 # First, do some preliminary work. This may shift some apostrophes from
1078 # being mark-up to being text. It also counts the number of occurrences
1079 # of bold and italics mark-ups.
1083 foreach ( $arr as $r )
1085 if ( ( $i %
2 ) == 1 )
1087 # If there are ever four apostrophes, assume the first is supposed to
1088 # be text, and the remaining three constitute mark-up for bold text.
1089 if ( strlen( $arr[$i] ) == 4 )
1094 # If there are more than 5 apostrophes in a row, assume they're all
1095 # text except for the last 5.
1096 else if ( strlen( $arr[$i] ) > 5 )
1098 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1101 # Count the number of occurrences of bold and italics mark-ups.
1102 # We are not counting sequences of five apostrophes.
1103 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1104 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1105 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1110 # If there is an odd number of both bold and italics, it is likely
1111 # that one of the bold ones was meant to be an apostrophe followed
1112 # by italics. Which one we cannot know for certain, but it is more
1113 # likely to be one that has a single-letter word before it.
1114 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1117 $firstsingleletterword = -1;
1118 $firstmultiletterword = -1;
1120 foreach ( $arr as $r )
1122 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1124 $x1 = substr ($arr[$i-1], -1);
1125 $x2 = substr ($arr[$i-1], -2, 1);
1127 if ($firstspace == -1) $firstspace = $i;
1128 } else if ($x2 === ' ') {
1129 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1131 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1137 # If there is a single-letter word, use it!
1138 if ($firstsingleletterword > -1)
1140 $arr [ $firstsingleletterword ] = "''";
1141 $arr [ $firstsingleletterword-1 ] .= "'";
1143 # If not, but there's a multi-letter word, use that one.
1144 else if ($firstmultiletterword > -1)
1146 $arr [ $firstmultiletterword ] = "''";
1147 $arr [ $firstmultiletterword-1 ] .= "'";
1149 # ... otherwise use the first one that has neither.
1150 # (notice that it is possible for all three to be -1 if, for example,
1151 # there is only one pentuple-apostrophe in the line)
1152 else if ($firstspace > -1)
1154 $arr [ $firstspace ] = "''";
1155 $arr [ $firstspace-1 ] .= "'";
1159 # Now let's actually convert our apostrophic mush to HTML!
1164 foreach ($arr as $r)
1168 if ($state === 'both')
1175 if (strlen ($r) == 2)
1178 { $output .= '</i>'; $state = ''; }
1179 else if ($state === 'bi')
1180 { $output .= '</i>'; $state = 'b'; }
1181 else if ($state === 'ib')
1182 { $output .= '</b></i><b>'; $state = 'b'; }
1183 else if ($state === 'both')
1184 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1185 else # $state can be 'b' or ''
1186 { $output .= '<i>'; $state .= 'i'; }
1188 else if (strlen ($r) == 3)
1191 { $output .= '</b>'; $state = ''; }
1192 else if ($state === 'bi')
1193 { $output .= '</i></b><i>'; $state = 'i'; }
1194 else if ($state === 'ib')
1195 { $output .= '</b>'; $state = 'i'; }
1196 else if ($state === 'both')
1197 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1198 else # $state can be 'i' or ''
1199 { $output .= '<b>'; $state .= 'b'; }
1201 else if (strlen ($r) == 5)
1204 { $output .= '</b><i>'; $state = 'i'; }
1205 else if ($state === 'i')
1206 { $output .= '</i><b>'; $state = 'b'; }
1207 else if ($state === 'bi')
1208 { $output .= '</i></b>'; $state = ''; }
1209 else if ($state === 'ib')
1210 { $output .= '</b></i>'; $state = ''; }
1211 else if ($state === 'both')
1212 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1213 else # ($state == '')
1214 { $buffer = ''; $state = 'both'; }
1219 # Now close all remaining tags. Notice that the order is important.
1220 if ($state === 'b' ||
$state === 'ib')
1222 if ($state === 'i' ||
$state === 'bi' ||
$state === 'ib')
1224 if ($state === 'bi')
1226 # There might be lonely ''''', so make sure we have a buffer
1227 if ($state === 'both' && $buffer)
1228 $output .= '<b><i>'.$buffer.'</i></b>';
1234 * Replace external links (REL)
1236 * Note: this is all very hackish and the order of execution matters a lot.
1237 * Make sure to run maintenance/parserTests.php if you change this code.
1241 function replaceExternalLinks( $text ) {
1243 wfProfileIn( __METHOD__
);
1245 $sk = $this->mOptions
->getSkin();
1247 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1248 $s = array_shift( $bits );
1251 while ( $i<count( $bits ) ) {
1253 $protocol = $bits[$i++
];
1254 $text = $bits[$i++
];
1255 $trail = $bits[$i++
];
1257 # The characters '<' and '>' (which were escaped by
1258 # removeHTMLtags()) should not be included in
1259 # URLs, per RFC 2396.
1261 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1262 $text = substr($url, $m2[0][1]) . ' ' . $text;
1263 $url = substr($url, 0, $m2[0][1]);
1266 # If the link text is an image URL, replace it with an <img> tag
1267 # This happened by accident in the original parser, but some people used it extensively
1268 $img = $this->maybeMakeExternalImage( $text );
1269 if ( $img !== false ) {
1275 # Set linktype for CSS - if URL==text, link is essentially free
1276 $linktype = ($text === $url) ?
'free' : 'text';
1278 # No link text, e.g. [http://domain.tld/some.link]
1279 if ( $text == '' ) {
1280 # Autonumber if allowed. See bug #5918
1281 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1282 $langObj = $this->getFunctionLang();
1283 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1284 $linktype = 'autonumber';
1286 # Otherwise just use the URL
1287 $text = htmlspecialchars( $url );
1291 # Have link text, e.g. [http://domain.tld/some.link text]s
1293 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1296 $text = $wgContLang->markNoConversion($text);
1298 $url = Sanitizer
::cleanUrl( $url );
1300 # Use the encoded URL
1301 # This means that users can paste URLs directly into the text
1302 # Funny characters like ö aren't valid in URLs anyway
1303 # This was changed in August 2004
1304 $s .= $sk->makeExternalLink( $url, $text, false, $linktype,
1305 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1307 # Register link in the output object.
1308 # Replace unnecessary URL escape codes with the referenced character
1309 # This prevents spammers from hiding links from the filters
1310 $pasteurized = self
::replaceUnusualEscapes( $url );
1311 $this->mOutput
->addExternalLink( $pasteurized );
1314 wfProfileOut( __METHOD__
);
1319 * Get an associative array of additional HTML attributes appropriate for a
1320 * particular external link. This currently may include rel => nofollow
1321 * (depending on configuration, namespace, and the URL's domain) and/or a
1322 * target attribute (depending on configuration).
1324 * @param string $url Optional URL, to extract the domain from for rel =>
1325 * nofollow if appropriate
1326 * @return array Associative array of HTML attributes
1328 function getExternalLinkAttribs( $url = false ) {
1330 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1331 $ns = $this->mTitle
->getNamespace();
1332 if( $wgNoFollowLinks && !in_array($ns, $wgNoFollowNsExceptions) ) {
1333 $attribs['rel'] = 'nofollow';
1335 global $wgNoFollowDomainExceptions;
1336 if ( $wgNoFollowDomainExceptions ) {
1337 $bits = wfParseUrl( $url );
1338 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1339 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1340 if( substr( $bits['host'], -strlen( $domain ) )
1342 unset( $attribs['rel'] );
1349 if ( $this->mOptions
->getExternalLinkTarget() ) {
1350 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1357 * Replace unusual URL escape codes with their equivalent characters
1361 * @todo This can merge genuinely required bits in the path or query string,
1362 * breaking legit URLs. A proper fix would treat the various parts of
1363 * the URL differently; as a workaround, just use the output for
1364 * statistical records, not for actual linking/output.
1366 static function replaceUnusualEscapes( $url ) {
1367 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1368 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1372 * Callback function used in replaceUnusualEscapes().
1373 * Replaces unusual URL escape codes with their equivalent character
1377 private static function replaceUnusualEscapesCallback( $matches ) {
1378 $char = urldecode( $matches[0] );
1379 $ord = ord( $char );
1380 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1381 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1382 // No, shouldn't be escaped
1385 // Yes, leave it escaped
1391 * make an image if it's allowed, either through the global
1392 * option, through the exception, or through the on-wiki whitelist
1395 function maybeMakeExternalImage( $url ) {
1396 $sk = $this->mOptions
->getSkin();
1397 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1398 $imagesexception = !empty($imagesfrom);
1400 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1401 if( $imagesexception && is_array( $imagesfrom ) ) {
1402 $imagematch = false;
1403 foreach( $imagesfrom as $match ) {
1404 if( strpos( $url, $match ) === 0 ) {
1409 } elseif( $imagesexception ) {
1410 $imagematch = (strpos( $url, $imagesfrom ) === 0);
1412 $imagematch = false;
1414 if ( $this->mOptions
->getAllowExternalImages()
1415 ||
( $imagesexception && $imagematch ) ) {
1416 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1418 $text = $sk->makeExternalImage( $url );
1421 if( !$text && $this->mOptions
->getEnableImageWhitelist()
1422 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1423 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1424 foreach( $whitelist as $entry ) {
1425 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1426 if( strpos( $entry, '#' ) === 0 ||
$entry === '' )
1428 if( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1429 # Image matches a whitelist entry
1430 $text = $sk->makeExternalImage( $url );
1439 * Process [[ ]] wikilinks
1440 * @return processed text
1444 function replaceInternalLinks( $s ) {
1445 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1450 * Process [[ ]] wikilinks (RIL)
1451 * @return LinkHolderArray
1455 function replaceInternalLinks2( &$s ) {
1458 wfProfileIn( __METHOD__
);
1460 wfProfileIn( __METHOD__
.'-setup' );
1461 static $tc = FALSE, $e1, $e1_img;
1462 # the % is needed to support urlencoded titles as well
1464 $tc = Title
::legalChars() . '#%';
1465 # Match a link having the form [[namespace:link|alternate]]trail
1466 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1467 # Match cases where there is no "]]", which might still be images
1468 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1471 $sk = $this->mOptions
->getSkin();
1472 $holders = new LinkHolderArray( $this );
1474 #split the entire text string on occurences of [[
1475 $a = StringUtils
::explode( '[[', ' ' . $s );
1476 #get the first element (all text up to first [[), and remove the space we added
1479 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1480 $s = substr( $s, 1 );
1482 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1484 if ( $useLinkPrefixExtension ) {
1485 # Match the end of a line for a word that's not followed by whitespace,
1486 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1487 $e2 = wfMsgForContent( 'linkprefix' );
1490 if( is_null( $this->mTitle
) ) {
1491 wfProfileOut( __METHOD__
.'-setup' );
1492 wfProfileOut( __METHOD__
);
1493 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1495 $nottalk = !$this->mTitle
->isTalkPage();
1497 if ( $useLinkPrefixExtension ) {
1499 if ( preg_match( $e2, $s, $m ) ) {
1500 $first_prefix = $m[2];
1502 $first_prefix = false;
1508 if($wgContLang->hasVariants()) {
1509 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1511 $selflink = array($this->mTitle
->getPrefixedText());
1513 $useSubpages = $this->areSubpagesAllowed();
1514 wfProfileOut( __METHOD__
.'-setup' );
1516 # Loop for each link
1517 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1518 # Check for excessive memory usage
1519 if ( $holders->isBig() ) {
1521 # Do the existence check, replace the link holders and clear the array
1522 $holders->replace( $s );
1526 if ( $useLinkPrefixExtension ) {
1527 wfProfileIn( __METHOD__
.'-prefixhandling' );
1528 if ( preg_match( $e2, $s, $m ) ) {
1536 $prefix = $first_prefix;
1537 $first_prefix = false;
1539 wfProfileOut( __METHOD__
.'-prefixhandling' );
1542 $might_be_img = false;
1544 wfProfileIn( __METHOD__
."-e1" );
1545 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1547 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1548 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1549 # the real problem is with the $e1 regex
1552 # Still some problems for cases where the ] is meant to be outside punctuation,
1553 # and no image is in sight. See bug 2095.
1556 substr( $m[3], 0, 1 ) === ']' &&
1557 strpos($text, '[') !== false
1560 $text .= ']'; # so that replaceExternalLinks($text) works later
1561 $m[3] = substr( $m[3], 1 );
1563 # fix up urlencoded title texts
1564 if( strpos( $m[1], '%' ) !== false ) {
1565 # Should anchors '#' also be rejected?
1566 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1569 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1570 $might_be_img = true;
1572 if ( strpos( $m[1], '%' ) !== false ) {
1573 $m[1] = urldecode($m[1]);
1576 } else { # Invalid form; output directly
1577 $s .= $prefix . '[[' . $line ;
1578 wfProfileOut( __METHOD__
."-e1" );
1581 wfProfileOut( __METHOD__
."-e1" );
1582 wfProfileIn( __METHOD__
."-misc" );
1584 # Don't allow internal links to pages containing
1585 # PROTO: where PROTO is a valid URL protocol; these
1586 # should be external links.
1587 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1588 $s .= $prefix . '[[' . $line ;
1589 wfProfileOut( __METHOD__
."-misc" );
1593 # Make subpage if necessary
1594 if ( $useSubpages ) {
1595 $link = $this->maybeDoSubpageLink( $m[1], $text );
1600 $noforce = (substr( $m[1], 0, 1 ) !== ':');
1602 # Strip off leading ':'
1603 $link = substr( $link, 1 );
1606 wfProfileOut( __METHOD__
."-misc" );
1607 wfProfileIn( __METHOD__
."-title" );
1608 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1609 if ( $nt === NULL ) {
1610 $s .= $prefix . '[[' . $line;
1611 wfProfileOut( __METHOD__
."-title" );
1615 $ns = $nt->getNamespace();
1616 $iw = $nt->getInterWiki();
1617 wfProfileOut( __METHOD__
."-title" );
1619 if ( $might_be_img ) { # if this is actually an invalid link
1620 wfProfileIn( __METHOD__
."-might_be_img" );
1621 if ( $ns == NS_FILE
&& $noforce ) { #but might be an image
1624 #look at the next 'line' to see if we can close it there
1626 $next_line = $a->current();
1627 if ( $next_line === false ||
$next_line === null ) {
1630 $m = explode( ']]', $next_line, 3 );
1631 if ( count( $m ) == 3 ) {
1632 # the first ]] closes the inner link, the second the image
1634 $text .= "[[{$m[0]}]]{$m[1]}";
1637 } elseif ( count( $m ) == 2 ) {
1638 #if there's exactly one ]] that's fine, we'll keep looking
1639 $text .= "[[{$m[0]}]]{$m[1]}";
1641 #if $next_line is invalid too, we need look no further
1642 $text .= '[[' . $next_line;
1647 # we couldn't find the end of this imageLink, so output it raw
1648 #but don't ignore what might be perfectly normal links in the text we've examined
1649 $holders->merge( $this->replaceInternalLinks2( $text ) );
1650 $s .= "{$prefix}[[$link|$text";
1651 # note: no $trail, because without an end, there *is* no trail
1652 wfProfileOut( __METHOD__
."-might_be_img" );
1655 } else { #it's not an image, so output it raw
1656 $s .= "{$prefix}[[$link|$text";
1657 # note: no $trail, because without an end, there *is* no trail
1658 wfProfileOut( __METHOD__
."-might_be_img" );
1661 wfProfileOut( __METHOD__
."-might_be_img" );
1664 $wasblank = ( '' == $text );
1665 if ( $wasblank ) $text = $link;
1667 # Link not escaped by : , create the various objects
1671 wfProfileIn( __METHOD__
."-interwiki" );
1672 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1673 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1674 $s = rtrim($s . $prefix);
1675 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1676 wfProfileOut( __METHOD__
."-interwiki" );
1679 wfProfileOut( __METHOD__
."-interwiki" );
1681 if ( $ns == NS_FILE
) {
1682 wfProfileIn( __METHOD__
."-image" );
1683 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1685 # if no parameters were passed, $text
1686 # becomes something like "File:Foo.png",
1687 # which we don't want to pass on to the
1691 # recursively parse links inside the image caption
1692 # actually, this will parse them in any other parameters, too,
1693 # but it might be hard to fix that, and it doesn't matter ATM
1694 $text = $this->replaceExternalLinks($text);
1695 $holders->merge( $this->replaceInternalLinks2( $text ) );
1697 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1698 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1700 $this->mOutput
->addImage( $nt->getDBkey() );
1701 wfProfileOut( __METHOD__
."-image" );
1706 if ( $ns == NS_CATEGORY
) {
1707 wfProfileIn( __METHOD__
."-category" );
1708 $s = rtrim($s . "\n"); # bug 87
1711 $sortkey = $this->getDefaultSort();
1715 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1716 $sortkey = str_replace( "\n", '', $sortkey );
1717 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1718 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1721 * Strip the whitespace Category links produce, see bug 87
1722 * @todo We might want to use trim($tmp, "\n") here.
1724 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1726 wfProfileOut( __METHOD__
."-category" );
1731 # Self-link checking
1732 if( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1733 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1734 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1739 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1740 # FIXME: Should do batch file existence checks, see comment below
1741 if( $ns == NS_MEDIA
) {
1742 wfProfileIn( __METHOD__
."-media" );
1743 # Give extensions a chance to select the file revision for us
1744 $skip = $time = false;
1745 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1747 $link = $sk->link( $nt );
1749 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1751 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1752 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1753 $this->mOutput
->addImage( $nt->getDBkey() );
1754 wfProfileOut( __METHOD__
."-media" );
1758 wfProfileIn( __METHOD__
."-always_known" );
1759 # Some titles, such as valid special pages or files in foreign repos, should
1760 # be shown as bluelinks even though they're not included in the page table
1762 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1763 # batch file existence checks for NS_FILE and NS_MEDIA
1764 if( $iw == '' && $nt->isAlwaysKnown() ) {
1765 $this->mOutput
->addLink( $nt );
1766 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1768 # Links will be added to the output link list after checking
1769 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1771 wfProfileOut( __METHOD__
."-always_known" );
1773 wfProfileOut( __METHOD__
);
1778 * Make a link placeholder. The text returned can be later resolved to a real link with
1779 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1780 * parsing of interwiki links, and secondly to allow all existence checks and
1781 * article length checks (for stub links) to be bundled into a single query.
1785 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1786 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1790 * Render a forced-blue link inline; protect against double expansion of
1791 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1792 * Since this little disaster has to split off the trail text to avoid
1793 * breaking URLs in the following text without breaking trails on the
1794 * wiki links, it's been made into a horrible function.
1797 * @param string $text
1798 * @param string $query
1799 * @param string $trail
1800 * @param string $prefix
1801 * @return string HTML-wikitext mix oh yuck
1803 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1804 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1805 $sk = $this->mOptions
->getSkin();
1806 // FIXME: use link() instead of deprecated makeKnownLinkObj()
1807 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1808 return $this->armorLinks( $link ) . $trail;
1812 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1813 * going to go through further parsing steps before inline URL expansion.
1815 * Not needed quite as much as it used to be since free links are a bit
1816 * more sensible these days. But bracketed links are still an issue.
1818 * @param string more-or-less HTML
1819 * @return string less-or-more HTML with NOPARSE bits
1821 function armorLinks( $text ) {
1822 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1823 "{$this->mUniqPrefix}NOPARSE$1", $text );
1827 * Return true if subpage links should be expanded on this page.
1830 function areSubpagesAllowed() {
1831 # Some namespaces don't allow subpages
1832 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
1836 * Handle link to subpage if necessary
1837 * @param string $target the source of the link
1838 * @param string &$text the link text, modified as necessary
1839 * @return string the full name of the link
1842 function maybeDoSubpageLink($target, &$text) {
1843 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
1847 * Used by doBlockLevels()
1850 /* private */ function closeParagraph() {
1852 if ( '' != $this->mLastSection
) {
1853 $result = '</' . $this->mLastSection
. ">\n";
1855 $this->mInPre
= false;
1856 $this->mLastSection
= '';
1859 # getCommon() returns the length of the longest common substring
1860 # of both arguments, starting at the beginning of both.
1862 /* private */ function getCommon( $st1, $st2 ) {
1863 $fl = strlen( $st1 );
1864 $shorter = strlen( $st2 );
1865 if ( $fl < $shorter ) { $shorter = $fl; }
1867 for ( $i = 0; $i < $shorter; ++
$i ) {
1868 if ( $st1{$i} != $st2{$i} ) { break; }
1872 # These next three functions open, continue, and close the list
1873 # element appropriate to the prefix character passed into them.
1875 /* private */ function openList( $char ) {
1876 $result = $this->closeParagraph();
1878 if ( '*' === $char ) { $result .= '<ul><li>'; }
1879 elseif ( '#' === $char ) { $result .= '<ol><li>'; }
1880 elseif ( ':' === $char ) { $result .= '<dl><dd>'; }
1881 elseif ( ';' === $char ) {
1882 $result .= '<dl><dt>';
1883 $this->mDTopen
= true;
1884 } elseif ( '>' === $char ) { $result .= "<blockquote><p>"; }
1885 else { $result = '<!-- ERR 1 -->'; }
1890 /* private */ function nextItem( $char ) {
1891 if ( '*' === $char ||
'#' === $char ) { return '</li><li>'; }
1892 elseif ( '>' === $char ) { return "</p><p>"; }
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 ) { $text = "</p></blockquote>"; }
1911 elseif ( ':' === $char ) {
1912 if ( $this->mDTopen
) {
1913 $this->mDTopen
= false;
1914 $text = '</dt></dl>';
1916 $text = '</dd></dl>';
1919 else { return '<!-- ERR 3 -->'; }
1925 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
1927 * @param $linestart bool whether or not this is at the start of a line.
1929 * @return string the lists rendered as HTML
1931 function doBlockLevels( $text, $linestart ) {
1932 wfProfileIn( __METHOD__
);
1934 # Parsing through the text line by line. The main thing
1935 # happening here is handling of block-level elements p, pre,
1936 # and making lists from lines starting with * # : etc.
1938 $textLines = StringUtils
::explode( "\n", $text );
1940 $lastPrefix = $output = '';
1941 $this->mDTopen
= $inBlockElem = false;
1943 $paragraphStack = false;
1945 foreach ( $textLines as $oLine ) {
1947 if ( !$linestart ) {
1958 $lastPrefixLength = strlen( $lastPrefix );
1959 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1960 $preOpenMatch = preg_match('/<pre/i', $oLine );
1962 // Need to decode > --> > for blockquote syntax. Re-encode later.
1963 // To avoid collision with real >s, we temporarily convert them to >
1964 // This is a weird choice of armouring, but it's totally resistant to any
1967 $oLine = strtr( $oLine, array( '>' => '>', '>' => '>' ) );
1969 // If not in a <pre> element, scan for and figure out what prefixes are there.
1970 if ( !$this->mInPre
) {
1971 # Multiple prefixes may abut each other for nested lists.
1972 $prefixLength = strspn( $oLine, '*#:;>' );
1973 $prefix = substr( $oLine, 0, $prefixLength );
1976 // ; and : are both from definition-lists, so they're equivalent
1977 // for the purposes of determining whether or not we need to open/close
1979 $prefix2 = str_replace( ';', ':', $prefix );
1980 $t = substr( $oLine, $prefixLength );
1981 $this->mInPre
= (bool)$preOpenMatch;
1983 # Don't interpret any other prefixes in preformatted text
1985 $prefix = $prefix2 = '';
1990 $t = strtr( $t, array( '>' => '>', '>' => '>' ) );
1993 if( $prefixLength && $lastPrefix === $prefix2 ) {
1994 # Same as the last item, so no need to deal with nesting or opening stuff
1995 $output .= $this->nextItem( substr( $prefix, -1 ) );
1996 $paragraphStack = false;
1998 if ( substr( $prefix, -1 ) === ';') {
1999 # The one nasty exception: definition lists work like this:
2000 # ; title : definition text
2001 # So we check for : in the remainder text to split up the
2002 # title and definition, without b0rking links.
2004 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2006 $output .= $term . $this->nextItem( ':' );
2009 } elseif( $prefixLength ||
$lastPrefixLength ) {
2010 // We need to open or close prefixes, or both.
2012 # Either open or close a level...
2013 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2014 $paragraphStack = false;
2016 // Close all the prefixes which aren't shared.
2017 while( $commonPrefixLength < $lastPrefixLength ) {
2018 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2019 --$lastPrefixLength;
2022 // Continue the current prefix if appropriate.
2023 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2024 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2027 // Open prefixes where appropriate.
2028 while ( $prefixLength > $commonPrefixLength ) {
2029 $char = substr( $prefix, $commonPrefixLength, 1 );
2030 $output .= $this->openList( $char );
2032 if ( ';' === $char ) {
2033 # FIXME: This is dupe of code above
2034 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2036 $output .= $term . $this->nextItem( ':' );
2039 ++
$commonPrefixLength;
2041 $lastPrefix = $prefix2;
2044 // If we have no prefixes, go to paragraph mode.
2045 if( 0 == $prefixLength ) {
2046 wfProfileIn( __METHOD__
."-paragraph" );
2047 # No prefix (not in list)--go to paragraph mode
2048 // XXX: use a stack for nestable elements like span, table and div
2049 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2050 $closematch = preg_match(
2051 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2052 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2053 if ( $openmatch or $closematch ) {
2054 $paragraphStack = false;
2055 #Â TODO bug 5718: paragraph closed
2056 $output .= $this->closeParagraph();
2057 if ( $preOpenMatch and !$preCloseMatch ) {
2058 $this->mInPre
= true;
2060 if ( $closematch ) {
2061 $inBlockElem = false;
2063 $inBlockElem = true;
2065 } else if ( !$inBlockElem && !$this->mInPre
) {
2066 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' or trim($t) != '' ) ) {
2068 if ($this->mLastSection
!== 'pre') {
2069 $paragraphStack = false;
2070 $output .= $this->closeParagraph().'<pre>';
2071 $this->mLastSection
= 'pre';
2073 $t = substr( $t, 1 );
2076 if ( '' == trim($t) ) {
2077 if ( $paragraphStack ) {
2078 $output .= $paragraphStack.'<br />';
2079 $paragraphStack = false;
2080 $this->mLastSection
= 'p';
2082 if ($this->mLastSection
!== 'p' ) {
2083 $output .= $this->closeParagraph();
2084 $this->mLastSection
= '';
2085 $paragraphStack = '<p>';
2087 $paragraphStack = '</p><p>';
2091 if ( $paragraphStack ) {
2092 $output .= $paragraphStack;
2093 $paragraphStack = false;
2094 $this->mLastSection
= 'p';
2095 } else if ($this->mLastSection
!== 'p') {
2096 $output .= $this->closeParagraph().'<p>';
2097 $this->mLastSection
= 'p';
2102 wfProfileOut( __METHOD__
."-paragraph" );
2104 // somewhere above we forget to get out of pre block (bug 785)
2105 if($preCloseMatch && $this->mInPre
) {
2106 $this->mInPre
= false;
2108 if ($paragraphStack === false) {
2112 while ( $prefixLength ) {
2113 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2116 if ( '' != $this->mLastSection
) {
2117 $output .= '</' . $this->mLastSection
. '>';
2118 $this->mLastSection
= '';
2121 wfProfileOut( __METHOD__
);
2126 * Split up a string on ':', ignoring any occurences inside tags
2127 * to prevent illegal overlapping.
2128 * @param string $str the string to split
2129 * @param string &$before set to everything before the ':'
2130 * @param string &$after set to everything after the ':'
2131 * return string the position of the ':', or false if none found
2133 function findColonNoLinks($str, &$before, &$after) {
2134 wfProfileIn( __METHOD__
);
2136 $pos = strpos( $str, ':' );
2137 if( $pos === false ) {
2139 wfProfileOut( __METHOD__
);
2143 $lt = strpos( $str, '<' );
2144 if( $lt === false ||
$lt > $pos ) {
2145 // Easy; no tag nesting to worry about
2146 $before = substr( $str, 0, $pos );
2147 $after = substr( $str, $pos+
1 );
2148 wfProfileOut( __METHOD__
);
2152 // Ugly state machine to walk through avoiding tags.
2153 $state = self
::COLON_STATE_TEXT
;
2155 $len = strlen( $str );
2156 for( $i = 0; $i < $len; $i++
) {
2160 // (Using the number is a performance hack for common cases)
2161 case 0: // self::COLON_STATE_TEXT:
2164 // Could be either a <start> tag or an </end> tag
2165 $state = self
::COLON_STATE_TAGSTART
;
2170 $before = substr( $str, 0, $i );
2171 $after = substr( $str, $i +
1 );
2172 wfProfileOut( __METHOD__
);
2175 // Embedded in a tag; don't break it.
2178 // Skip ahead looking for something interesting
2179 $colon = strpos( $str, ':', $i );
2180 if( $colon === false ) {
2181 // Nothing else interesting
2182 wfProfileOut( __METHOD__
);
2185 $lt = strpos( $str, '<', $i );
2186 if( $stack === 0 ) {
2187 if( $lt === false ||
$colon < $lt ) {
2189 $before = substr( $str, 0, $colon );
2190 $after = substr( $str, $colon +
1 );
2191 wfProfileOut( __METHOD__
);
2195 if( $lt === false ) {
2196 // Nothing else interesting to find; abort!
2197 // We're nested, but there's no close tags left. Abort!
2200 // Skip ahead to next tag start
2202 $state = self
::COLON_STATE_TAGSTART
;
2205 case 1: // self::COLON_STATE_TAG:
2210 $state = self
::COLON_STATE_TEXT
;
2213 // Slash may be followed by >?
2214 $state = self
::COLON_STATE_TAGSLASH
;
2220 case 2: // self::COLON_STATE_TAGSTART:
2223 $state = self
::COLON_STATE_CLOSETAG
;
2226 $state = self
::COLON_STATE_COMMENT
;
2229 // Illegal early close? This shouldn't happen D:
2230 $state = self
::COLON_STATE_TEXT
;
2233 $state = self
::COLON_STATE_TAG
;
2236 case 3: // self::COLON_STATE_CLOSETAG:
2241 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2242 wfProfileOut( __METHOD__
);
2245 $state = self
::COLON_STATE_TEXT
;
2248 case self
::COLON_STATE_TAGSLASH
:
2250 // Yes, a self-closed tag <blah/>
2251 $state = self
::COLON_STATE_TEXT
;
2253 // Probably we're jumping the gun, and this is an attribute
2254 $state = self
::COLON_STATE_TAG
;
2257 case 5: // self::COLON_STATE_COMMENT:
2259 $state = self
::COLON_STATE_COMMENTDASH
;
2262 case self
::COLON_STATE_COMMENTDASH
:
2264 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2266 $state = self
::COLON_STATE_COMMENT
;
2269 case self
::COLON_STATE_COMMENTDASHDASH
:
2271 $state = self
::COLON_STATE_TEXT
;
2273 $state = self
::COLON_STATE_COMMENT
;
2277 throw new MWException( "State machine error in " . __METHOD__
);
2281 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2284 wfProfileOut( __METHOD__
);
2289 * Return value of a magic variable (like PAGENAME)
2293 function getVariableValue( $index ) {
2294 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2297 * Some of these require message or data lookups and can be
2298 * expensive to check many times.
2300 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2301 if ( isset( $this->mVarCache
[$index] ) ) {
2302 return $this->mVarCache
[$index];
2306 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2307 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2310 global $wgLocaltimezone;
2311 if ( isset( $wgLocaltimezone ) ) {
2312 $oldtz = getenv( 'TZ' );
2313 putenv( 'TZ='.$wgLocaltimezone );
2316 wfSuppressWarnings(); // E_STRICT system time bitching
2317 $localTimestamp = date( 'YmdHis', $ts );
2318 $localMonth = date( 'm', $ts );
2319 $localMonth1 = date( 'n', $ts );
2320 $localMonthName = date( 'n', $ts );
2321 $localDay = date( 'j', $ts );
2322 $localDay2 = date( 'd', $ts );
2323 $localDayOfWeek = date( 'w', $ts );
2324 $localWeek = date( 'W', $ts );
2325 $localYear = date( 'Y', $ts );
2326 $localHour = date( 'H', $ts );
2327 if ( isset( $wgLocaltimezone ) ) {
2328 putenv( 'TZ='.$oldtz );
2330 wfRestoreWarnings();
2333 case 'currentmonth':
2334 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2335 case 'currentmonth1':
2336 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2337 case 'currentmonthname':
2338 return $this->mVarCache
[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2339 case 'currentmonthnamegen':
2340 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2341 case 'currentmonthabbrev':
2342 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2344 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2346 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2348 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localMonth );
2350 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localMonth1 );
2351 case 'localmonthname':
2352 return $this->mVarCache
[$index] = $wgContLang->getMonthName( $localMonthName );
2353 case 'localmonthnamegen':
2354 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2355 case 'localmonthabbrev':
2356 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2358 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay );
2360 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay2 );
2362 return wfEscapeWikiText( $this->mTitle
->getText() );
2364 return $this->mTitle
->getPartialURL();
2365 case 'fullpagename':
2366 return wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2367 case 'fullpagenamee':
2368 return $this->mTitle
->getPrefixedURL();
2370 return wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2371 case 'subpagenamee':
2372 return $this->mTitle
->getSubpageUrlForm();
2373 case 'basepagename':
2374 return wfEscapeWikiText( $this->mTitle
->getBaseText() );
2375 case 'basepagenamee':
2376 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2377 case 'talkpagename':
2378 if( $this->mTitle
->canTalk() ) {
2379 $talkPage = $this->mTitle
->getTalkPage();
2380 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2384 case 'talkpagenamee':
2385 if( $this->mTitle
->canTalk() ) {
2386 $talkPage = $this->mTitle
->getTalkPage();
2387 return $talkPage->getPrefixedUrl();
2391 case 'subjectpagename':
2392 $subjPage = $this->mTitle
->getSubjectPage();
2393 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2394 case 'subjectpagenamee':
2395 $subjPage = $this->mTitle
->getSubjectPage();
2396 return $subjPage->getPrefixedUrl();
2398 // Let the edit saving system know we should parse the page
2399 // *after* a revision ID has been assigned.
2400 $this->mOutput
->setFlag( 'vary-revision' );
2401 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2402 return $this->mRevisionId
;
2404 // Let the edit saving system know we should parse the page
2405 // *after* a revision ID has been assigned. This is for null edits.
2406 $this->mOutput
->setFlag( 'vary-revision' );
2407 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2408 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2409 case 'revisionday2':
2410 // Let the edit saving system know we should parse the page
2411 // *after* a revision ID has been assigned. This is for null edits.
2412 $this->mOutput
->setFlag( 'vary-revision' );
2413 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2414 return substr( $this->getRevisionTimestamp(), 6, 2 );
2415 case 'revisionmonth':
2416 // Let the edit saving system know we should parse the page
2417 // *after* a revision ID has been assigned. This is for null edits.
2418 $this->mOutput
->setFlag( 'vary-revision' );
2419 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2420 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2421 case 'revisionyear':
2422 // Let the edit saving system know we should parse the page
2423 // *after* a revision ID has been assigned. This is for null edits.
2424 $this->mOutput
->setFlag( 'vary-revision' );
2425 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2426 return substr( $this->getRevisionTimestamp(), 0, 4 );
2427 case 'revisiontimestamp':
2428 // Let the edit saving system know we should parse the page
2429 // *after* a revision ID has been assigned. This is for null edits.
2430 $this->mOutput
->setFlag( 'vary-revision' );
2431 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2432 return $this->getRevisionTimestamp();
2433 case 'revisionuser':
2434 // Let the edit saving system know we should parse the page
2435 // *after* a revision ID has been assigned. This is for null edits.
2436 $this->mOutput
->setFlag( 'vary-revision' );
2437 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2438 return $this->getRevisionUser();
2440 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2442 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2444 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2446 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2447 case 'subjectspace':
2448 return $this->mTitle
->getSubjectNsText();
2449 case 'subjectspacee':
2450 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2451 case 'currentdayname':
2452 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2454 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2456 return $this->mVarCache
[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2458 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2460 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2461 // int to remove the padding
2462 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2464 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2465 case 'localdayname':
2466 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2468 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localYear, true );
2470 return $this->mVarCache
[$index] = $wgContLang->time( $localTimestamp, false, false );
2472 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localHour, true );
2474 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2475 // int to remove the padding
2476 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)$localWeek );
2478 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDayOfWeek );
2479 case 'numberofarticles':
2480 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2481 case 'numberoffiles':
2482 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::images() );
2483 case 'numberofusers':
2484 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::users() );
2485 case 'numberofactiveusers':
2486 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::activeUsers() );
2487 case 'numberofpages':
2488 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2489 case 'numberofadmins':
2490 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::numberingroup('sysop') );
2491 case 'numberofedits':
2492 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2493 case 'numberofviews':
2494 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::views() );
2495 case 'currenttimestamp':
2496 return $this->mVarCache
[$index] = wfTimestamp( TS_MW
, $ts );
2497 case 'localtimestamp':
2498 return $this->mVarCache
[$index] = $localTimestamp;
2499 case 'currentversion':
2500 return $this->mVarCache
[$index] = SpecialVersion
::getVersion();
2506 return $wgServerName;
2508 return $wgScriptPath;
2509 case 'directionmark':
2510 return $wgContLang->getDirMark();
2511 case 'contentlanguage':
2512 global $wgContLanguageCode;
2513 return $wgContLanguageCode;
2516 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret ) ) )
2524 * initialise the magic variables (like CURRENTMONTHNAME)
2528 function initialiseVariables() {
2529 wfProfileIn( __METHOD__
);
2530 $variableIDs = MagicWord
::getVariableIDs();
2532 $this->mVariables
= new MagicWordArray( $variableIDs );
2533 wfProfileOut( __METHOD__
);
2537 * Preprocess some wikitext and return the document tree.
2538 * This is the ghost of replace_variables().
2540 * @param string $text The text to parse
2541 * @param integer flags Bitwise combination of:
2542 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2543 * included. Default is to assume a direct page view.
2545 * The generated DOM tree must depend only on the input text and the flags.
2546 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2548 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2549 * change in the DOM tree for a given text, must be passed through the section identifier
2550 * in the section edit link and thus back to extractSections().
2552 * The output of this function is currently only cached in process memory, but a persistent
2553 * cache may be implemented at a later date which takes further advantage of these strict
2554 * dependency requirements.
2558 function preprocessToDom ( $text, $flags = 0 ) {
2559 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2564 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2566 public static function splitWhitespace( $s ) {
2567 $ltrimmed = ltrim( $s );
2568 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2569 $trimmed = rtrim( $ltrimmed );
2570 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2572 $w2 = substr( $ltrimmed, -$diff );
2576 return array( $w1, $trimmed, $w2 );
2580 * Replace magic variables, templates, and template arguments
2581 * with the appropriate text. Templates are substituted recursively,
2582 * taking care to avoid infinite loops.
2584 * Note that the substitution depends on value of $mOutputType:
2585 * self::OT_WIKI: only {{subst:}} templates
2586 * self::OT_PREPROCESS: templates but not extension tags
2587 * self::OT_HTML: all templates and extension tags
2589 * @param string $tex The text to transform
2590 * @param PPFrame $frame Object describing the arguments passed to the template.
2591 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2592 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2593 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2596 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2597 # Is there any text? Also, Prevent too big inclusions!
2598 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2601 wfProfileIn( __METHOD__
);
2603 if ( $frame === false ) {
2604 $frame = $this->getPreprocessor()->newFrame();
2605 } elseif ( !( $frame instanceof PPFrame
) ) {
2606 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2607 $frame = $this->getPreprocessor()->newCustomFrame($frame);
2610 $dom = $this->preprocessToDom( $text );
2611 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2612 $text = $frame->expand( $dom, $flags );
2614 wfProfileOut( __METHOD__
);
2618 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2619 static function createAssocArgs( $args ) {
2620 $assocArgs = array();
2622 foreach( $args as $arg ) {
2623 $eqpos = strpos( $arg, '=' );
2624 if ( $eqpos === false ) {
2625 $assocArgs[$index++
] = $arg;
2627 $name = trim( substr( $arg, 0, $eqpos ) );
2628 $value = trim( substr( $arg, $eqpos+
1 ) );
2629 if ( $value === false ) {
2632 if ( $name !== false ) {
2633 $assocArgs[$name] = $value;
2642 * Warn the user when a parser limitation is reached
2643 * Will warn at most once the user per limitation type
2645 * @param string $limitationType, should be one of:
2646 * 'expensive-parserfunction' (corresponding messages: 'expensive-parserfunction-warning', 'expensive-parserfunction-category')
2647 * 'post-expand-template-argument' (corresponding messages: 'post-expand-template-argument-warning', 'post-expand-template-argument-category')
2648 * 'post-expand-template-inclusion' (corresponding messages: 'post-expand-template-inclusion-warning', 'post-expand-template-inclusion-category')
2649 * @params int $current, $max When an explicit limit has been
2650 * exceeded, provide the values (optional)
2652 function limitationWarn( $limitationType, $current=null, $max=null) {
2653 $msgName = $limitationType . '-warning';
2654 //does no harm if $current and $max are present but are unnecessary for the message
2655 $warning = wfMsgExt( $msgName, array( 'parsemag', 'escape' ), $current, $max );
2656 $this->mOutput
->addWarning( $warning );
2657 $cat = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( $limitationType . '-category' ) );
2659 $this->mOutput
->addCategory( $cat->getDBkey(), $this->getDefaultSort() );
2664 * Return the text of a template, after recursively
2665 * replacing any variables or templates within the template.
2667 * @param array $piece The parts of the template
2668 * $piece['title']: the title, i.e. the part before the |
2669 * $piece['parts']: the parameter array
2670 * $piece['lineStart']: whether the brace was at the start of a line
2671 * @param PPFrame The current frame, contains template arguments
2672 * @return string the text of the template
2675 function braceSubstitution( $piece, $frame ) {
2676 global $wgContLang, $wgNonincludableNamespaces;
2677 wfProfileIn( __METHOD__
);
2678 wfProfileIn( __METHOD__
.'-setup' );
2681 $found = false; # $text has been filled
2682 $nowiki = false; # wiki markup in $text should be escaped
2683 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2684 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2685 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2686 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2688 # Title object, where $text came from
2691 # $part1 is the bit before the first |, and must contain only title characters.
2692 # Various prefixes will be stripped from it later.
2693 $titleWithSpaces = $frame->expand( $piece['title'] );
2694 $part1 = trim( $titleWithSpaces );
2697 # Original title text preserved for various purposes
2698 $originalTitle = $part1;
2700 # $args is a list of argument nodes, starting from index 0, not including $part1
2701 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2702 wfProfileOut( __METHOD__
.'-setup' );
2705 wfProfileIn( __METHOD__
.'-modifiers' );
2707 $mwSubst = MagicWord
::get( 'subst' );
2708 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2709 # One of two possibilities is true:
2710 # 1) Found SUBST but not in the PST phase
2711 # 2) Didn't find SUBST and in the PST phase
2712 # In either case, return without further processing
2713 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2720 if ( !$found && $args->getLength() == 0 ) {
2721 $id = $this->mVariables
->matchStartToEnd( $part1 );
2722 if ( $id !== false ) {
2723 $text = $this->getVariableValue( $id );
2724 if (MagicWord
::getCacheTTL($id)>-1)
2725 $this->mOutput
->mContainsOldMagic
= true;
2730 # MSG, MSGNW and RAW
2733 $mwMsgnw = MagicWord
::get( 'msgnw' );
2734 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2737 # Remove obsolete MSG:
2738 $mwMsg = MagicWord
::get( 'msg' );
2739 $mwMsg->matchStartAndRemove( $part1 );
2743 $mwRaw = MagicWord
::get( 'raw' );
2744 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2745 $forceRawInterwiki = true;
2748 wfProfileOut( __METHOD__
.'-modifiers' );
2752 wfProfileIn( __METHOD__
. '-pfunc' );
2754 $colonPos = strpos( $part1, ':' );
2755 if ( $colonPos !== false ) {
2756 # Case sensitive functions
2757 $function = substr( $part1, 0, $colonPos );
2758 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2759 $function = $this->mFunctionSynonyms
[1][$function];
2761 # Case insensitive functions
2762 $function = strtolower( $function );
2763 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2764 $function = $this->mFunctionSynonyms
[0][$function];
2770 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2771 $initialArgs = array( &$this );
2772 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2773 if ( $flags & SFH_OBJECT_ARGS
) {
2774 # Add a frame parameter, and pass the arguments as an array
2775 $allArgs = $initialArgs;
2776 $allArgs[] = $frame;
2777 for ( $i = 0; $i < $args->getLength(); $i++
) {
2778 $funcArgs[] = $args->item( $i );
2780 $allArgs[] = $funcArgs;
2782 # Convert arguments to plain text
2783 for ( $i = 0; $i < $args->getLength(); $i++
) {
2784 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2786 $allArgs = array_merge( $initialArgs, $funcArgs );
2789 # Workaround for PHP bug 35229 and similar
2790 if ( !is_callable( $callback ) ) {
2791 wfProfileOut( __METHOD__
. '-pfunc' );
2792 wfProfileOut( __METHOD__
);
2793 throw new MWException( "Tag hook for $function is not callable\n" );
2795 $result = call_user_func_array( $callback, $allArgs );
2798 $preprocessFlags = 0;
2800 if ( is_array( $result ) ) {
2801 if ( isset( $result[0] ) ) {
2803 unset( $result[0] );
2806 // Extract flags into the local scope
2807 // This allows callers to set flags such as nowiki, found, etc.
2813 $text = $this->preprocessToDom( $text, $preprocessFlags );
2818 wfProfileOut( __METHOD__
. '-pfunc' );
2821 # Finish mangling title and then check for loops.
2822 # Set $title to a Title object and $titleText to the PDBK
2825 # Split the title into page and subpage
2827 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2828 if ($subpage !== '') {
2829 $ns = $this->mTitle
->getNamespace();
2831 $title = Title
::newFromText( $part1, $ns );
2833 $titleText = $title->getPrefixedText();
2834 # Check for language variants if the template is not found
2835 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2836 $wgContLang->findVariantLink( $part1, $title, true );
2838 # Do recursion depth check
2839 $limit = $this->mOptions
->getMaxTemplateDepth();
2840 if ( $frame->depth
>= $limit ) {
2842 $text = '<span class="error">' . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit ) . '</span>';
2847 # Load from database
2848 if ( !$found && $title ) {
2849 wfProfileIn( __METHOD__
. '-loadtpl' );
2850 if ( !$title->isExternal() ) {
2851 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2852 $text = SpecialPage
::capturePath( $title );
2853 if ( is_string( $text ) ) {
2856 $this->disableCache();
2858 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2859 $found = false; //access denied
2860 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
2862 list( $text, $title ) = $this->getTemplateDom( $title );
2863 if ( $text !== false ) {
2869 # If the title is valid but undisplayable, make a link to it
2870 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2871 $text = "[[:$titleText]]";
2874 } elseif ( $title->isTrans() ) {
2875 // Interwiki transclusion
2876 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
2877 $text = $this->interwikiTransclude( $title, 'render' );
2880 $text = $this->interwikiTransclude( $title, 'raw' );
2881 // Preprocess it like a template
2882 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
2888 # Do infinite loop check
2889 # This has to be done after redirect resolution to avoid infinite loops via redirects
2890 if ( !$frame->loopCheck( $title ) ) {
2892 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
2893 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
2895 wfProfileOut( __METHOD__
. '-loadtpl' );
2898 # If we haven't found text to substitute by now, we're done
2899 # Recover the source wikitext and return it
2901 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2902 wfProfileOut( __METHOD__
);
2903 return array( 'object' => $text );
2906 # Expand DOM-style return values in a child frame
2907 if ( $isChildObj ) {
2908 # Clean up argument array
2909 $newFrame = $frame->newChild( $args, $title );
2912 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
2913 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
2914 # Expansion is eligible for the empty-frame cache
2915 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
2916 $text = $this->mTplExpandCache
[$titleText];
2918 $text = $newFrame->expand( $text );
2919 $this->mTplExpandCache
[$titleText] = $text;
2922 # Uncached expansion
2923 $text = $newFrame->expand( $text );
2926 if ( $isLocalObj && $nowiki ) {
2927 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
2928 $isLocalObj = false;
2931 # Replace raw HTML by a placeholder
2932 # Add a blank line preceding, to prevent it from mucking up
2933 # immediately preceding headings
2935 $text = "\n\n" . $this->insertStripItem( $text );
2937 # Escape nowiki-style return values
2938 elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2939 $text = wfEscapeWikiText( $text );
2941 # Bug 529: if the template begins with a table or block-level
2942 # element, it should be treated as beginning a new line.
2943 # This behaviour is somewhat controversial.
2944 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
2945 $text = "\n" . $text;
2948 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
2949 # Error, oversize inclusion
2950 $text = "[[$originalTitle]]" .
2951 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
2952 $this->limitationWarn( 'post-expand-template-inclusion' );
2955 if ( $isLocalObj ) {
2956 $ret = array( 'object' => $text );
2958 $ret = array( 'text' => $text );
2961 wfProfileOut( __METHOD__
);
2966 * Get the semi-parsed DOM representation of a template with a given title,
2967 * and its redirect destination title. Cached.
2969 function getTemplateDom( $title ) {
2970 $cacheTitle = $title;
2971 $titleText = $title->getPrefixedDBkey();
2973 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
2974 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
2975 $title = Title
::makeTitle( $ns, $dbk );
2976 $titleText = $title->getPrefixedDBkey();
2978 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
2979 return array( $this->mTplDomCache
[$titleText], $title );
2982 // Cache miss, go to the database
2983 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
2985 if ( $text === false ) {
2986 $this->mTplDomCache
[$titleText] = false;
2987 return array( false, $title );
2990 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
2991 $this->mTplDomCache
[ $titleText ] = $dom;
2993 if (! $title->equals($cacheTitle)) {
2994 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
2995 array( $title->getNamespace(),$cdb = $title->getDBkey() );
2998 return array( $dom, $title );
3002 * Fetch the unparsed text of a template and register a reference to it.
3004 function fetchTemplateAndTitle( $title ) {
3005 $templateCb = $this->mOptions
->getTemplateCallback();
3006 $stuff = call_user_func( $templateCb, $title, $this );
3007 $text = $stuff['text'];
3008 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3009 if ( isset( $stuff['deps'] ) ) {
3010 foreach ( $stuff['deps'] as $dep ) {
3011 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3014 return array($text,$finalTitle);
3017 function fetchTemplate( $title ) {
3018 $rv = $this->fetchTemplateAndTitle($title);
3023 * Static function to get a template
3024 * Can be overridden via ParserOptions::setTemplateCallback().
3026 static function statelessFetchTemplate( $title, $parser=false ) {
3027 $text = $skip = false;
3028 $finalTitle = $title;
3031 // Loop to fetch the article, with up to 1 redirect
3032 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3033 # Give extensions a chance to select the revision instead
3034 $id = false; // Assume current
3035 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3041 'page_id' => $title->getArticleID(),
3045 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3046 $rev_id = $rev ?
$rev->getId() : 0;
3047 // If there is no current revision, there is no page
3048 if( $id === false && !$rev ) {
3049 $linkCache = LinkCache
::singleton();
3050 $linkCache->addBadLinkObj( $title );
3055 'page_id' => $title->getArticleID(),
3056 'rev_id' => $rev_id );
3059 $text = $rev->getText();
3060 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3062 $message = $wgContLang->lcfirst( $title->getText() );
3063 $text = wfMsgForContentNoTrans( $message );
3064 if( wfEmptyMsg( $message, $text ) ) {
3071 if ( $text === false ) {
3075 $finalTitle = $title;
3076 $title = Title
::newFromRedirect( $text );
3080 'finalTitle' => $finalTitle,
3085 * Transclude an interwiki link.
3087 function interwikiTransclude( $title, $action ) {
3088 global $wgEnableScaryTranscluding;
3090 if (!$wgEnableScaryTranscluding)
3091 return wfMsg('scarytranscludedisabled');
3093 $url = $title->getFullUrl( "action=$action" );
3095 if (strlen($url) > 255)
3096 return wfMsg('scarytranscludetoolong');
3097 return $this->fetchScaryTemplateMaybeFromCache($url);
3100 function fetchScaryTemplateMaybeFromCache($url) {
3101 global $wgTranscludeCacheExpiry;
3102 $dbr = wfGetDB(DB_SLAVE
);
3103 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3104 array('tc_url' => $url));
3106 $time = $obj->tc_time
;
3107 $text = $obj->tc_contents
;
3108 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3113 $text = Http
::get($url);
3115 return wfMsg('scarytranscludefailed', $url);
3117 $dbw = wfGetDB(DB_MASTER
);
3118 $dbw->replace('transcache', array('tc_url'), array(
3120 'tc_time' => time(),
3121 'tc_contents' => $text));
3127 * Triple brace replacement -- used for template arguments
3130 function argSubstitution( $piece, $frame ) {
3131 wfProfileIn( __METHOD__
);
3134 $parts = $piece['parts'];
3135 $nameWithSpaces = $frame->expand( $piece['title'] );
3136 $argName = trim( $nameWithSpaces );
3138 $text = $frame->getArgument( $argName );
3139 if ( $text === false && $parts->getLength() > 0
3143 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3146 # No match in frame, use the supplied default
3147 $object = $parts->item( 0 )->getChildren();
3149 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3150 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3151 $this->limitationWarn( 'post-expand-template-argument' );
3154 if ( $text === false && $object === false ) {
3156 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3158 if ( $error !== false ) {
3161 if ( $object !== false ) {
3162 $ret = array( 'object' => $object );
3164 $ret = array( 'text' => $text );
3167 wfProfileOut( __METHOD__
);
3172 * Return the text to be used for a given extension tag.
3173 * This is the ghost of strip().
3175 * @param array $params Associative array of parameters:
3176 * name PPNode for the tag name
3177 * attr PPNode for unparsed text where tag attributes are thought to be
3178 * attributes Optional associative array of parsed attributes
3179 * inner Contents of extension element
3180 * noClose Original text did not have a close tag
3181 * @param PPFrame $frame
3183 function extensionSubstitution( $params, $frame ) {
3184 global $wgRawHtml, $wgContLang;
3186 $name = $frame->expand( $params['name'] );
3187 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3188 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3190 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3192 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3193 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3194 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3195 $name = strtolower( $name );
3196 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3197 if ( isset( $params['attributes'] ) ) {
3198 $attributes = $attributes +
$params['attributes'];
3206 throw new MWException( '<html> extension tag encountered unexpectedly' );
3209 $content = strtr($content, array('-{' => '-{', '}-' => '}-'));
3210 $output = Xml
::escapeTagsOnly( $content );
3213 $output = $wgContLang->armourMath(
3214 MathRenderer
::renderMath( $content, $attributes ) );
3217 $output = $this->renderImageGallery( $content, $attributes );
3220 if( isset( $this->mTagHooks
[$name] ) ) {
3221 # Workaround for PHP bug 35229 and similar
3222 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3223 throw new MWException( "Tag hook for $name is not callable\n" );
3225 $output = call_user_func_array( $this->mTagHooks
[$name],
3226 array( $content, $attributes, $this ) );
3227 } elseif( isset( $this->mFunctionTagHooks
[$name] ) ) {
3228 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3229 if( !is_callable( $callback ) )
3230 throw new MWException( "Tag hook for $name is not callable\n" );
3232 $output = call_user_func_array( $callback,
3233 array( &$this, $frame, $content, $attributes ) );
3235 $output = '<span class="error">Invalid tag extension name: ' .
3236 htmlspecialchars( $name ) . '</span>';
3240 if ( is_null( $attrText ) ) {
3243 if ( isset( $params['attributes'] ) ) {
3244 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3245 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3246 htmlspecialchars( $attrValue ) . '"';
3249 if ( $content === null ) {
3250 $output = "<$name$attrText/>";
3252 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3253 $output = "<$name$attrText>$content$close";
3257 if( $isFunctionTag ) {
3259 } elseif ( $name === 'html' ||
$name === 'nowiki' ) {
3260 $this->mStripState
->nowiki
->setPair( $marker, $output );
3262 $this->mStripState
->general
->setPair( $marker, $output );
3268 * Increment an include size counter
3270 * @param string $type The type of expansion
3271 * @param integer $size The size of the text
3272 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3274 function incrementIncludeSize( $type, $size ) {
3275 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3278 $this->mIncludeSizes
[$type] +
= $size;
3284 * Increment the expensive function count
3286 * @return boolean False if the limit has been exceeded
3288 function incrementExpensiveFunctionCount() {
3289 global $wgExpensiveParserFunctionLimit;
3290 $this->mExpensiveFunctionCount++
;
3291 if($this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit) {
3298 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3299 * Fills $this->mDoubleUnderscores, returns the modified text
3301 function doDoubleUnderscore( $text ) {
3302 wfProfileIn( __METHOD__
);
3303 // The position of __TOC__ needs to be recorded
3304 $mw = MagicWord
::get( 'toc' );
3305 if( $mw->match( $text ) ) {
3306 $this->mShowToc
= true;
3307 $this->mForceTocPosition
= true;
3309 // Set a placeholder. At the end we'll fill it in with the TOC.
3310 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3312 // Only keep the first one.
3313 $text = $mw->replace( '', $text );
3316 // Now match and remove the rest of them
3317 $mwa = MagicWord
::getDoubleUnderscoreArray();
3318 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3320 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3321 $this->mOutput
->mNoGallery
= true;
3323 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3324 $this->mShowToc
= false;
3326 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3327 $this->mOutput
->setProperty( 'hiddencat', 'y' );
3329 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( 'hidden-category-category' ) );
3330 if ( $containerCategory ) {
3331 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3333 wfDebug( __METHOD__
.": [[MediaWiki:hidden-category-category]] is not a valid title!\n" );
3336 # (bug 8068) Allow control over whether robots index a page.
3338 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3339 # is not desirable, the last one on the page should win.
3340 if( isset( $this->mDoubleUnderscores
['noindex'] ) ) {
3341 $this->mOutput
->setIndexPolicy( 'noindex' );
3342 } elseif( isset( $this->mDoubleUnderscores
['index'] ) ) {
3343 $this->mOutput
->setIndexPolicy( 'index' );
3345 wfProfileOut( __METHOD__
);
3350 * This function accomplishes several tasks:
3351 * 1) Auto-number headings if that option is enabled
3352 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3353 * 3) Add a Table of contents on the top for users who have enabled the option
3354 * 4) Auto-anchor headings
3356 * It loops through all headlines, collects the necessary data, then splits up the
3357 * string and re-inserts the newly formatted headlines.
3359 * @param string $text
3360 * @param string $origText Original, untouched wikitext
3361 * @param boolean $isMain
3364 function formatHeadings( $text, $origText, $isMain=true ) {
3365 global $wgMaxTocLevel, $wgContLang, $wgEnforceHtmlIds;
3367 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3368 $showEditLink = $this->mOptions
->getEditSection();
3370 // Do not call quickUserCan unless necessary
3371 if( $showEditLink && !$this->mTitle
->quickUserCan( 'edit' ) ) {
3375 # Inhibit editsection links if requested in the page
3376 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ||
$this->mOptions
->getIsPrintable() ) {
3380 # Get all headlines for numbering them and adding funky stuff like [edit]
3381 # links - this is for later, but we need the number of headlines right now
3383 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3385 # if there are fewer than 4 headlines in the article, do not show TOC
3386 # unless it's been explicitly enabled.
3387 $enoughToc = $this->mShowToc
&&
3388 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3390 # Allow user to stipulate that a page should have a "new section"
3391 # link added via __NEWSECTIONLINK__
3392 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3393 $this->mOutput
->setNewSection( true );
3396 # Allow user to remove the "new section"
3397 # link via __NONEWSECTIONLINK__
3398 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3399 $this->mOutput
->hideNewSection( true );
3402 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3403 # override above conditions and always show TOC above first header
3404 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3405 $this->mShowToc
= true;
3409 # We need this to perform operations on the HTML
3410 $sk = $this->mOptions
->getSkin();
3416 # Ugh .. the TOC should have neat indentation levels which can be
3417 # passed to the skin functions. These are determined here
3421 $sublevelCount = array();
3422 $levelCount = array();
3428 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3429 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3430 $oldType = $this->mOutputType
;
3431 $this->setOutputType( self
::OT_WIKI
);
3432 $frame = $this->getPreprocessor()->newFrame();
3433 $root = $this->preprocessToDom( $origText );
3434 $node = $root->getFirstChild();
3438 foreach( $matches[3] as $headline ) {
3439 $isTemplate = false;
3441 $sectionIndex = false;
3443 $markerMatches = array();
3444 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3445 $serial = $markerMatches[1];
3446 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3447 $isTemplate = ($titleText != $baseTitleText);
3448 $headline = preg_replace("/^$markerRegex/", "", $headline);
3452 $prevlevel = $level;
3453 $prevtoclevel = $toclevel;
3455 $level = $matches[1][$headlineCount];
3457 if ( $level > $prevlevel ) {
3458 # Increase TOC level
3460 $sublevelCount[$toclevel] = 0;
3461 if( $toclevel<$wgMaxTocLevel ) {
3462 $prevtoclevel = $toclevel;
3463 $toc .= $sk->tocIndent();
3467 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3468 # Decrease TOC level, find level to jump to
3470 for ($i = $toclevel; $i > 0; $i--) {
3471 if ( $levelCount[$i] == $level ) {
3472 # Found last matching level
3476 elseif ( $levelCount[$i] < $level ) {
3477 # Found first matching level below current level
3482 if( $i == 0 ) $toclevel = 1;
3483 if( $toclevel<$wgMaxTocLevel ) {
3484 if($prevtoclevel < $wgMaxTocLevel) {
3485 # Unindent only if the previous toc level was shown :p
3486 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3487 $prevtoclevel = $toclevel;
3489 $toc .= $sk->tocLineEnd();
3494 # No change in level, end TOC line
3495 if( $toclevel<$wgMaxTocLevel ) {
3496 $toc .= $sk->tocLineEnd();
3500 $levelCount[$toclevel] = $level;
3502 # count number of headlines for each level
3503 @$sublevelCount[$toclevel]++
;
3505 for( $i = 1; $i <= $toclevel; $i++
) {
3506 if( !empty( $sublevelCount[$i] ) ) {
3510 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3515 # The safe header is a version of the header text safe to use for links
3516 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3517 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3519 # Remove link placeholders by the link text.
3520 # <!--LINK number-->
3522 # link text with suffix
3523 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3525 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3526 $tocline = preg_replace(
3527 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3531 $tocline = trim( $tocline );
3533 # For the anchor, strip out HTML-y stuff period
3534 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3535 $safeHeadline = preg_replace( '/[ _]+/', ' ', $safeHeadline );
3536 $safeHeadline = trim( $safeHeadline );
3538 # Save headline for section edit hint before it's escaped
3539 $headlineHint = $safeHeadline;
3541 if ( $wgEnforceHtmlIds ) {
3542 $legacyHeadline = false;
3543 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
3546 # For reverse compatibility, provide an id that's
3547 # HTML4-compatible, like we used to.
3549 # It may be worth noting, academically, that it's possible for
3550 # the legacy anchor to conflict with a non-legacy headline
3551 # anchor on the page. In this case likely the "correct" thing
3552 # would be to either drop the legacy anchors or make sure
3553 # they're numbered first. However, this would require people
3554 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3555 # manually, so let's not bother worrying about it.
3556 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
3558 $safeHeadline = Sanitizer
::escapeId( $safeHeadline, 'xml' );
3560 if ( $legacyHeadline == $safeHeadline ) {
3561 # No reason to have both (in fact, we can't)
3562 $legacyHeadline = false;
3563 } elseif ( $legacyHeadline != Sanitizer
::escapeId(
3564 $legacyHeadline, 'xml' ) ) {
3565 # The legacy id is invalid XML. We used to allow this, but
3566 # there's no reason to do so anymore. Backward
3567 # compatibility will fail slightly in this case, but it's
3569 $legacyHeadline = false;
3573 # HTML names must be case-insensitively unique (bug 10721). FIXME:
3574 # Does this apply to Unicode characters? Because we aren't
3575 # handling those here.
3576 $arrayKey = strtolower( $safeHeadline );
3577 if ( $legacyHeadline === false ) {
3578 $legacyArrayKey = false;
3580 $legacyArrayKey = strtolower( $legacyHeadline );
3583 # count how many in assoc. array so we can track dupes in anchors
3584 if ( isset( $refers[$arrayKey] ) ) {
3585 $refers[$arrayKey]++
;
3587 $refers[$arrayKey] = 1;
3589 if ( isset( $refers[$legacyArrayKey] ) ) {
3590 $refers[$legacyArrayKey]++
;
3592 $refers[$legacyArrayKey] = 1;
3595 # Don't number the heading if it is the only one (looks silly)
3596 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3597 # the two are different if the line contains a link
3598 $headline=$numbering . ' ' . $headline;
3601 # Create the anchor for linking from the TOC to the section
3602 $anchor = $safeHeadline;
3603 $legacyAnchor = $legacyHeadline;
3604 if ( $refers[$arrayKey] > 1 ) {
3605 $anchor .= '_' . $refers[$arrayKey];
3607 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3608 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3610 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3611 $toc .= $sk->tocLine($anchor, $tocline,
3612 $numbering, $toclevel, ($isTemplate ?
false : $sectionIndex));
3615 # Add the section to the section tree
3616 # Find the DOM node for this header
3617 while ( $node && !$isTemplate ) {
3618 if ( $node->getName() === 'h' ) {
3619 $bits = $node->splitHeading();
3620 if ( $bits['i'] == $sectionIndex )
3623 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
3624 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
3625 $node = $node->getNextSibling();
3628 'toclevel' => $toclevel,
3631 'number' => $numbering,
3632 'index' => ($isTemplate ?
'T-' : '' ) . $sectionIndex,
3633 'fromtitle' => $titleText,
3634 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
3635 'anchor' => $anchor,
3638 # give headline the correct <h#> tag
3639 if( $showEditLink && $sectionIndex !== false ) {
3641 # Put a T flag in the section identifier, to indicate to extractSections()
3642 # that sections inside <includeonly> should be counted.
3643 $editlink = $sk->doEditSectionLink(Title
::newFromText( $titleText ), "T-$sectionIndex");
3645 $editlink = $sk->doEditSectionLink($this->mTitle
, $sectionIndex, $headlineHint);
3650 $head[$headlineCount] = $sk->makeHeadline( $level,
3651 $matches['attrib'][$headlineCount], $anchor, $headline,
3652 $editlink, $legacyAnchor );
3657 $this->setOutputType( $oldType );
3659 # Never ever show TOC if no headers
3660 if( $numVisible < 1 ) {
3665 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3666 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3668 $toc = $sk->tocList( $toc );
3669 $this->mOutput
->setTOCHTML( $toc );
3673 $this->mOutput
->setSections( $tocraw );
3676 # split up and insert constructed headlines
3678 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3681 foreach( $blocks as $block ) {
3682 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3683 # This is the [edit] link that appears for the top block of text when
3684 # section editing is enabled
3686 # Disabled because it broke block formatting
3687 # For example, a bullet point in the top line
3688 # $full .= $sk->editSectionLink(0);
3691 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3692 # Top anchor now in skin
3696 if( !empty( $head[$i] ) ) {
3701 if( $this->mForceTocPosition
) {
3702 return str_replace( '<!--MWTOC-->', $toc, $full );
3709 * Merge $tree2 into $tree1 by replacing the section with index
3710 * $section in $tree1 and its descendants with the sections in $tree2.
3711 * Note that in the returned section tree, only the 'index' and
3712 * 'byteoffset' fields are guaranteed to be correct.
3713 * @param $tree1 array Section tree from ParserOutput::getSectons()
3714 * @param $tree2 array Section tree
3715 * @param $section int Section index
3716 * @param $title Title Title both section trees come from
3717 * @param $len2 int Length of the original wikitext for $tree2
3718 * @return array Merged section tree
3720 public static function mergeSectionTrees( $tree1, $tree2, $section, $title, $len2 ) {
3723 $targetLevel = false;
3727 $numbering = array( 0 );
3728 $titletext = $title->getPrefixedDBkey();
3729 foreach ( $tree1 as $s ) {
3730 if ( $targetLevel !== false ) {
3731 if ( $s['level'] <= $targetLevel )
3732 // We've skipped enough
3733 $targetLevel = false;
3737 if ( $s['index'] != $section ||
3738 $s['fromtitle'] != $titletext ) {
3739 self
::incrementNumbering( $numbering,
3740 $s['toclevel'], $lastLevel );
3742 // Rewrite index, byteoffset and number
3743 if ( $s['fromtitle'] == $titletext ) {
3744 $s['index'] = $nextIndex++
;
3746 $s['byteoffset'] +
= $len2;
3748 $s['number'] = implode( '.', array_map(
3749 array( $wgContLang, 'formatnum' ),
3751 $lastLevel = $s['toclevel'];
3754 // We're at $section
3755 // Insert sections from $tree2 here
3756 foreach ( $tree2 as $s2 ) {
3757 // Rewrite the fields in $s2
3758 // before inserting it
3759 $s2['toclevel'] +
= $s['toclevel'] - 1;
3760 $s2['level'] +
= $s['level'] - 1;
3761 $s2['index'] = $nextIndex++
;
3762 $s2['byteoffset'] +
= $s['byteoffset'];
3764 self
::incrementNumbering( $numbering,
3765 $s2['toclevel'], $lastLevel );
3766 $s2['number'] = implode( '.', array_map(
3767 array( $wgContLang, 'formatnum' ),
3769 $lastLevel = $s2['toclevel'];
3772 // Skip all descendants of $section in $tree1
3773 $targetLevel = $s['level'];
3781 * Increment a section number. Helper function for mergeSectionTrees()
3782 * @param $number array Array representing a section number
3783 * @param $level int Current TOC level (depth)
3784 * @param $lastLevel int Level of previous TOC entry
3786 private static function incrementNumbering( &$number, $level, $lastLevel ) {
3787 if ( $level > $lastLevel )
3788 $number[$level - 1] = 1;
3789 else if ( $level < $lastLevel ) {
3790 foreach ( $number as $key => $unused )
3791 if ( $key >= $level )
3792 unset( $number[$key] );
3793 $number[$level - 1]++
;
3795 $number[$level - 1]++
;
3799 * Transform wiki markup when saving a page by doing \r\n -> \n
3800 * conversion, substitting signatures, {{subst:}} templates, etc.
3802 * @param string $text the text to transform
3803 * @param Title &$title the Title object for the current article
3804 * @param User $user the User object describing the current user
3805 * @param ParserOptions $options parsing options
3806 * @param bool $clearState whether to clear the parser state first
3807 * @return string the altered wiki markup
3810 function preSaveTransform( $text, Title
$title, $user, $options, $clearState = true ) {
3811 $this->mOptions
= $options;
3812 $this->setTitle( $title );
3813 $this->setOutputType( self
::OT_WIKI
);
3815 if ( $clearState ) {
3816 $this->clearState();
3822 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3823 $text = $this->pstPass2( $text, $user );
3824 $text = $this->mStripState
->unstripBoth( $text );
3829 * Pre-save transform helper function
3832 function pstPass2( $text, $user ) {
3833 global $wgContLang, $wgLocaltimezone;
3835 /* Note: This is the timestamp saved as hardcoded wikitext to
3836 * the database, we use $wgContLang here in order to give
3837 * everyone the same signature and use the default one rather
3838 * than the one selected in each user's preferences.
3840 * (see also bug 12815)
3842 $ts = $this->mOptions
->getTimestamp();
3843 $tz = wfMsgForContent( 'timezone-utc' );
3844 if ( isset( $wgLocaltimezone ) ) {
3845 $unixts = wfTimestamp( TS_UNIX
, $ts );
3846 $oldtz = getenv( 'TZ' );
3847 putenv( 'TZ='.$wgLocaltimezone );
3848 $ts = date( 'YmdHis', $unixts );
3849 $tz = date( 'T', $unixts ); # might vary on DST changeover!
3851 /* Allow translation of timezones trough wiki. date() can return
3852 * whatever crap the system uses, localised or not, so we cannot
3853 * ship premade translations.
3855 $key = 'timezone-' . strtolower( trim( $tz ) );
3856 $value = wfMsgForContent( $key );
3857 if ( !wfEmptyMsg( $key, $value ) ) $tz = $value;
3859 putenv( 'TZ='.$oldtz );
3862 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tz)";
3864 # Variable replacement
3865 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3866 $text = $this->replaceVariables( $text );
3869 $sigText = $this->getUserSig( $user );
3870 $text = strtr( $text, array(
3872 '~~~~' => "$sigText $d",
3876 # Context links: [[|name]] and [[name (context)|]]
3878 global $wgLegalTitleChars;
3879 $tc = "[$wgLegalTitleChars]";
3880 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
3882 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3883 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
3884 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3885 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3887 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3888 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3889 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
3890 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3892 $t = $this->mTitle
->getText();
3894 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3895 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3896 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3897 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3899 # if there's no context, don't bother duplicating the title
3900 $text = preg_replace( $p2, '[[\\1]]', $text );
3903 # Trim trailing whitespace
3904 $text = rtrim( $text );
3910 * Fetch the user's signature text, if any, and normalize to
3911 * validated, ready-to-insert wikitext.
3917 function getUserSig( &$user ) {
3918 global $wgMaxSigChars;
3920 $username = $user->getName();
3921 $nickname = $user->getOption( 'nickname' );
3922 $nickname = $nickname === null ?
$username : $nickname;
3924 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3925 $nickname = $username;
3926 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
3927 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3928 # Sig. might contain markup; validate this
3929 if( $this->validateSig( $nickname ) !== false ) {
3930 # Validated; clean up (if needed) and return it
3931 return $this->cleanSig( $nickname, true );
3933 # Failed to validate; fall back to the default
3934 $nickname = $username;
3935 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
3939 // Make sure nickname doesnt get a sig in a sig
3940 $nickname = $this->cleanSigInSig( $nickname );
3942 # If we're still here, make it a link to the user page
3943 $userText = wfEscapeWikiText( $username );
3944 $nickText = wfEscapeWikiText( $nickname );
3945 if ( $user->isAnon() ) {
3946 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
3948 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
3953 * Check that the user's signature contains no bad XML
3955 * @param string $text
3956 * @return mixed An expanded string, or false if invalid.
3958 function validateSig( $text ) {
3959 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
3963 * Clean up signature text
3965 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
3966 * 2) Substitute all transclusions
3968 * @param string $text
3969 * @param $parsing Whether we're cleaning (preferences save) or parsing
3970 * @return string Signature text
3972 function cleanSig( $text, $parsing = false ) {
3975 $this->clearState();
3976 $this->setTitle( $wgTitle );
3977 $this->mOptions
= new ParserOptions
;
3978 $this->setOutputType
= self
::OT_PREPROCESS
;
3981 # Option to disable this feature
3982 if ( !$this->mOptions
->getCleanSignatures() ) {
3986 # FIXME: regex doesn't respect extension tags or nowiki
3987 # => Move this logic to braceSubstitution()
3988 $substWord = MagicWord
::get( 'subst' );
3989 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
3990 $substText = '{{' . $substWord->getSynonym( 0 );
3992 $text = preg_replace( $substRegex, $substText, $text );
3993 $text = $this->cleanSigInSig( $text );
3994 $dom = $this->preprocessToDom( $text );
3995 $frame = $this->getPreprocessor()->newFrame();
3996 $text = $frame->expand( $dom );
3999 $text = $this->mStripState
->unstripBoth( $text );
4006 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4007 * @param string $text
4008 * @return string Signature text with /~{3,5}/ removed
4010 function cleanSigInSig( $text ) {
4011 $text = preg_replace( '/~{3,5}/', '', $text );
4016 * Set up some variables which are usually set up in parse()
4017 * so that an external function can call some class members with confidence
4020 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
4021 $this->setTitle( $title );
4022 $this->mOptions
= $options;
4023 $this->setOutputType( $outputType );
4024 if ( $clearState ) {
4025 $this->clearState();
4030 * Wrapper for preprocess()
4032 * @param string $text the text to preprocess
4033 * @param ParserOptions $options options
4037 function transformMsg( $text, $options ) {
4039 static $executing = false;
4041 # Guard against infinite recursion
4047 wfProfileIn(__METHOD__
);
4048 $text = $this->preprocess( $text, $wgTitle, $options );
4051 wfProfileOut(__METHOD__
);
4056 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4057 * The callback should have the following form:
4058 * function myParserHook( $text, $params, &$parser ) { ... }
4060 * Transform and return $text. Use $parser for any required context, e.g. use
4061 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4065 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
4066 * @param mixed $callback The callback function (and object) to use for the tag
4068 * @return The old value of the mTagHooks array associated with the hook
4070 function setHook( $tag, $callback ) {
4071 $tag = strtolower( $tag );
4072 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4073 $this->mTagHooks
[$tag] = $callback;
4074 if( !in_array( $tag, $this->mStripList
) ) {
4075 $this->mStripList
[] = $tag;
4081 function setTransparentTagHook( $tag, $callback ) {
4082 $tag = strtolower( $tag );
4083 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4084 $this->mTransparentTagHooks
[$tag] = $callback;
4090 * Remove all tag hooks
4092 function clearTagHooks() {
4093 $this->mTagHooks
= array();
4094 $this->mStripList
= $this->mDefaultStripList
;
4098 * Create a function, e.g. {{sum:1|2|3}}
4099 * The callback function should have the form:
4100 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4102 * Or with SFH_OBJECT_ARGS:
4103 * function myParserFunction( $parser, $frame, $args ) { ... }
4105 * The callback may either return the text result of the function, or an array with the text
4106 * in element 0, and a number of flags in the other elements. The names of the flags are
4107 * specified in the keys. Valid flags are:
4108 * found The text returned is valid, stop processing the template. This
4110 * nowiki Wiki markup in the return value should be escaped
4111 * isHTML The returned text is HTML, armour it against wikitext transformation
4115 * @param string $id The magic word ID
4116 * @param mixed $callback The callback function (and object) to use
4117 * @param integer $flags a combination of the following flags:
4118 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4120 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4121 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4122 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4123 * the arguments, and to control the way they are expanded.
4125 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4126 * arguments, for instance:
4127 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4129 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4130 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4131 * working if/when this is changed.
4133 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4136 * Please read the documentation in includes/parser/Preprocessor.php for more information
4137 * about the methods available in PPFrame and PPNode.
4139 * @return The old callback function for this name, if any
4141 function setFunctionHook( $id, $callback, $flags = 0 ) {
4142 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4143 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4145 # Add to function cache
4146 $mw = MagicWord
::get( $id );
4148 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4150 $synonyms = $mw->getSynonyms();
4151 $sensitive = intval( $mw->isCaseSensitive() );
4153 foreach ( $synonyms as $syn ) {
4155 if ( !$sensitive ) {
4156 $syn = strtolower( $syn );
4159 if ( !( $flags & SFH_NO_HASH
) ) {
4162 # Remove trailing colon
4163 if ( substr( $syn, -1, 1 ) === ':' ) {
4164 $syn = substr( $syn, 0, -1 );
4166 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4172 * Get all registered function hook identifiers
4176 function getFunctionHooks() {
4177 return array_keys( $this->mFunctionHooks
);
4181 * Create a tag function, e.g. <test>some stuff</test>.
4182 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4183 * Unlike parser functions, their content is not preprocessed.
4185 function setFunctionTagHook( $tag, $callback, $flags ) {
4186 $tag = strtolower( $tag );
4187 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4188 $this->mFunctionTagHooks
[$tag] : null;
4189 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4191 if( !in_array( $tag, $this->mStripList
) ) {
4192 $this->mStripList
[] = $tag;
4199 * FIXME: update documentation. makeLinkObj() is deprecated.
4200 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4201 * Placeholders created in Skin::makeLinkObj()
4202 * Returns an array of link CSS classes, indexed by PDBK.
4204 function replaceLinkHolders( &$text, $options = 0 ) {
4205 return $this->mLinkHolders
->replace( $text );
4209 * Replace <!--LINK--> link placeholders with plain text of links
4210 * (not HTML-formatted).
4211 * @param string $text
4214 function replaceLinkHoldersText( $text ) {
4215 return $this->mLinkHolders
->replaceText( $text );
4219 * Tag hook handler for 'pre'.
4221 function renderPreTag( $text, $attribs ) {
4222 // Backwards-compatibility hack
4223 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4225 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4226 return Xml
::openElement( 'pre', $attribs ) .
4227 Xml
::escapeTagsOnly( $content ) .
4232 * Renders an image gallery from a text with one line per image.
4233 * text labels may be given by using |-style alternative text. E.g.
4234 * Image:one.jpg|The number "1"
4235 * Image:tree.jpg|A tree
4236 * given as text will return the HTML of a gallery with two images,
4237 * labeled 'The number "1"' and
4240 function renderImageGallery( $text, $params ) {
4241 $ig = new ImageGallery();
4242 $ig->setContextTitle( $this->mTitle
);
4243 $ig->setShowBytes( false );
4244 $ig->setShowFilename( false );
4245 $ig->setParser( $this );
4246 $ig->setHideBadImages();
4247 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4248 $ig->useSkin( $this->mOptions
->getSkin() );
4249 $ig->mRevisionId
= $this->mRevisionId
;
4251 if( isset( $params['caption'] ) ) {
4252 $caption = $params['caption'];
4253 $caption = htmlspecialchars( $caption );
4254 $caption = $this->replaceInternalLinks( $caption );
4255 $ig->setCaptionHtml( $caption );
4257 if( isset( $params['perrow'] ) ) {
4258 $ig->setPerRow( $params['perrow'] );
4260 if( isset( $params['widths'] ) ) {
4261 $ig->setWidths( $params['widths'] );
4263 if( isset( $params['heights'] ) ) {
4264 $ig->setHeights( $params['heights'] );
4267 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4269 $lines = StringUtils
::explode( "\n", $text );
4270 foreach ( $lines as $line ) {
4271 # match lines like these:
4272 # Image:someimage.jpg|This is some image
4274 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4276 if ( count( $matches ) == 0 ) {
4280 if ( strpos( $matches[0], '%' ) !== false )
4281 $matches[1] = urldecode( $matches[1] );
4282 $tp = Title
::newFromText( $matches[1]/*, NS_FILE*/ );
4284 if( is_null( $nt ) ) {
4285 # Bogus title. Ignore these so we don't bomb out later.
4288 if ( isset( $matches[3] ) ) {
4289 $label = $matches[3];
4294 $html = $this->recursiveTagParse( trim( $label ) );
4296 $ig->add( $nt, $html );
4298 # Only add real images (bug #5586)
4299 if ( $nt->getNamespace() == NS_FILE
) {
4300 $this->mOutput
->addImage( $nt->getDBkey() );
4303 return $ig->toHTML();
4306 function getImageParams( $handler ) {
4308 $handlerClass = get_class( $handler );
4312 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4313 // Initialise static lists
4314 static $internalParamNames = array(
4315 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4316 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4317 'bottom', 'text-bottom' ),
4318 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4319 'upright', 'border', 'link', 'alt' ),
4321 static $internalParamMap;
4322 if ( !$internalParamMap ) {
4323 $internalParamMap = array();
4324 foreach ( $internalParamNames as $type => $names ) {
4325 foreach ( $names as $name ) {
4326 $magicName = str_replace( '-', '_', "img_$name" );
4327 $internalParamMap[$magicName] = array( $type, $name );
4332 // Add handler params
4333 $paramMap = $internalParamMap;
4335 $handlerParamMap = $handler->getParamMap();
4336 foreach ( $handlerParamMap as $magic => $paramName ) {
4337 $paramMap[$magic] = array( 'handler', $paramName );
4340 $this->mImageParams
[$handlerClass] = $paramMap;
4341 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4343 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4347 * Parse image options text and use it to make an image
4348 * @param Title $title
4349 * @param string $options
4350 * @param LinkHolderArray $holders
4352 function makeImage( $title, $options, $holders = false ) {
4353 # Check if the options text is of the form "options|alt text"
4355 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4356 # * left no resizing, just left align. label is used for alt= only
4357 # * right same, but right aligned
4358 # * none same, but not aligned
4359 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4360 # * center center the image
4361 # * frame Keep original image size, no magnify-button.
4362 # * framed Same as "frame"
4363 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4364 # * upright reduce width for upright images, rounded to full __0 px
4365 # * border draw a 1px border around the image
4366 # * alt Text for HTML alt attribute (defaults to empty)
4367 # * link Set the target of the image link. Can be external, interwiki, or local
4368 # vertical-align values (no % or length right now):
4378 $parts = StringUtils
::explode( "|", $options );
4379 $sk = $this->mOptions
->getSkin();
4381 # Give extensions a chance to select the file revision for us
4382 $skip = $time = $descQuery = false;
4383 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4386 return $sk->link( $title );
4390 $imagename = $title->getDBkey();
4391 if ( isset( $this->mFileCache
[$imagename][$time] ) ) {
4392 $file = $this->mFileCache
[$imagename][$time];
4394 $file = wfFindFile( $title, $time );
4395 if ( count( $this->mFileCache
) > 1000 ) {
4396 $this->mFileCache
= array();
4398 $this->mFileCache
[$imagename][$time] = $file;
4401 $handler = $file ?
$file->getHandler() : false;
4403 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4405 # Process the input parameters
4407 $params = array( 'frame' => array(), 'handler' => array(),
4408 'horizAlign' => array(), 'vertAlign' => array() );
4409 foreach( $parts as $part ) {
4410 $part = trim( $part );
4411 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4413 if( isset( $paramMap[$magicName] ) ) {
4414 list( $type, $paramName ) = $paramMap[$magicName];
4416 // Special case; width and height come in one variable together
4417 if( $type === 'handler' && $paramName === 'width' ) {
4419 # (bug 13500) In both cases (width/height and width only),
4420 # permit trailing "px" for backward compatibility.
4421 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4422 $width = intval( $m[1] );
4423 $height = intval( $m[2] );
4424 if ( $handler->validateParam( 'width', $width ) ) {
4425 $params[$type]['width'] = $width;
4428 if ( $handler->validateParam( 'height', $height ) ) {
4429 $params[$type]['height'] = $height;
4432 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4433 $width = intval( $value );
4434 if ( $handler->validateParam( 'width', $width ) ) {
4435 $params[$type]['width'] = $width;
4438 } // else no validation -- bug 13436
4440 if ( $type === 'handler' ) {
4441 # Validate handler parameter
4442 $validated = $handler->validateParam( $paramName, $value );
4444 # Validate internal parameters
4445 switch( $paramName ) {
4448 // @fixme - possibly check validity here for
4449 // manualthumb? downstream behavior seems odd with
4450 // missing manual thumbs.
4452 $value = $this->stripAltText( $value, $holders );
4455 $chars = self
::EXT_LINK_URL_CLASS
;
4456 $prots = $this->mUrlProtocols
;
4457 if ( $value === '' ) {
4458 $paramName = 'no-link';
4461 } elseif ( preg_match( "/^$prots/", $value ) ) {
4462 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4463 $paramName = 'link-url';
4464 $this->mOutput
->addExternalLink( $value );
4468 $linkTitle = Title
::newFromText( $value );
4470 $paramName = 'link-title';
4471 $value = $linkTitle;
4472 $this->mOutput
->addLink( $linkTitle );
4478 // Most other things appear to be empty or numeric...
4479 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4484 $params[$type][$paramName] = $value;
4488 if ( !$validated ) {
4493 # Process alignment parameters
4494 if ( $params['horizAlign'] ) {
4495 $params['frame']['align'] = key( $params['horizAlign'] );
4497 if ( $params['vertAlign'] ) {
4498 $params['frame']['valign'] = key( $params['vertAlign'] );
4501 $params['frame']['caption'] = $caption;
4503 # Will the image be presented in a frame, with the caption below?
4504 $imageIsFramed = isset( $params['frame']['frame'] ) ||
4505 isset( $params['frame']['framed'] ) ||
4506 isset( $params['frame']['thumbnail'] ) ||
4507 isset( $params['frame']['manualthumb'] );
4509 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4510 # came to also set the caption, ordinary text after the image -- which
4511 # makes no sense, because that just repeats the text multiple times in
4512 # screen readers. It *also* came to set the title attribute.
4514 # Now that we have an alt attribute, we should not set the alt text to
4515 # equal the caption: that's worse than useless, it just repeats the
4516 # text. This is the framed/thumbnail case. If there's no caption, we
4517 # use the unnamed parameter for alt text as well, just for the time be-
4518 # ing, if the unnamed param is set and the alt param is not.
4520 # For the future, we need to figure out if we want to tweak this more,
4521 # e.g., introducing a title= parameter for the title; ignoring the un-
4522 # named parameter entirely for images without a caption; adding an ex-
4523 # plicit caption= parameter and preserving the old magic unnamed para-
4525 if ( $imageIsFramed ) { # Framed image
4526 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
4527 # No caption or alt text, add the filename as the alt text so
4528 # that screen readers at least get some description of the image
4529 $params['frame']['alt'] = $title->getText();
4531 # Do not set $params['frame']['title'] because tooltips don't make sense
4533 } else { # Inline image
4534 if ( !isset( $params['frame']['alt'] ) ) {
4535 # No alt text, use the "caption" for the alt text
4536 if ( $caption !== '') {
4537 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
4539 # No caption, fall back to using the filename for the
4541 $params['frame']['alt'] = $title->getText();
4544 # Use the "caption" for the tooltip text
4545 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4548 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4550 # Linker does the rest
4551 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4553 # Give the handler a chance to modify the parser object
4555 $handler->parserTransformHook( $this, $file );
4561 protected function stripAltText( $caption, $holders ) {
4562 # Strip bad stuff out of the title (tooltip). We can't just use
4563 # replaceLinkHoldersText() here, because if this function is called
4564 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4566 $tooltip = $holders->replaceText( $caption );
4568 $tooltip = $this->replaceLinkHoldersText( $caption );
4571 # make sure there are no placeholders in thumbnail attributes
4572 # that are later expanded to html- so expand them now and
4574 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
4575 $tooltip = Sanitizer
::stripAllTags( $tooltip );
4581 * Set a flag in the output object indicating that the content is dynamic and
4582 * shouldn't be cached.
4584 function disableCache() {
4585 wfDebug( "Parser output marked as uncacheable.\n" );
4586 $this->mOutput
->mCacheTime
= -1;
4590 * Callback from the Sanitizer for expanding items found in HTML attribute
4591 * values, so they can be safely tested and escaped.
4592 * @param string $text
4593 * @param PPFrame $frame
4597 function attributeStripCallback( &$text, $frame = false ) {
4598 $text = $this->replaceVariables( $text, $frame );
4599 $text = $this->mStripState
->unstripBoth( $text );
4608 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4609 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4610 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4616 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4621 * Break wikitext input into sections, and either pull or replace
4622 * some particular section's text.
4624 * External callers should use the getSection and replaceSection methods.
4626 * @param string $text Page wikitext
4627 * @param string $section A section identifier string of the form:
4628 * <flag1> - <flag2> - ... - <section number>
4630 * Currently the only recognised flag is "T", which means the target section number
4631 * was derived during a template inclusion parse, in other words this is a template
4632 * section edit link. If no flags are given, it was an ordinary section edit link.
4633 * This flag is required to avoid a section numbering mismatch when a section is
4634 * enclosed by <includeonly> (bug 6563).
4636 * The section number 0 pulls the text before the first heading; other numbers will
4637 * pull the given section along with its lower-level subsections. If the section is
4638 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4640 * @param string $mode One of "get" or "replace"
4641 * @param string $newText Replacement text for section data.
4642 * @return string for "get", the extracted section text.
4643 * for "replace", the whole page with the section replaced.
4645 private function extractSections( $text, $section, $mode, $newText='' ) {
4647 $this->clearState();
4648 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4649 $this->mOptions
= new ParserOptions
;
4650 $this->setOutputType( self
::OT_WIKI
);
4652 $frame = $this->getPreprocessor()->newFrame();
4654 // Process section extraction flags
4656 $sectionParts = explode( '-', $section );
4657 $sectionIndex = array_pop( $sectionParts );
4658 foreach ( $sectionParts as $part ) {
4659 if ( $part === 'T' ) {
4660 $flags |
= self
::PTD_FOR_INCLUSION
;
4663 // Preprocess the text
4664 $root = $this->preprocessToDom( $text, $flags );
4666 // <h> nodes indicate section breaks
4667 // They can only occur at the top level, so we can find them by iterating the root's children
4668 $node = $root->getFirstChild();
4670 // Find the target section
4671 if ( $sectionIndex == 0 ) {
4672 // Section zero doesn't nest, level=big
4673 $targetLevel = 1000;
4676 if ( $node->getName() === 'h' ) {
4677 $bits = $node->splitHeading();
4678 if ( $bits['i'] == $sectionIndex ) {
4679 $targetLevel = $bits['level'];
4683 if ( $mode === 'replace' ) {
4684 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4686 $node = $node->getNextSibling();
4692 if ( $mode === 'get' ) {
4699 // Find the end of the section, including nested sections
4701 if ( $node->getName() === 'h' ) {
4702 $bits = $node->splitHeading();
4703 $curLevel = $bits['level'];
4704 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4708 if ( $mode === 'get' ) {
4709 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4711 $node = $node->getNextSibling();
4714 // Write out the remainder (in replace mode only)
4715 if ( $mode === 'replace' ) {
4716 // Output the replacement text
4717 // Add two newlines on -- trailing whitespace in $newText is conventionally
4718 // stripped by the editor, so we need both newlines to restore the paragraph gap
4719 // Only add trailing whitespace if there is newText
4720 if($newText != "") {
4721 $outText .= $newText . "\n\n";
4725 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4726 $node = $node->getNextSibling();
4730 if ( is_string( $outText ) ) {
4731 // Re-insert stripped tags
4732 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4739 * This function returns the text of a section, specified by a number ($section).
4740 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4741 * the first section before any such heading (section 0).
4743 * If a section contains subsections, these are also returned.
4745 * @param string $text text to look in
4746 * @param string $section section identifier
4747 * @param string $deftext default to return if section is not found
4748 * @return string text of the requested section
4750 public function getSection( $text, $section, $deftext='' ) {
4751 return $this->extractSections( $text, $section, "get", $deftext );
4754 public function replaceSection( $oldtext, $section, $text ) {
4755 return $this->extractSections( $oldtext, $section, "replace", $text );
4759 * Get the timestamp associated with the current revision, adjusted for
4760 * the default server-local timestamp
4762 function getRevisionTimestamp() {
4763 if ( is_null( $this->mRevisionTimestamp
) ) {
4764 wfProfileIn( __METHOD__
);
4766 $dbr = wfGetDB( DB_SLAVE
);
4767 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4768 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4770 // Normalize timestamp to internal MW format for timezone processing.
4771 // This has the added side-effect of replacing a null value with
4772 // the current time, which gives us more sensible behavior for
4774 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4776 // The cryptic '' timezone parameter tells to use the site-default
4777 // timezone offset instead of the user settings.
4779 // Since this value will be saved into the parser cache, served
4780 // to other users, and potentially even used inside links and such,
4781 // it needs to be consistent for all visitors.
4782 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4784 wfProfileOut( __METHOD__
);
4786 return $this->mRevisionTimestamp
;
4790 * Get the name of the user that edited the last revision
4792 function getRevisionUser() {
4793 // if this template is subst: the revision id will be blank,
4794 // so just use the current user's name
4795 if( $this->mRevisionId
) {
4796 $revision = Revision
::newFromId( $this->mRevisionId
);
4797 $revuser = $revision->getUserText();
4800 $revuser = $wgUser->getName();
4806 * Mutator for $mDefaultSort
4808 * @param $sort New value
4810 public function setDefaultSort( $sort ) {
4811 $this->mDefaultSort
= $sort;
4815 * Accessor for $mDefaultSort
4816 * Will use the title/prefixed title if none is set
4820 public function getDefaultSort() {
4821 global $wgCategoryPrefixedDefaultSortkey;
4822 if( $this->mDefaultSort
!== false ) {
4823 return $this->mDefaultSort
;
4824 } elseif ($this->mTitle
->getNamespace() == NS_CATEGORY ||
4825 !$wgCategoryPrefixedDefaultSortkey) {
4826 return $this->mTitle
->getText();
4828 return $this->mTitle
->getPrefixedText();
4833 * Accessor for $mDefaultSort
4834 * Unlike getDefaultSort(), will return false if none is set
4836 * @return string or false
4838 public function getCustomDefaultSort() {
4839 return $this->mDefaultSort
;
4843 * Try to guess the section anchor name based on a wikitext fragment
4844 * presumably extracted from a heading, for example "Header" from
4847 public function guessSectionNameFromWikiText( $text ) {
4848 # Strip out wikitext links(they break the anchor)
4849 $text = $this->stripSectionName( $text );
4850 $headline = Sanitizer
::decodeCharReferences( $text );
4852 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
4853 $headline = trim( $headline );
4854 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4855 $replacearray = array(
4860 array_keys( $replacearray ),
4861 array_values( $replacearray ),
4866 * Strips a text string of wikitext for use in a section anchor
4868 * Accepts a text string and then removes all wikitext from the
4869 * string and leaves only the resultant text (i.e. the result of
4870 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4871 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4872 * to create valid section anchors by mimicing the output of the
4873 * parser when headings are parsed.
4875 * @param $text string Text string to be stripped of wikitext
4876 * for use in a Section anchor
4877 * @return Filtered text string
4879 public function stripSectionName( $text ) {
4880 # Strip internal link markup
4881 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4882 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4884 # Strip external link markup (FIXME: Not Tolerant to blank link text
4885 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4886 # on how many empty links there are on the page - need to figure that out.
4887 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4889 # Parse wikitext quotes (italics & bold)
4890 $text = $this->doQuotes($text);
4893 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
4897 function srvus( $text ) {
4898 return $this->testSrvus( $text, $this->mOutputType
);
4902 * strip/replaceVariables/unstrip for preprocessor regression testing
4904 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
4905 $this->clearState();
4906 if ( ! ( $title instanceof Title
) ) {
4907 $title = Title
::newFromText( $title );
4909 $this->mTitle
= $title;
4910 $this->mOptions
= $options;
4911 $this->setOutputType( $outputType );
4912 $text = $this->replaceVariables( $text );
4913 $text = $this->mStripState
->unstripBoth( $text );
4914 $text = Sanitizer
::removeHTMLtags( $text );
4918 function testPst( $text, $title, $options ) {
4920 if ( ! ( $title instanceof Title
) ) {
4921 $title = Title
::newFromText( $title );
4923 return $this->preSaveTransform( $text, $title, $wgUser, $options );
4926 function testPreprocess( $text, $title, $options ) {
4927 if ( ! ( $title instanceof Title
) ) {
4928 $title = Title
::newFromText( $title );
4930 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
4933 function markerSkipCallback( $s, $callback ) {
4936 while ( $i < strlen( $s ) ) {
4937 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
4938 if ( $markerStart === false ) {
4939 $out .= call_user_func( $callback, substr( $s, $i ) );
4942 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
4943 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
4944 if ( $markerEnd === false ) {
4945 $out .= substr( $s, $markerStart );
4948 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
4949 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
4957 function serialiseHalfParsedText( $text ) {
4959 $data['text'] = $text;
4961 // First, find all strip markers, and store their
4962 // data in an array.
4963 $stripState = new StripState
;
4965 while( ( $start_pos = strpos( $text, $this->mUniqPrefix
, $pos ) ) && ( $end_pos = strpos( $text, self
::MARKER_SUFFIX
, $pos ) ) ) {
4966 $end_pos +
= strlen( self
::MARKER_SUFFIX
);
4967 $marker = substr( $text, $start_pos, $end_pos-$start_pos );
4969 if ( !empty( $this->mStripState
->general
->data
[$marker] ) ) {
4970 $replaceArray = $stripState->general
;
4971 $stripText = $this->mStripState
->general
->data
[$marker];
4972 } elseif ( !empty( $this->mStripState
->nowiki
->data
[$marker] ) ) {
4973 $replaceArray = $stripState->nowiki
;
4974 $stripText = $this->mStripState
->nowiki
->data
[$marker];
4976 throw new MWException( "Hanging strip marker: '$marker'." );
4979 $replaceArray->setPair( $marker, $stripText );
4982 $data['stripstate'] = $stripState;
4984 // Now, find all of our links, and store THEIR
4985 // data in an array! :)
4986 $links = array( 'internal' => array(), 'interwiki' => array() );
4990 while( ( $start_pos = strpos( $text, '<!--LINK ', $pos ) ) ) {
4991 list( $ns, $trail ) = explode( ':', substr( $text, $start_pos +
strlen( '<!--LINK ' ) ), 2 );
4994 if (empty( $links['internal'][$ns] )) {
4995 $links['internal'][$ns] = array();
4998 $key = trim( substr( $trail, 0, strpos( $trail, '-->' ) ) );
4999 $links['internal'][$ns][] = $this->mLinkHolders
->internals
[$ns][$key];
5000 $pos = $start_pos +
strlen( "<!--LINK $ns:$key-->" );
5006 while( ( $start_pos = strpos( $text, '<!--IWLINK ', $pos ) ) ) {
5007 $data = substr( $text, $start_pos );
5008 $key = trim( substr( $data, 0, strpos( $data, '-->' ) ) );
5009 $links['interwiki'][] = $this->mLinkHolders
->interwiki
[$key];
5010 $pos = $start_pos +
strlen( "<!--IWLINK $key-->" );
5013 $data['linkholder'] = $links;
5018 function unserialiseHalfParsedText( $data, $intPrefix = null /* Unique identifying prefix */ ) {
5020 $intPrefix = $this->getRandomString();
5022 // First, extract the strip state.
5023 $stripState = $data['stripstate'];
5024 $this->mStripState
->general
->merge( $stripState->general
);
5025 $this->mStripState
->nowiki
->merge( $stripState->nowiki
);
5027 // Now, extract the text, and renumber links
5028 $text = $data['text'];
5029 $links = $data['linkholder'];
5032 foreach( $links['internal'] as $ns => $nsLinks ) {
5033 foreach( $nsLinks as $key => $entry ) {
5034 $newKey = $intPrefix . '-' . $key;
5035 $this->mLinkHolders
->internals
[$ns][$newKey] = $entry;
5037 $text = str_replace( "<!--LINK $ns:$key-->", "<!--LINK $ns:$newKey-->", $text );
5042 foreach( $links['interwiki'] as $key => $entry ) {
5043 $newKey = "$intPrefix-$key";
5044 $this->mLinkHolders
->interwikis
[$newKey] = $entry;
5046 $text = str_replace( "<!--IWLINK $key-->", "<!--IWLINK $newKey-->", $text );
5049 // Should be good to go.
5055 * @todo document, briefly.
5059 var $general, $nowiki;
5061 function __construct() {
5062 $this->general
= new ReplacementArray
;
5063 $this->nowiki
= new ReplacementArray
;
5066 function unstripGeneral( $text ) {
5067 wfProfileIn( __METHOD__
);
5070 $text = $this->general
->replace( $text );
5071 } while ( $text !== $oldText );
5072 wfProfileOut( __METHOD__
);
5076 function unstripNoWiki( $text ) {
5077 wfProfileIn( __METHOD__
);
5080 $text = $this->nowiki
->replace( $text );
5081 } while ( $text !== $oldText );
5082 wfProfileOut( __METHOD__
);
5086 function unstripBoth( $text ) {
5087 wfProfileIn( __METHOD__
);
5090 $text = $this->general
->replace( $text );
5091 $text = $this->nowiki
->replace( $text );
5092 } while ( $text !== $oldText );
5093 wfProfileOut( __METHOD__
);
5099 * @todo document, briefly.
5102 class OnlyIncludeReplacer
{
5105 function replace( $matches ) {
5106 if ( substr( $matches[1], -1 ) === "\n" ) {
5107 $this->output
.= substr( $matches[1], 0, -1 );
5109 $this->output
.= $matches[1];