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) {
1845 # :Foobar -- override special treatment of prefix (images, language links)
1846 # /Foobar -- convert to CurrentPage/Foobar
1847 # /Foobar/ -- convert to CurrentPage/Foobar, strip the initial / from text
1848 # ../ -- convert to CurrentPage, from CurrentPage/CurrentSubPage
1849 # ../Foobar -- convert to CurrentPage/Foobar, from CurrentPage/CurrentSubPage
1851 wfProfileIn( __METHOD__
);
1852 $ret = $target; # default return value is no change
1854 # Some namespaces don't allow subpages,
1855 # so only perform processing if subpages are allowed
1856 if( $this->areSubpagesAllowed() ) {
1857 $hash = strpos( $target, '#' );
1858 if( $hash !== false ) {
1859 $suffix = substr( $target, $hash );
1860 $target = substr( $target, 0, $hash );
1865 $target = trim( $target );
1866 # Look at the first character
1867 if( $target != '' && $target{0} === '/' ) {
1868 # / at end means we don't want the slash to be shown
1870 $trailingSlashes = preg_match_all( '%(/+)$%', $target, $m );
1871 if( $trailingSlashes ) {
1872 $noslash = $target = substr( $target, 1, -strlen($m[0][0]) );
1874 $noslash = substr( $target, 1 );
1877 $ret = $this->mTitle
->getPrefixedText(). '/' . trim($noslash) . $suffix;
1878 if( '' === $text ) {
1879 $text = $target . $suffix;
1880 } # this might be changed for ugliness reasons
1882 # check for .. subpage backlinks
1884 $nodotdot = $target;
1885 while( strncmp( $nodotdot, "../", 3 ) == 0 ) {
1887 $nodotdot = substr( $nodotdot, 3 );
1889 if($dotdotcount > 0) {
1890 $exploded = explode( '/', $this->mTitle
->GetPrefixedText() );
1891 if( count( $exploded ) > $dotdotcount ) { # not allowed to go below top level page
1892 $ret = implode( '/', array_slice( $exploded, 0, -$dotdotcount ) );
1893 # / at the end means don't show full path
1894 if( substr( $nodotdot, -1, 1 ) === '/' ) {
1895 $nodotdot = substr( $nodotdot, 0, -1 );
1896 if( '' === $text ) {
1897 $text = $nodotdot . $suffix;
1900 $nodotdot = trim( $nodotdot );
1901 if( $nodotdot != '' ) {
1902 $ret .= '/' . $nodotdot;
1910 wfProfileOut( __METHOD__
);
1915 * Used by doBlockLevels()
1918 /* private */ function closeParagraph() {
1920 if ( '' != $this->mLastSection
) {
1921 $result = '</' . $this->mLastSection
. ">\n";
1923 $this->mInPre
= false;
1924 $this->mLastSection
= '';
1927 # getCommon() returns the length of the longest common substring
1928 # of both arguments, starting at the beginning of both.
1930 /* private */ function getCommon( $st1, $st2 ) {
1931 $fl = strlen( $st1 );
1932 $shorter = strlen( $st2 );
1933 if ( $fl < $shorter ) { $shorter = $fl; }
1935 for ( $i = 0; $i < $shorter; ++
$i ) {
1936 if ( $st1{$i} != $st2{$i} ) { break; }
1940 # These next three functions open, continue, and close the list
1941 # element appropriate to the prefix character passed into them.
1943 /* private */ function openList( $char ) {
1944 $result = $this->closeParagraph();
1946 if ( '*' === $char ) { $result .= '<ul><li>'; }
1947 elseif ( '#' === $char ) { $result .= '<ol><li>'; }
1948 elseif ( ':' === $char ) { $result .= '<dl><dd>'; }
1949 elseif ( ';' === $char ) {
1950 $result .= '<dl><dt>';
1951 $this->mDTopen
= true;
1952 } elseif ( '>' === $char ) { $result .= "<blockquote><p>"; }
1953 else { $result = '<!-- ERR 1 -->'; }
1958 /* private */ function nextItem( $char ) {
1959 if ( '*' === $char ||
'#' === $char ) { return '</li><li>'; }
1960 elseif ( '>' === $char ) { return "</p><p>"; }
1961 elseif ( ':' === $char ||
';' === $char ) {
1963 if ( $this->mDTopen
) { $close = '</dt>'; }
1964 if ( ';' === $char ) {
1965 $this->mDTopen
= true;
1966 return $close . '<dt>';
1968 $this->mDTopen
= false;
1969 return $close . '<dd>';
1972 return '<!-- ERR 2 -->';
1975 /* private */ function closeList( $char ) {
1976 if ( '*' === $char ) { $text = '</li></ul>'; }
1977 elseif ( '#' === $char ) { $text = '</li></ol>'; }
1978 elseif ( '>' === $char ) { $text = "</p></blockquote>"; }
1979 elseif ( ':' === $char ) {
1980 if ( $this->mDTopen
) {
1981 $this->mDTopen
= false;
1982 $text = '</dt></dl>';
1984 $text = '</dd></dl>';
1987 else { return '<!-- ERR 3 -->'; }
1993 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
1995 * @param $linestart bool whether or not this is at the start of a line.
1997 * @return string the lists rendered as HTML
1999 function doBlockLevels( $text, $linestart ) {
2000 wfProfileIn( __METHOD__
);
2002 # Parsing through the text line by line. The main thing
2003 # happening here is handling of block-level elements p, pre,
2004 # and making lists from lines starting with * # : etc.
2006 $textLines = StringUtils
::explode( "\n", $text );
2008 $lastPrefix = $output = '';
2009 $this->mDTopen
= $inBlockElem = false;
2011 $paragraphStack = false;
2013 foreach ( $textLines as $oLine ) {
2015 if ( !$linestart ) {
2026 $lastPrefixLength = strlen( $lastPrefix );
2027 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2028 $preOpenMatch = preg_match('/<pre/i', $oLine );
2030 // Need to decode > --> > for blockquote syntax. Re-encode later.
2031 // To avoid collision with real >s, we temporarily convert them to >
2032 // This is a weird choice of armouring, but it's totally resistant to any
2035 $oLine = strtr( $oLine, array( '>' => '>', '>' => '>' ) );
2037 // If not in a <pre> element, scan for and figure out what prefixes are there.
2038 if ( !$this->mInPre
) {
2039 # Multiple prefixes may abut each other for nested lists.
2040 $prefixLength = strspn( $oLine, '*#:;>' );
2041 $prefix = substr( $oLine, 0, $prefixLength );
2044 // ; and : are both from definition-lists, so they're equivalent
2045 // for the purposes of determining whether or not we need to open/close
2047 $prefix2 = str_replace( ';', ':', $prefix );
2048 $t = substr( $oLine, $prefixLength );
2049 $this->mInPre
= (bool)$preOpenMatch;
2051 # Don't interpret any other prefixes in preformatted text
2053 $prefix = $prefix2 = '';
2058 $t = strtr( $t, array( '>' => '>', '>' => '>' ) );
2061 if( $prefixLength && $lastPrefix === $prefix2 ) {
2062 # Same as the last item, so no need to deal with nesting or opening stuff
2063 $output .= $this->nextItem( substr( $prefix, -1 ) );
2064 $paragraphStack = false;
2066 if ( substr( $prefix, -1 ) === ';') {
2067 # The one nasty exception: definition lists work like this:
2068 # ; title : definition text
2069 # So we check for : in the remainder text to split up the
2070 # title and definition, without b0rking links.
2072 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2074 $output .= $term . $this->nextItem( ':' );
2077 } elseif( $prefixLength ||
$lastPrefixLength ) {
2078 // We need to open or close prefixes, or both.
2080 # Either open or close a level...
2081 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2082 $paragraphStack = false;
2084 // Close all the prefixes which aren't shared.
2085 while( $commonPrefixLength < $lastPrefixLength ) {
2086 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2087 --$lastPrefixLength;
2090 // Continue the current prefix if appropriate.
2091 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2092 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2095 // Open prefixes where appropriate.
2096 while ( $prefixLength > $commonPrefixLength ) {
2097 $char = substr( $prefix, $commonPrefixLength, 1 );
2098 $output .= $this->openList( $char );
2100 if ( ';' === $char ) {
2101 # FIXME: This is dupe of code above
2102 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2104 $output .= $term . $this->nextItem( ':' );
2107 ++
$commonPrefixLength;
2109 $lastPrefix = $prefix2;
2112 // If we have no prefixes, go to paragraph mode.
2113 if( 0 == $prefixLength ) {
2114 wfProfileIn( __METHOD__
."-paragraph" );
2115 # No prefix (not in list)--go to paragraph mode
2116 // XXX: use a stack for nestable elements like span, table and div
2117 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2118 $closematch = preg_match(
2119 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2120 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2121 if ( $openmatch or $closematch ) {
2122 $paragraphStack = false;
2123 #Â TODO bug 5718: paragraph closed
2124 $output .= $this->closeParagraph();
2125 if ( $preOpenMatch and !$preCloseMatch ) {
2126 $this->mInPre
= true;
2128 if ( $closematch ) {
2129 $inBlockElem = false;
2131 $inBlockElem = true;
2133 } else if ( !$inBlockElem && !$this->mInPre
) {
2134 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' or trim($t) != '' ) ) {
2136 if ($this->mLastSection
!== 'pre') {
2137 $paragraphStack = false;
2138 $output .= $this->closeParagraph().'<pre>';
2139 $this->mLastSection
= 'pre';
2141 $t = substr( $t, 1 );
2144 if ( '' == trim($t) ) {
2145 if ( $paragraphStack ) {
2146 $output .= $paragraphStack.'<br />';
2147 $paragraphStack = false;
2148 $this->mLastSection
= 'p';
2150 if ($this->mLastSection
!== 'p' ) {
2151 $output .= $this->closeParagraph();
2152 $this->mLastSection
= '';
2153 $paragraphStack = '<p>';
2155 $paragraphStack = '</p><p>';
2159 if ( $paragraphStack ) {
2160 $output .= $paragraphStack;
2161 $paragraphStack = false;
2162 $this->mLastSection
= 'p';
2163 } else if ($this->mLastSection
!== 'p') {
2164 $output .= $this->closeParagraph().'<p>';
2165 $this->mLastSection
= 'p';
2170 wfProfileOut( __METHOD__
."-paragraph" );
2172 // somewhere above we forget to get out of pre block (bug 785)
2173 if($preCloseMatch && $this->mInPre
) {
2174 $this->mInPre
= false;
2176 if ($paragraphStack === false) {
2180 while ( $prefixLength ) {
2181 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2184 if ( '' != $this->mLastSection
) {
2185 $output .= '</' . $this->mLastSection
. '>';
2186 $this->mLastSection
= '';
2189 wfProfileOut( __METHOD__
);
2194 * Split up a string on ':', ignoring any occurences inside tags
2195 * to prevent illegal overlapping.
2196 * @param string $str the string to split
2197 * @param string &$before set to everything before the ':'
2198 * @param string &$after set to everything after the ':'
2199 * return string the position of the ':', or false if none found
2201 function findColonNoLinks($str, &$before, &$after) {
2202 wfProfileIn( __METHOD__
);
2204 $pos = strpos( $str, ':' );
2205 if( $pos === false ) {
2207 wfProfileOut( __METHOD__
);
2211 $lt = strpos( $str, '<' );
2212 if( $lt === false ||
$lt > $pos ) {
2213 // Easy; no tag nesting to worry about
2214 $before = substr( $str, 0, $pos );
2215 $after = substr( $str, $pos+
1 );
2216 wfProfileOut( __METHOD__
);
2220 // Ugly state machine to walk through avoiding tags.
2221 $state = self
::COLON_STATE_TEXT
;
2223 $len = strlen( $str );
2224 for( $i = 0; $i < $len; $i++
) {
2228 // (Using the number is a performance hack for common cases)
2229 case 0: // self::COLON_STATE_TEXT:
2232 // Could be either a <start> tag or an </end> tag
2233 $state = self
::COLON_STATE_TAGSTART
;
2238 $before = substr( $str, 0, $i );
2239 $after = substr( $str, $i +
1 );
2240 wfProfileOut( __METHOD__
);
2243 // Embedded in a tag; don't break it.
2246 // Skip ahead looking for something interesting
2247 $colon = strpos( $str, ':', $i );
2248 if( $colon === false ) {
2249 // Nothing else interesting
2250 wfProfileOut( __METHOD__
);
2253 $lt = strpos( $str, '<', $i );
2254 if( $stack === 0 ) {
2255 if( $lt === false ||
$colon < $lt ) {
2257 $before = substr( $str, 0, $colon );
2258 $after = substr( $str, $colon +
1 );
2259 wfProfileOut( __METHOD__
);
2263 if( $lt === false ) {
2264 // Nothing else interesting to find; abort!
2265 // We're nested, but there's no close tags left. Abort!
2268 // Skip ahead to next tag start
2270 $state = self
::COLON_STATE_TAGSTART
;
2273 case 1: // self::COLON_STATE_TAG:
2278 $state = self
::COLON_STATE_TEXT
;
2281 // Slash may be followed by >?
2282 $state = self
::COLON_STATE_TAGSLASH
;
2288 case 2: // self::COLON_STATE_TAGSTART:
2291 $state = self
::COLON_STATE_CLOSETAG
;
2294 $state = self
::COLON_STATE_COMMENT
;
2297 // Illegal early close? This shouldn't happen D:
2298 $state = self
::COLON_STATE_TEXT
;
2301 $state = self
::COLON_STATE_TAG
;
2304 case 3: // self::COLON_STATE_CLOSETAG:
2309 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2310 wfProfileOut( __METHOD__
);
2313 $state = self
::COLON_STATE_TEXT
;
2316 case self
::COLON_STATE_TAGSLASH
:
2318 // Yes, a self-closed tag <blah/>
2319 $state = self
::COLON_STATE_TEXT
;
2321 // Probably we're jumping the gun, and this is an attribute
2322 $state = self
::COLON_STATE_TAG
;
2325 case 5: // self::COLON_STATE_COMMENT:
2327 $state = self
::COLON_STATE_COMMENTDASH
;
2330 case self
::COLON_STATE_COMMENTDASH
:
2332 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2334 $state = self
::COLON_STATE_COMMENT
;
2337 case self
::COLON_STATE_COMMENTDASHDASH
:
2339 $state = self
::COLON_STATE_TEXT
;
2341 $state = self
::COLON_STATE_COMMENT
;
2345 throw new MWException( "State machine error in " . __METHOD__
);
2349 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2352 wfProfileOut( __METHOD__
);
2357 * Return value of a magic variable (like PAGENAME)
2361 function getVariableValue( $index ) {
2362 global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
2365 * Some of these require message or data lookups and can be
2366 * expensive to check many times.
2368 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2369 if ( isset( $this->mVarCache
[$index] ) ) {
2370 return $this->mVarCache
[$index];
2374 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2375 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2378 global $wgLocaltimezone;
2379 if ( isset( $wgLocaltimezone ) ) {
2380 $oldtz = getenv( 'TZ' );
2381 putenv( 'TZ='.$wgLocaltimezone );
2384 wfSuppressWarnings(); // E_STRICT system time bitching
2385 $localTimestamp = date( 'YmdHis', $ts );
2386 $localMonth = date( 'm', $ts );
2387 $localMonth1 = date( 'n', $ts );
2388 $localMonthName = date( 'n', $ts );
2389 $localDay = date( 'j', $ts );
2390 $localDay2 = date( 'd', $ts );
2391 $localDayOfWeek = date( 'w', $ts );
2392 $localWeek = date( 'W', $ts );
2393 $localYear = date( 'Y', $ts );
2394 $localHour = date( 'H', $ts );
2395 if ( isset( $wgLocaltimezone ) ) {
2396 putenv( 'TZ='.$oldtz );
2398 wfRestoreWarnings();
2401 case 'currentmonth':
2402 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2403 case 'currentmonth1':
2404 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2405 case 'currentmonthname':
2406 return $this->mVarCache
[$index] = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2407 case 'currentmonthnamegen':
2408 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2409 case 'currentmonthabbrev':
2410 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2412 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2414 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2416 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localMonth );
2418 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localMonth1 );
2419 case 'localmonthname':
2420 return $this->mVarCache
[$index] = $wgContLang->getMonthName( $localMonthName );
2421 case 'localmonthnamegen':
2422 return $this->mVarCache
[$index] = $wgContLang->getMonthNameGen( $localMonthName );
2423 case 'localmonthabbrev':
2424 return $this->mVarCache
[$index] = $wgContLang->getMonthAbbreviation( $localMonthName );
2426 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay );
2428 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDay2 );
2430 return wfEscapeWikiText( $this->mTitle
->getText() );
2432 return $this->mTitle
->getPartialURL();
2433 case 'fullpagename':
2434 return wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2435 case 'fullpagenamee':
2436 return $this->mTitle
->getPrefixedURL();
2438 return wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2439 case 'subpagenamee':
2440 return $this->mTitle
->getSubpageUrlForm();
2441 case 'basepagename':
2442 return wfEscapeWikiText( $this->mTitle
->getBaseText() );
2443 case 'basepagenamee':
2444 return wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2445 case 'talkpagename':
2446 if( $this->mTitle
->canTalk() ) {
2447 $talkPage = $this->mTitle
->getTalkPage();
2448 return wfEscapeWikiText( $talkPage->getPrefixedText() );
2452 case 'talkpagenamee':
2453 if( $this->mTitle
->canTalk() ) {
2454 $talkPage = $this->mTitle
->getTalkPage();
2455 return $talkPage->getPrefixedUrl();
2459 case 'subjectpagename':
2460 $subjPage = $this->mTitle
->getSubjectPage();
2461 return wfEscapeWikiText( $subjPage->getPrefixedText() );
2462 case 'subjectpagenamee':
2463 $subjPage = $this->mTitle
->getSubjectPage();
2464 return $subjPage->getPrefixedUrl();
2466 // Let the edit saving system know we should parse the page
2467 // *after* a revision ID has been assigned.
2468 $this->mOutput
->setFlag( 'vary-revision' );
2469 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2470 return $this->mRevisionId
;
2472 // Let the edit saving system know we should parse the page
2473 // *after* a revision ID has been assigned. This is for null edits.
2474 $this->mOutput
->setFlag( 'vary-revision' );
2475 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2476 return intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2477 case 'revisionday2':
2478 // Let the edit saving system know we should parse the page
2479 // *after* a revision ID has been assigned. This is for null edits.
2480 $this->mOutput
->setFlag( 'vary-revision' );
2481 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2482 return substr( $this->getRevisionTimestamp(), 6, 2 );
2483 case 'revisionmonth':
2484 // Let the edit saving system know we should parse the page
2485 // *after* a revision ID has been assigned. This is for null edits.
2486 $this->mOutput
->setFlag( 'vary-revision' );
2487 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2488 return intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2489 case 'revisionyear':
2490 // Let the edit saving system know we should parse the page
2491 // *after* a revision ID has been assigned. This is for null edits.
2492 $this->mOutput
->setFlag( 'vary-revision' );
2493 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2494 return substr( $this->getRevisionTimestamp(), 0, 4 );
2495 case 'revisiontimestamp':
2496 // Let the edit saving system know we should parse the page
2497 // *after* a revision ID has been assigned. This is for null edits.
2498 $this->mOutput
->setFlag( 'vary-revision' );
2499 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2500 return $this->getRevisionTimestamp();
2501 case 'revisionuser':
2502 // Let the edit saving system know we should parse the page
2503 // *after* a revision ID has been assigned. This is for null edits.
2504 $this->mOutput
->setFlag( 'vary-revision' );
2505 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2506 return $this->getRevisionUser();
2508 return str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2510 return wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2512 return $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2514 return $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2515 case 'subjectspace':
2516 return $this->mTitle
->getSubjectNsText();
2517 case 'subjectspacee':
2518 return( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2519 case 'currentdayname':
2520 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2522 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2524 return $this->mVarCache
[$index] = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2526 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2528 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2529 // int to remove the padding
2530 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2532 return $this->mVarCache
[$index] = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2533 case 'localdayname':
2534 return $this->mVarCache
[$index] = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2536 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localYear, true );
2538 return $this->mVarCache
[$index] = $wgContLang->time( $localTimestamp, false, false );
2540 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localHour, true );
2542 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2543 // int to remove the padding
2544 return $this->mVarCache
[$index] = $wgContLang->formatNum( (int)$localWeek );
2546 return $this->mVarCache
[$index] = $wgContLang->formatNum( $localDayOfWeek );
2547 case 'numberofarticles':
2548 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::articles() );
2549 case 'numberoffiles':
2550 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::images() );
2551 case 'numberofusers':
2552 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::users() );
2553 case 'numberofactiveusers':
2554 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::activeUsers() );
2555 case 'numberofpages':
2556 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::pages() );
2557 case 'numberofadmins':
2558 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::numberingroup('sysop') );
2559 case 'numberofedits':
2560 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::edits() );
2561 case 'numberofviews':
2562 return $this->mVarCache
[$index] = $wgContLang->formatNum( SiteStats
::views() );
2563 case 'currenttimestamp':
2564 return $this->mVarCache
[$index] = wfTimestamp( TS_MW
, $ts );
2565 case 'localtimestamp':
2566 return $this->mVarCache
[$index] = $localTimestamp;
2567 case 'currentversion':
2568 return $this->mVarCache
[$index] = SpecialVersion
::getVersion();
2574 return $wgServerName;
2576 return $wgScriptPath;
2577 case 'directionmark':
2578 return $wgContLang->getDirMark();
2579 case 'contentlanguage':
2580 global $wgContLanguageCode;
2581 return $wgContLanguageCode;
2584 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret ) ) )
2592 * initialise the magic variables (like CURRENTMONTHNAME)
2596 function initialiseVariables() {
2597 wfProfileIn( __METHOD__
);
2598 $variableIDs = MagicWord
::getVariableIDs();
2600 $this->mVariables
= new MagicWordArray( $variableIDs );
2601 wfProfileOut( __METHOD__
);
2605 * Preprocess some wikitext and return the document tree.
2606 * This is the ghost of replace_variables().
2608 * @param string $text The text to parse
2609 * @param integer flags Bitwise combination of:
2610 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2611 * included. Default is to assume a direct page view.
2613 * The generated DOM tree must depend only on the input text and the flags.
2614 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2616 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2617 * change in the DOM tree for a given text, must be passed through the section identifier
2618 * in the section edit link and thus back to extractSections().
2620 * The output of this function is currently only cached in process memory, but a persistent
2621 * cache may be implemented at a later date which takes further advantage of these strict
2622 * dependency requirements.
2626 function preprocessToDom ( $text, $flags = 0 ) {
2627 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2632 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2634 public static function splitWhitespace( $s ) {
2635 $ltrimmed = ltrim( $s );
2636 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2637 $trimmed = rtrim( $ltrimmed );
2638 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2640 $w2 = substr( $ltrimmed, -$diff );
2644 return array( $w1, $trimmed, $w2 );
2648 * Replace magic variables, templates, and template arguments
2649 * with the appropriate text. Templates are substituted recursively,
2650 * taking care to avoid infinite loops.
2652 * Note that the substitution depends on value of $mOutputType:
2653 * self::OT_WIKI: only {{subst:}} templates
2654 * self::OT_PREPROCESS: templates but not extension tags
2655 * self::OT_HTML: all templates and extension tags
2657 * @param string $tex The text to transform
2658 * @param PPFrame $frame Object describing the arguments passed to the template.
2659 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2660 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2661 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2664 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2665 # Is there any text? Also, Prevent too big inclusions!
2666 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2669 wfProfileIn( __METHOD__
);
2671 if ( $frame === false ) {
2672 $frame = $this->getPreprocessor()->newFrame();
2673 } elseif ( !( $frame instanceof PPFrame
) ) {
2674 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2675 $frame = $this->getPreprocessor()->newCustomFrame($frame);
2678 $dom = $this->preprocessToDom( $text );
2679 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2680 $text = $frame->expand( $dom, $flags );
2682 wfProfileOut( __METHOD__
);
2686 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2687 static function createAssocArgs( $args ) {
2688 $assocArgs = array();
2690 foreach( $args as $arg ) {
2691 $eqpos = strpos( $arg, '=' );
2692 if ( $eqpos === false ) {
2693 $assocArgs[$index++
] = $arg;
2695 $name = trim( substr( $arg, 0, $eqpos ) );
2696 $value = trim( substr( $arg, $eqpos+
1 ) );
2697 if ( $value === false ) {
2700 if ( $name !== false ) {
2701 $assocArgs[$name] = $value;
2710 * Warn the user when a parser limitation is reached
2711 * Will warn at most once the user per limitation type
2713 * @param string $limitationType, should be one of:
2714 * 'expensive-parserfunction' (corresponding messages: 'expensive-parserfunction-warning', 'expensive-parserfunction-category')
2715 * 'post-expand-template-argument' (corresponding messages: 'post-expand-template-argument-warning', 'post-expand-template-argument-category')
2716 * 'post-expand-template-inclusion' (corresponding messages: 'post-expand-template-inclusion-warning', 'post-expand-template-inclusion-category')
2717 * @params int $current, $max When an explicit limit has been
2718 * exceeded, provide the values (optional)
2720 function limitationWarn( $limitationType, $current=null, $max=null) {
2721 $msgName = $limitationType . '-warning';
2722 //does no harm if $current and $max are present but are unnecessary for the message
2723 $warning = wfMsgExt( $msgName, array( 'parsemag', 'escape' ), $current, $max );
2724 $this->mOutput
->addWarning( $warning );
2725 $cat = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( $limitationType . '-category' ) );
2727 $this->mOutput
->addCategory( $cat->getDBkey(), $this->getDefaultSort() );
2732 * Return the text of a template, after recursively
2733 * replacing any variables or templates within the template.
2735 * @param array $piece The parts of the template
2736 * $piece['title']: the title, i.e. the part before the |
2737 * $piece['parts']: the parameter array
2738 * $piece['lineStart']: whether the brace was at the start of a line
2739 * @param PPFrame The current frame, contains template arguments
2740 * @return string the text of the template
2743 function braceSubstitution( $piece, $frame ) {
2744 global $wgContLang, $wgNonincludableNamespaces;
2745 wfProfileIn( __METHOD__
);
2746 wfProfileIn( __METHOD__
.'-setup' );
2749 $found = false; # $text has been filled
2750 $nowiki = false; # wiki markup in $text should be escaped
2751 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2752 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2753 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2754 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2756 # Title object, where $text came from
2759 # $part1 is the bit before the first |, and must contain only title characters.
2760 # Various prefixes will be stripped from it later.
2761 $titleWithSpaces = $frame->expand( $piece['title'] );
2762 $part1 = trim( $titleWithSpaces );
2765 # Original title text preserved for various purposes
2766 $originalTitle = $part1;
2768 # $args is a list of argument nodes, starting from index 0, not including $part1
2769 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2770 wfProfileOut( __METHOD__
.'-setup' );
2773 wfProfileIn( __METHOD__
.'-modifiers' );
2775 $mwSubst = MagicWord
::get( 'subst' );
2776 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2777 # One of two possibilities is true:
2778 # 1) Found SUBST but not in the PST phase
2779 # 2) Didn't find SUBST and in the PST phase
2780 # In either case, return without further processing
2781 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2788 if ( !$found && $args->getLength() == 0 ) {
2789 $id = $this->mVariables
->matchStartToEnd( $part1 );
2790 if ( $id !== false ) {
2791 $text = $this->getVariableValue( $id );
2792 if (MagicWord
::getCacheTTL($id)>-1)
2793 $this->mOutput
->mContainsOldMagic
= true;
2798 # MSG, MSGNW and RAW
2801 $mwMsgnw = MagicWord
::get( 'msgnw' );
2802 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2805 # Remove obsolete MSG:
2806 $mwMsg = MagicWord
::get( 'msg' );
2807 $mwMsg->matchStartAndRemove( $part1 );
2811 $mwRaw = MagicWord
::get( 'raw' );
2812 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2813 $forceRawInterwiki = true;
2816 wfProfileOut( __METHOD__
.'-modifiers' );
2820 wfProfileIn( __METHOD__
. '-pfunc' );
2822 $colonPos = strpos( $part1, ':' );
2823 if ( $colonPos !== false ) {
2824 # Case sensitive functions
2825 $function = substr( $part1, 0, $colonPos );
2826 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2827 $function = $this->mFunctionSynonyms
[1][$function];
2829 # Case insensitive functions
2830 $function = strtolower( $function );
2831 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2832 $function = $this->mFunctionSynonyms
[0][$function];
2838 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2839 $initialArgs = array( &$this );
2840 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2841 if ( $flags & SFH_OBJECT_ARGS
) {
2842 # Add a frame parameter, and pass the arguments as an array
2843 $allArgs = $initialArgs;
2844 $allArgs[] = $frame;
2845 for ( $i = 0; $i < $args->getLength(); $i++
) {
2846 $funcArgs[] = $args->item( $i );
2848 $allArgs[] = $funcArgs;
2850 # Convert arguments to plain text
2851 for ( $i = 0; $i < $args->getLength(); $i++
) {
2852 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2854 $allArgs = array_merge( $initialArgs, $funcArgs );
2857 # Workaround for PHP bug 35229 and similar
2858 if ( !is_callable( $callback ) ) {
2859 wfProfileOut( __METHOD__
. '-pfunc' );
2860 wfProfileOut( __METHOD__
);
2861 throw new MWException( "Tag hook for $function is not callable\n" );
2863 $result = call_user_func_array( $callback, $allArgs );
2866 $preprocessFlags = 0;
2868 if ( is_array( $result ) ) {
2869 if ( isset( $result[0] ) ) {
2871 unset( $result[0] );
2874 // Extract flags into the local scope
2875 // This allows callers to set flags such as nowiki, found, etc.
2881 $text = $this->preprocessToDom( $text, $preprocessFlags );
2886 wfProfileOut( __METHOD__
. '-pfunc' );
2889 # Finish mangling title and then check for loops.
2890 # Set $title to a Title object and $titleText to the PDBK
2893 # Split the title into page and subpage
2895 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2896 if ($subpage !== '') {
2897 $ns = $this->mTitle
->getNamespace();
2899 $title = Title
::newFromText( $part1, $ns );
2901 $titleText = $title->getPrefixedText();
2902 # Check for language variants if the template is not found
2903 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2904 $wgContLang->findVariantLink( $part1, $title, true );
2906 # Do recursion depth check
2907 $limit = $this->mOptions
->getMaxTemplateDepth();
2908 if ( $frame->depth
>= $limit ) {
2910 $text = '<span class="error">' . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit ) . '</span>';
2915 # Load from database
2916 if ( !$found && $title ) {
2917 wfProfileIn( __METHOD__
. '-loadtpl' );
2918 if ( !$title->isExternal() ) {
2919 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2920 $text = SpecialPage
::capturePath( $title );
2921 if ( is_string( $text ) ) {
2924 $this->disableCache();
2926 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2927 $found = false; //access denied
2928 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
2930 list( $text, $title ) = $this->getTemplateDom( $title );
2931 if ( $text !== false ) {
2937 # If the title is valid but undisplayable, make a link to it
2938 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2939 $text = "[[:$titleText]]";
2942 } elseif ( $title->isTrans() ) {
2943 // Interwiki transclusion
2944 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
2945 $text = $this->interwikiTransclude( $title, 'render' );
2948 $text = $this->interwikiTransclude( $title, 'raw' );
2949 // Preprocess it like a template
2950 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
2956 # Do infinite loop check
2957 # This has to be done after redirect resolution to avoid infinite loops via redirects
2958 if ( !$frame->loopCheck( $title ) ) {
2960 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
2961 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
2963 wfProfileOut( __METHOD__
. '-loadtpl' );
2966 # If we haven't found text to substitute by now, we're done
2967 # Recover the source wikitext and return it
2969 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2970 wfProfileOut( __METHOD__
);
2971 return array( 'object' => $text );
2974 # Expand DOM-style return values in a child frame
2975 if ( $isChildObj ) {
2976 # Clean up argument array
2977 $newFrame = $frame->newChild( $args, $title );
2980 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
2981 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
2982 # Expansion is eligible for the empty-frame cache
2983 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
2984 $text = $this->mTplExpandCache
[$titleText];
2986 $text = $newFrame->expand( $text );
2987 $this->mTplExpandCache
[$titleText] = $text;
2990 # Uncached expansion
2991 $text = $newFrame->expand( $text );
2994 if ( $isLocalObj && $nowiki ) {
2995 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
2996 $isLocalObj = false;
2999 # Replace raw HTML by a placeholder
3000 # Add a blank line preceding, to prevent it from mucking up
3001 # immediately preceding headings
3003 $text = "\n\n" . $this->insertStripItem( $text );
3005 # Escape nowiki-style return values
3006 elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3007 $text = wfEscapeWikiText( $text );
3009 # Bug 529: if the template begins with a table or block-level
3010 # element, it should be treated as beginning a new line.
3011 # This behaviour is somewhat controversial.
3012 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3013 $text = "\n" . $text;
3016 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3017 # Error, oversize inclusion
3018 $text = "[[$originalTitle]]" .
3019 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3020 $this->limitationWarn( 'post-expand-template-inclusion' );
3023 if ( $isLocalObj ) {
3024 $ret = array( 'object' => $text );
3026 $ret = array( 'text' => $text );
3029 wfProfileOut( __METHOD__
);
3034 * Get the semi-parsed DOM representation of a template with a given title,
3035 * and its redirect destination title. Cached.
3037 function getTemplateDom( $title ) {
3038 $cacheTitle = $title;
3039 $titleText = $title->getPrefixedDBkey();
3041 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3042 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3043 $title = Title
::makeTitle( $ns, $dbk );
3044 $titleText = $title->getPrefixedDBkey();
3046 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3047 return array( $this->mTplDomCache
[$titleText], $title );
3050 // Cache miss, go to the database
3051 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3053 if ( $text === false ) {
3054 $this->mTplDomCache
[$titleText] = false;
3055 return array( false, $title );
3058 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3059 $this->mTplDomCache
[ $titleText ] = $dom;
3061 if (! $title->equals($cacheTitle)) {
3062 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3063 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3066 return array( $dom, $title );
3070 * Fetch the unparsed text of a template and register a reference to it.
3072 function fetchTemplateAndTitle( $title ) {
3073 $templateCb = $this->mOptions
->getTemplateCallback();
3074 $stuff = call_user_func( $templateCb, $title, $this );
3075 $text = $stuff['text'];
3076 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3077 if ( isset( $stuff['deps'] ) ) {
3078 foreach ( $stuff['deps'] as $dep ) {
3079 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3082 return array($text,$finalTitle);
3085 function fetchTemplate( $title ) {
3086 $rv = $this->fetchTemplateAndTitle($title);
3091 * Static function to get a template
3092 * Can be overridden via ParserOptions::setTemplateCallback().
3094 static function statelessFetchTemplate( $title, $parser=false ) {
3095 $text = $skip = false;
3096 $finalTitle = $title;
3099 // Loop to fetch the article, with up to 1 redirect
3100 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3101 # Give extensions a chance to select the revision instead
3102 $id = false; // Assume current
3103 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3109 'page_id' => $title->getArticleID(),
3113 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3114 $rev_id = $rev ?
$rev->getId() : 0;
3115 // If there is no current revision, there is no page
3116 if( $id === false && !$rev ) {
3117 $linkCache = LinkCache
::singleton();
3118 $linkCache->addBadLinkObj( $title );
3123 'page_id' => $title->getArticleID(),
3124 'rev_id' => $rev_id );
3127 $text = $rev->getText();
3128 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3130 $message = $wgContLang->lcfirst( $title->getText() );
3131 $text = wfMsgForContentNoTrans( $message );
3132 if( wfEmptyMsg( $message, $text ) ) {
3139 if ( $text === false ) {
3143 $finalTitle = $title;
3144 $title = Title
::newFromRedirect( $text );
3148 'finalTitle' => $finalTitle,
3153 * Transclude an interwiki link.
3155 function interwikiTransclude( $title, $action ) {
3156 global $wgEnableScaryTranscluding;
3158 if (!$wgEnableScaryTranscluding)
3159 return wfMsg('scarytranscludedisabled');
3161 $url = $title->getFullUrl( "action=$action" );
3163 if (strlen($url) > 255)
3164 return wfMsg('scarytranscludetoolong');
3165 return $this->fetchScaryTemplateMaybeFromCache($url);
3168 function fetchScaryTemplateMaybeFromCache($url) {
3169 global $wgTranscludeCacheExpiry;
3170 $dbr = wfGetDB(DB_SLAVE
);
3171 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3172 array('tc_url' => $url));
3174 $time = $obj->tc_time
;
3175 $text = $obj->tc_contents
;
3176 if ($time && time() < $time +
$wgTranscludeCacheExpiry ) {
3181 $text = Http
::get($url);
3183 return wfMsg('scarytranscludefailed', $url);
3185 $dbw = wfGetDB(DB_MASTER
);
3186 $dbw->replace('transcache', array('tc_url'), array(
3188 'tc_time' => time(),
3189 'tc_contents' => $text));
3195 * Triple brace replacement -- used for template arguments
3198 function argSubstitution( $piece, $frame ) {
3199 wfProfileIn( __METHOD__
);
3202 $parts = $piece['parts'];
3203 $nameWithSpaces = $frame->expand( $piece['title'] );
3204 $argName = trim( $nameWithSpaces );
3206 $text = $frame->getArgument( $argName );
3207 if ( $text === false && $parts->getLength() > 0
3211 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3214 # No match in frame, use the supplied default
3215 $object = $parts->item( 0 )->getChildren();
3217 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3218 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3219 $this->limitationWarn( 'post-expand-template-argument' );
3222 if ( $text === false && $object === false ) {
3224 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3226 if ( $error !== false ) {
3229 if ( $object !== false ) {
3230 $ret = array( 'object' => $object );
3232 $ret = array( 'text' => $text );
3235 wfProfileOut( __METHOD__
);
3240 * Return the text to be used for a given extension tag.
3241 * This is the ghost of strip().
3243 * @param array $params Associative array of parameters:
3244 * name PPNode for the tag name
3245 * attr PPNode for unparsed text where tag attributes are thought to be
3246 * attributes Optional associative array of parsed attributes
3247 * inner Contents of extension element
3248 * noClose Original text did not have a close tag
3249 * @param PPFrame $frame
3251 function extensionSubstitution( $params, $frame ) {
3252 global $wgRawHtml, $wgContLang;
3254 $name = $frame->expand( $params['name'] );
3255 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3256 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3258 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3260 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3261 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3262 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3263 $name = strtolower( $name );
3264 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3265 if ( isset( $params['attributes'] ) ) {
3266 $attributes = $attributes +
$params['attributes'];
3274 throw new MWException( '<html> extension tag encountered unexpectedly' );
3277 $content = strtr($content, array('-{' => '-{', '}-' => '}-'));
3278 $output = Xml
::escapeTagsOnly( $content );
3281 $output = $wgContLang->armourMath(
3282 MathRenderer
::renderMath( $content, $attributes ) );
3285 $output = $this->renderImageGallery( $content, $attributes );
3288 if( isset( $this->mTagHooks
[$name] ) ) {
3289 # Workaround for PHP bug 35229 and similar
3290 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3291 throw new MWException( "Tag hook for $name is not callable\n" );
3293 $output = call_user_func_array( $this->mTagHooks
[$name],
3294 array( $content, $attributes, $this ) );
3295 } elseif( isset( $this->mFunctionTagHooks
[$name] ) ) {
3296 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3297 if( !is_callable( $callback ) )
3298 throw new MWException( "Tag hook for $name is not callable\n" );
3300 $output = call_user_func_array( $callback,
3301 array( &$this, $frame, $content, $attributes ) );
3303 $output = '<span class="error">Invalid tag extension name: ' .
3304 htmlspecialchars( $name ) . '</span>';
3308 if ( is_null( $attrText ) ) {
3311 if ( isset( $params['attributes'] ) ) {
3312 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3313 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3314 htmlspecialchars( $attrValue ) . '"';
3317 if ( $content === null ) {
3318 $output = "<$name$attrText/>";
3320 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3321 $output = "<$name$attrText>$content$close";
3325 if( $isFunctionTag ) {
3327 } elseif ( $name === 'html' ||
$name === 'nowiki' ) {
3328 $this->mStripState
->nowiki
->setPair( $marker, $output );
3330 $this->mStripState
->general
->setPair( $marker, $output );
3336 * Increment an include size counter
3338 * @param string $type The type of expansion
3339 * @param integer $size The size of the text
3340 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3342 function incrementIncludeSize( $type, $size ) {
3343 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3346 $this->mIncludeSizes
[$type] +
= $size;
3352 * Increment the expensive function count
3354 * @return boolean False if the limit has been exceeded
3356 function incrementExpensiveFunctionCount() {
3357 global $wgExpensiveParserFunctionLimit;
3358 $this->mExpensiveFunctionCount++
;
3359 if($this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit) {
3366 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3367 * Fills $this->mDoubleUnderscores, returns the modified text
3369 function doDoubleUnderscore( $text ) {
3370 wfProfileIn( __METHOD__
);
3371 // The position of __TOC__ needs to be recorded
3372 $mw = MagicWord
::get( 'toc' );
3373 if( $mw->match( $text ) ) {
3374 $this->mShowToc
= true;
3375 $this->mForceTocPosition
= true;
3377 // Set a placeholder. At the end we'll fill it in with the TOC.
3378 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3380 // Only keep the first one.
3381 $text = $mw->replace( '', $text );
3384 // Now match and remove the rest of them
3385 $mwa = MagicWord
::getDoubleUnderscoreArray();
3386 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3388 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3389 $this->mOutput
->mNoGallery
= true;
3391 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3392 $this->mShowToc
= false;
3394 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3395 $this->mOutput
->setProperty( 'hiddencat', 'y' );
3397 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, wfMsgForContent( 'hidden-category-category' ) );
3398 if ( $containerCategory ) {
3399 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3401 wfDebug( __METHOD__
.": [[MediaWiki:hidden-category-category]] is not a valid title!\n" );
3404 # (bug 8068) Allow control over whether robots index a page.
3406 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3407 # is not desirable, the last one on the page should win.
3408 if( isset( $this->mDoubleUnderscores
['noindex'] ) ) {
3409 $this->mOutput
->setIndexPolicy( 'noindex' );
3410 } elseif( isset( $this->mDoubleUnderscores
['index'] ) ) {
3411 $this->mOutput
->setIndexPolicy( 'index' );
3413 wfProfileOut( __METHOD__
);
3418 * This function accomplishes several tasks:
3419 * 1) Auto-number headings if that option is enabled
3420 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3421 * 3) Add a Table of contents on the top for users who have enabled the option
3422 * 4) Auto-anchor headings
3424 * It loops through all headlines, collects the necessary data, then splits up the
3425 * string and re-inserts the newly formatted headlines.
3427 * @param string $text
3428 * @param string $origText Original, untouched wikitext
3429 * @param boolean $isMain
3432 function formatHeadings( $text, $origText, $isMain=true ) {
3433 global $wgMaxTocLevel, $wgContLang, $wgEnforceHtmlIds;
3435 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3436 $showEditLink = $this->mOptions
->getEditSection();
3438 // Do not call quickUserCan unless necessary
3439 if( $showEditLink && !$this->mTitle
->quickUserCan( 'edit' ) ) {
3443 # Inhibit editsection links if requested in the page
3444 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ||
$this->mOptions
->getIsPrintable() ) {
3448 # Get all headlines for numbering them and adding funky stuff like [edit]
3449 # links - this is for later, but we need the number of headlines right now
3451 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3453 # if there are fewer than 4 headlines in the article, do not show TOC
3454 # unless it's been explicitly enabled.
3455 $enoughToc = $this->mShowToc
&&
3456 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3458 # Allow user to stipulate that a page should have a "new section"
3459 # link added via __NEWSECTIONLINK__
3460 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3461 $this->mOutput
->setNewSection( true );
3464 # Allow user to remove the "new section"
3465 # link via __NONEWSECTIONLINK__
3466 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3467 $this->mOutput
->hideNewSection( true );
3470 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3471 # override above conditions and always show TOC above first header
3472 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3473 $this->mShowToc
= true;
3477 # We need this to perform operations on the HTML
3478 $sk = $this->mOptions
->getSkin();
3484 # Ugh .. the TOC should have neat indentation levels which can be
3485 # passed to the skin functions. These are determined here
3489 $sublevelCount = array();
3490 $levelCount = array();
3496 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3497 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3498 $oldType = $this->mOutputType
;
3499 $this->setOutputType( self
::OT_WIKI
);
3500 $frame = $this->getPreprocessor()->newFrame();
3501 $root = $this->preprocessToDom( $origText );
3502 $node = $root->getFirstChild();
3506 foreach( $matches[3] as $headline ) {
3507 $isTemplate = false;
3509 $sectionIndex = false;
3511 $markerMatches = array();
3512 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3513 $serial = $markerMatches[1];
3514 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3515 $isTemplate = ($titleText != $baseTitleText);
3516 $headline = preg_replace("/^$markerRegex/", "", $headline);
3520 $prevlevel = $level;
3521 $prevtoclevel = $toclevel;
3523 $level = $matches[1][$headlineCount];
3525 if ( $level > $prevlevel ) {
3526 # Increase TOC level
3528 $sublevelCount[$toclevel] = 0;
3529 if( $toclevel<$wgMaxTocLevel ) {
3530 $prevtoclevel = $toclevel;
3531 $toc .= $sk->tocIndent();
3535 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3536 # Decrease TOC level, find level to jump to
3538 for ($i = $toclevel; $i > 0; $i--) {
3539 if ( $levelCount[$i] == $level ) {
3540 # Found last matching level
3544 elseif ( $levelCount[$i] < $level ) {
3545 # Found first matching level below current level
3550 if( $i == 0 ) $toclevel = 1;
3551 if( $toclevel<$wgMaxTocLevel ) {
3552 if($prevtoclevel < $wgMaxTocLevel) {
3553 # Unindent only if the previous toc level was shown :p
3554 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3555 $prevtoclevel = $toclevel;
3557 $toc .= $sk->tocLineEnd();
3562 # No change in level, end TOC line
3563 if( $toclevel<$wgMaxTocLevel ) {
3564 $toc .= $sk->tocLineEnd();
3568 $levelCount[$toclevel] = $level;
3570 # count number of headlines for each level
3571 @$sublevelCount[$toclevel]++
;
3573 for( $i = 1; $i <= $toclevel; $i++
) {
3574 if( !empty( $sublevelCount[$i] ) ) {
3578 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3583 # The safe header is a version of the header text safe to use for links
3584 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3585 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3587 # Remove link placeholders by the link text.
3588 # <!--LINK number-->
3590 # link text with suffix
3591 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3593 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3594 $tocline = preg_replace(
3595 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3599 $tocline = trim( $tocline );
3601 # For the anchor, strip out HTML-y stuff period
3602 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3603 $safeHeadline = preg_replace( '/[ _]+/', ' ', $safeHeadline );
3604 $safeHeadline = trim( $safeHeadline );
3606 # Save headline for section edit hint before it's escaped
3607 $headlineHint = $safeHeadline;
3609 if ( $wgEnforceHtmlIds ) {
3610 $legacyHeadline = false;
3611 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
3614 # For reverse compatibility, provide an id that's
3615 # HTML4-compatible, like we used to.
3617 # It may be worth noting, academically, that it's possible for
3618 # the legacy anchor to conflict with a non-legacy headline
3619 # anchor on the page. In this case likely the "correct" thing
3620 # would be to either drop the legacy anchors or make sure
3621 # they're numbered first. However, this would require people
3622 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3623 # manually, so let's not bother worrying about it.
3624 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
3626 $safeHeadline = Sanitizer
::escapeId( $safeHeadline, 'xml' );
3628 if ( $legacyHeadline == $safeHeadline ) {
3629 # No reason to have both (in fact, we can't)
3630 $legacyHeadline = false;
3631 } elseif ( $legacyHeadline != Sanitizer
::escapeId(
3632 $legacyHeadline, 'xml' ) ) {
3633 # The legacy id is invalid XML. We used to allow this, but
3634 # there's no reason to do so anymore. Backward
3635 # compatibility will fail slightly in this case, but it's
3637 $legacyHeadline = false;
3641 # HTML names must be case-insensitively unique (bug 10721). FIXME:
3642 # Does this apply to Unicode characters? Because we aren't
3643 # handling those here.
3644 $arrayKey = strtolower( $safeHeadline );
3645 if ( $legacyHeadline === false ) {
3646 $legacyArrayKey = false;
3648 $legacyArrayKey = strtolower( $legacyHeadline );
3651 # count how many in assoc. array so we can track dupes in anchors
3652 if ( isset( $refers[$arrayKey] ) ) {
3653 $refers[$arrayKey]++
;
3655 $refers[$arrayKey] = 1;
3657 if ( isset( $refers[$legacyArrayKey] ) ) {
3658 $refers[$legacyArrayKey]++
;
3660 $refers[$legacyArrayKey] = 1;
3663 # Don't number the heading if it is the only one (looks silly)
3664 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3665 # the two are different if the line contains a link
3666 $headline=$numbering . ' ' . $headline;
3669 # Create the anchor for linking from the TOC to the section
3670 $anchor = $safeHeadline;
3671 $legacyAnchor = $legacyHeadline;
3672 if ( $refers[$arrayKey] > 1 ) {
3673 $anchor .= '_' . $refers[$arrayKey];
3675 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3676 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3678 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3679 $toc .= $sk->tocLine($anchor, $tocline,
3680 $numbering, $toclevel, ($isTemplate ?
false : $sectionIndex));
3683 # Add the section to the section tree
3684 # Find the DOM node for this header
3685 while ( $node && !$isTemplate ) {
3686 if ( $node->getName() === 'h' ) {
3687 $bits = $node->splitHeading();
3688 if ( $bits['i'] == $sectionIndex )
3691 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
3692 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
3693 $node = $node->getNextSibling();
3696 'toclevel' => $toclevel,
3699 'number' => $numbering,
3700 'index' => ($isTemplate ?
'T-' : '' ) . $sectionIndex,
3701 'fromtitle' => $titleText,
3702 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
3703 'anchor' => $anchor,
3706 # give headline the correct <h#> tag
3707 if( $showEditLink && $sectionIndex !== false ) {
3709 # Put a T flag in the section identifier, to indicate to extractSections()
3710 # that sections inside <includeonly> should be counted.
3711 $editlink = $sk->doEditSectionLink(Title
::newFromText( $titleText ), "T-$sectionIndex");
3713 $editlink = $sk->doEditSectionLink($this->mTitle
, $sectionIndex, $headlineHint);
3718 $head[$headlineCount] = $sk->makeHeadline( $level,
3719 $matches['attrib'][$headlineCount], $anchor, $headline,
3720 $editlink, $legacyAnchor );
3725 $this->setOutputType( $oldType );
3727 # Never ever show TOC if no headers
3728 if( $numVisible < 1 ) {
3733 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3734 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3736 $toc = $sk->tocList( $toc );
3737 $this->mOutput
->setTOCHTML( $toc );
3741 $this->mOutput
->setSections( $tocraw );
3744 # split up and insert constructed headlines
3746 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3749 foreach( $blocks as $block ) {
3750 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3751 # This is the [edit] link that appears for the top block of text when
3752 # section editing is enabled
3754 # Disabled because it broke block formatting
3755 # For example, a bullet point in the top line
3756 # $full .= $sk->editSectionLink(0);
3759 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3760 # Top anchor now in skin
3764 if( !empty( $head[$i] ) ) {
3769 if( $this->mForceTocPosition
) {
3770 return str_replace( '<!--MWTOC-->', $toc, $full );
3777 * Merge $tree2 into $tree1 by replacing the section with index
3778 * $section in $tree1 and its descendants with the sections in $tree2.
3779 * Note that in the returned section tree, only the 'index' and
3780 * 'byteoffset' fields are guaranteed to be correct.
3781 * @param $tree1 array Section tree from ParserOutput::getSectons()
3782 * @param $tree2 array Section tree
3783 * @param $section int Section index
3784 * @param $title Title Title both section trees come from
3785 * @param $len2 int Length of the original wikitext for $tree2
3786 * @return array Merged section tree
3788 public static function mergeSectionTrees( $tree1, $tree2, $section, $title, $len2 ) {
3791 $targetLevel = false;
3795 $numbering = array( 0 );
3796 $titletext = $title->getPrefixedDBkey();
3797 foreach ( $tree1 as $s ) {
3798 if ( $targetLevel !== false ) {
3799 if ( $s['level'] <= $targetLevel )
3800 // We've skipped enough
3801 $targetLevel = false;
3805 if ( $s['index'] != $section ||
3806 $s['fromtitle'] != $titletext ) {
3807 self
::incrementNumbering( $numbering,
3808 $s['toclevel'], $lastLevel );
3810 // Rewrite index, byteoffset and number
3811 if ( $s['fromtitle'] == $titletext ) {
3812 $s['index'] = $nextIndex++
;
3814 $s['byteoffset'] +
= $len2;
3816 $s['number'] = implode( '.', array_map(
3817 array( $wgContLang, 'formatnum' ),
3819 $lastLevel = $s['toclevel'];
3822 // We're at $section
3823 // Insert sections from $tree2 here
3824 foreach ( $tree2 as $s2 ) {
3825 // Rewrite the fields in $s2
3826 // before inserting it
3827 $s2['toclevel'] +
= $s['toclevel'] - 1;
3828 $s2['level'] +
= $s['level'] - 1;
3829 $s2['index'] = $nextIndex++
;
3830 $s2['byteoffset'] +
= $s['byteoffset'];
3832 self
::incrementNumbering( $numbering,
3833 $s2['toclevel'], $lastLevel );
3834 $s2['number'] = implode( '.', array_map(
3835 array( $wgContLang, 'formatnum' ),
3837 $lastLevel = $s2['toclevel'];
3840 // Skip all descendants of $section in $tree1
3841 $targetLevel = $s['level'];
3849 * Increment a section number. Helper function for mergeSectionTrees()
3850 * @param $number array Array representing a section number
3851 * @param $level int Current TOC level (depth)
3852 * @param $lastLevel int Level of previous TOC entry
3854 private static function incrementNumbering( &$number, $level, $lastLevel ) {
3855 if ( $level > $lastLevel )
3856 $number[$level - 1] = 1;
3857 else if ( $level < $lastLevel ) {
3858 foreach ( $number as $key => $unused )
3859 if ( $key >= $level )
3860 unset( $number[$key] );
3861 $number[$level - 1]++
;
3863 $number[$level - 1]++
;
3867 * Transform wiki markup when saving a page by doing \r\n -> \n
3868 * conversion, substitting signatures, {{subst:}} templates, etc.
3870 * @param string $text the text to transform
3871 * @param Title &$title the Title object for the current article
3872 * @param User $user the User object describing the current user
3873 * @param ParserOptions $options parsing options
3874 * @param bool $clearState whether to clear the parser state first
3875 * @return string the altered wiki markup
3878 function preSaveTransform( $text, Title
$title, $user, $options, $clearState = true ) {
3879 $this->mOptions
= $options;
3880 $this->setTitle( $title );
3881 $this->setOutputType( self
::OT_WIKI
);
3883 if ( $clearState ) {
3884 $this->clearState();
3890 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3891 $text = $this->pstPass2( $text, $user );
3892 $text = $this->mStripState
->unstripBoth( $text );
3897 * Pre-save transform helper function
3900 function pstPass2( $text, $user ) {
3901 global $wgContLang, $wgLocaltimezone;
3903 /* Note: This is the timestamp saved as hardcoded wikitext to
3904 * the database, we use $wgContLang here in order to give
3905 * everyone the same signature and use the default one rather
3906 * than the one selected in each user's preferences.
3908 * (see also bug 12815)
3910 $ts = $this->mOptions
->getTimestamp();
3911 $tz = wfMsgForContent( 'timezone-utc' );
3912 if ( isset( $wgLocaltimezone ) ) {
3913 $unixts = wfTimestamp( TS_UNIX
, $ts );
3914 $oldtz = getenv( 'TZ' );
3915 putenv( 'TZ='.$wgLocaltimezone );
3916 $ts = date( 'YmdHis', $unixts );
3917 $tz = date( 'T', $unixts ); # might vary on DST changeover!
3919 /* Allow translation of timezones trough wiki. date() can return
3920 * whatever crap the system uses, localised or not, so we cannot
3921 * ship premade translations.
3923 $key = 'timezone-' . strtolower( trim( $tz ) );
3924 $value = wfMsgForContent( $key );
3925 if ( !wfEmptyMsg( $key, $value ) ) $tz = $value;
3927 putenv( 'TZ='.$oldtz );
3930 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tz)";
3932 # Variable replacement
3933 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3934 $text = $this->replaceVariables( $text );
3937 $sigText = $this->getUserSig( $user );
3938 $text = strtr( $text, array(
3940 '~~~~' => "$sigText $d",
3944 # Context links: [[|name]] and [[name (context)|]]
3946 global $wgLegalTitleChars;
3947 $tc = "[$wgLegalTitleChars]";
3948 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
3950 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
3951 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
3952 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
3953 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
3955 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
3956 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
3957 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
3958 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
3960 $t = $this->mTitle
->getText();
3962 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
3963 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3964 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && '' != "$m[1]$m[2]" ) {
3965 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
3967 # if there's no context, don't bother duplicating the title
3968 $text = preg_replace( $p2, '[[\\1]]', $text );
3971 # Trim trailing whitespace
3972 $text = rtrim( $text );
3978 * Fetch the user's signature text, if any, and normalize to
3979 * validated, ready-to-insert wikitext.
3985 function getUserSig( &$user ) {
3986 global $wgMaxSigChars;
3988 $username = $user->getName();
3989 $nickname = $user->getOption( 'nickname' );
3990 $nickname = $nickname === null ?
$username : $nickname;
3992 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
3993 $nickname = $username;
3994 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
3995 } elseif( $user->getBoolOption( 'fancysig' ) !== false ) {
3996 # Sig. might contain markup; validate this
3997 if( $this->validateSig( $nickname ) !== false ) {
3998 # Validated; clean up (if needed) and return it
3999 return $this->cleanSig( $nickname, true );
4001 # Failed to validate; fall back to the default
4002 $nickname = $username;
4003 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4007 // Make sure nickname doesnt get a sig in a sig
4008 $nickname = $this->cleanSigInSig( $nickname );
4010 # If we're still here, make it a link to the user page
4011 $userText = wfEscapeWikiText( $username );
4012 $nickText = wfEscapeWikiText( $nickname );
4013 if ( $user->isAnon() ) {
4014 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4016 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4021 * Check that the user's signature contains no bad XML
4023 * @param string $text
4024 * @return mixed An expanded string, or false if invalid.
4026 function validateSig( $text ) {
4027 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4031 * Clean up signature text
4033 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4034 * 2) Substitute all transclusions
4036 * @param string $text
4037 * @param $parsing Whether we're cleaning (preferences save) or parsing
4038 * @return string Signature text
4040 function cleanSig( $text, $parsing = false ) {
4043 $this->clearState();
4044 $this->setTitle( $wgTitle );
4045 $this->mOptions
= new ParserOptions
;
4046 $this->setOutputType
= self
::OT_PREPROCESS
;
4049 # Option to disable this feature
4050 if ( !$this->mOptions
->getCleanSignatures() ) {
4054 # FIXME: regex doesn't respect extension tags or nowiki
4055 # => Move this logic to braceSubstitution()
4056 $substWord = MagicWord
::get( 'subst' );
4057 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4058 $substText = '{{' . $substWord->getSynonym( 0 );
4060 $text = preg_replace( $substRegex, $substText, $text );
4061 $text = $this->cleanSigInSig( $text );
4062 $dom = $this->preprocessToDom( $text );
4063 $frame = $this->getPreprocessor()->newFrame();
4064 $text = $frame->expand( $dom );
4067 $text = $this->mStripState
->unstripBoth( $text );
4074 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4075 * @param string $text
4076 * @return string Signature text with /~{3,5}/ removed
4078 function cleanSigInSig( $text ) {
4079 $text = preg_replace( '/~{3,5}/', '', $text );
4084 * Set up some variables which are usually set up in parse()
4085 * so that an external function can call some class members with confidence
4088 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
4089 $this->setTitle( $title );
4090 $this->mOptions
= $options;
4091 $this->setOutputType( $outputType );
4092 if ( $clearState ) {
4093 $this->clearState();
4098 * Wrapper for preprocess()
4100 * @param string $text the text to preprocess
4101 * @param ParserOptions $options options
4105 function transformMsg( $text, $options ) {
4107 static $executing = false;
4109 # Guard against infinite recursion
4115 wfProfileIn(__METHOD__
);
4116 $text = $this->preprocess( $text, $wgTitle, $options );
4119 wfProfileOut(__METHOD__
);
4124 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4125 * The callback should have the following form:
4126 * function myParserHook( $text, $params, &$parser ) { ... }
4128 * Transform and return $text. Use $parser for any required context, e.g. use
4129 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4133 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
4134 * @param mixed $callback The callback function (and object) to use for the tag
4136 * @return The old value of the mTagHooks array associated with the hook
4138 function setHook( $tag, $callback ) {
4139 $tag = strtolower( $tag );
4140 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4141 $this->mTagHooks
[$tag] = $callback;
4142 if( !in_array( $tag, $this->mStripList
) ) {
4143 $this->mStripList
[] = $tag;
4149 function setTransparentTagHook( $tag, $callback ) {
4150 $tag = strtolower( $tag );
4151 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4152 $this->mTransparentTagHooks
[$tag] = $callback;
4158 * Remove all tag hooks
4160 function clearTagHooks() {
4161 $this->mTagHooks
= array();
4162 $this->mStripList
= $this->mDefaultStripList
;
4166 * Create a function, e.g. {{sum:1|2|3}}
4167 * The callback function should have the form:
4168 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4170 * Or with SFH_OBJECT_ARGS:
4171 * function myParserFunction( $parser, $frame, $args ) { ... }
4173 * The callback may either return the text result of the function, or an array with the text
4174 * in element 0, and a number of flags in the other elements. The names of the flags are
4175 * specified in the keys. Valid flags are:
4176 * found The text returned is valid, stop processing the template. This
4178 * nowiki Wiki markup in the return value should be escaped
4179 * isHTML The returned text is HTML, armour it against wikitext transformation
4183 * @param string $id The magic word ID
4184 * @param mixed $callback The callback function (and object) to use
4185 * @param integer $flags a combination of the following flags:
4186 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4188 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4189 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4190 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4191 * the arguments, and to control the way they are expanded.
4193 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4194 * arguments, for instance:
4195 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4197 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4198 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4199 * working if/when this is changed.
4201 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4204 * Please read the documentation in includes/parser/Preprocessor.php for more information
4205 * about the methods available in PPFrame and PPNode.
4207 * @return The old callback function for this name, if any
4209 function setFunctionHook( $id, $callback, $flags = 0 ) {
4210 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4211 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4213 # Add to function cache
4214 $mw = MagicWord
::get( $id );
4216 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4218 $synonyms = $mw->getSynonyms();
4219 $sensitive = intval( $mw->isCaseSensitive() );
4221 foreach ( $synonyms as $syn ) {
4223 if ( !$sensitive ) {
4224 $syn = strtolower( $syn );
4227 if ( !( $flags & SFH_NO_HASH
) ) {
4230 # Remove trailing colon
4231 if ( substr( $syn, -1, 1 ) === ':' ) {
4232 $syn = substr( $syn, 0, -1 );
4234 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4240 * Get all registered function hook identifiers
4244 function getFunctionHooks() {
4245 return array_keys( $this->mFunctionHooks
);
4249 * Create a tag function, e.g. <test>some stuff</test>.
4250 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4251 * Unlike parser functions, their content is not preprocessed.
4253 function setFunctionTagHook( $tag, $callback, $flags ) {
4254 $tag = strtolower( $tag );
4255 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4256 $this->mFunctionTagHooks
[$tag] : null;
4257 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4259 if( !in_array( $tag, $this->mStripList
) ) {
4260 $this->mStripList
[] = $tag;
4267 * FIXME: update documentation. makeLinkObj() is deprecated.
4268 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4269 * Placeholders created in Skin::makeLinkObj()
4270 * Returns an array of link CSS classes, indexed by PDBK.
4272 function replaceLinkHolders( &$text, $options = 0 ) {
4273 return $this->mLinkHolders
->replace( $text );
4277 * Replace <!--LINK--> link placeholders with plain text of links
4278 * (not HTML-formatted).
4279 * @param string $text
4282 function replaceLinkHoldersText( $text ) {
4283 return $this->mLinkHolders
->replaceText( $text );
4287 * Tag hook handler for 'pre'.
4289 function renderPreTag( $text, $attribs ) {
4290 // Backwards-compatibility hack
4291 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4293 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4294 return Xml
::openElement( 'pre', $attribs ) .
4295 Xml
::escapeTagsOnly( $content ) .
4300 * Renders an image gallery from a text with one line per image.
4301 * text labels may be given by using |-style alternative text. E.g.
4302 * Image:one.jpg|The number "1"
4303 * Image:tree.jpg|A tree
4304 * given as text will return the HTML of a gallery with two images,
4305 * labeled 'The number "1"' and
4308 function renderImageGallery( $text, $params ) {
4309 $ig = new ImageGallery();
4310 $ig->setContextTitle( $this->mTitle
);
4311 $ig->setShowBytes( false );
4312 $ig->setShowFilename( false );
4313 $ig->setParser( $this );
4314 $ig->setHideBadImages();
4315 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4316 $ig->useSkin( $this->mOptions
->getSkin() );
4317 $ig->mRevisionId
= $this->mRevisionId
;
4319 if( isset( $params['caption'] ) ) {
4320 $caption = $params['caption'];
4321 $caption = htmlspecialchars( $caption );
4322 $caption = $this->replaceInternalLinks( $caption );
4323 $ig->setCaptionHtml( $caption );
4325 if( isset( $params['perrow'] ) ) {
4326 $ig->setPerRow( $params['perrow'] );
4328 if( isset( $params['widths'] ) ) {
4329 $ig->setWidths( $params['widths'] );
4331 if( isset( $params['heights'] ) ) {
4332 $ig->setHeights( $params['heights'] );
4335 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4337 $lines = StringUtils
::explode( "\n", $text );
4338 foreach ( $lines as $line ) {
4339 # match lines like these:
4340 # Image:someimage.jpg|This is some image
4342 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4344 if ( count( $matches ) == 0 ) {
4348 if ( strpos( $matches[0], '%' ) !== false )
4349 $matches[1] = urldecode( $matches[1] );
4350 $tp = Title
::newFromText( $matches[1]/*, NS_FILE*/ );
4352 if( is_null( $nt ) ) {
4353 # Bogus title. Ignore these so we don't bomb out later.
4356 if ( isset( $matches[3] ) ) {
4357 $label = $matches[3];
4362 $html = $this->recursiveTagParse( trim( $label ) );
4364 $ig->add( $nt, $html );
4366 # Only add real images (bug #5586)
4367 if ( $nt->getNamespace() == NS_FILE
) {
4368 $this->mOutput
->addImage( $nt->getDBkey() );
4371 return $ig->toHTML();
4374 function getImageParams( $handler ) {
4376 $handlerClass = get_class( $handler );
4380 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4381 // Initialise static lists
4382 static $internalParamNames = array(
4383 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4384 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4385 'bottom', 'text-bottom' ),
4386 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4387 'upright', 'border', 'link', 'alt' ),
4389 static $internalParamMap;
4390 if ( !$internalParamMap ) {
4391 $internalParamMap = array();
4392 foreach ( $internalParamNames as $type => $names ) {
4393 foreach ( $names as $name ) {
4394 $magicName = str_replace( '-', '_', "img_$name" );
4395 $internalParamMap[$magicName] = array( $type, $name );
4400 // Add handler params
4401 $paramMap = $internalParamMap;
4403 $handlerParamMap = $handler->getParamMap();
4404 foreach ( $handlerParamMap as $magic => $paramName ) {
4405 $paramMap[$magic] = array( 'handler', $paramName );
4408 $this->mImageParams
[$handlerClass] = $paramMap;
4409 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4411 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4415 * Parse image options text and use it to make an image
4416 * @param Title $title
4417 * @param string $options
4418 * @param LinkHolderArray $holders
4420 function makeImage( $title, $options, $holders = false ) {
4421 # Check if the options text is of the form "options|alt text"
4423 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4424 # * left no resizing, just left align. label is used for alt= only
4425 # * right same, but right aligned
4426 # * none same, but not aligned
4427 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4428 # * center center the image
4429 # * frame Keep original image size, no magnify-button.
4430 # * framed Same as "frame"
4431 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4432 # * upright reduce width for upright images, rounded to full __0 px
4433 # * border draw a 1px border around the image
4434 # * alt Text for HTML alt attribute (defaults to empty)
4435 # vertical-align values (no % or length right now):
4445 $parts = StringUtils
::explode( "|", $options );
4446 $sk = $this->mOptions
->getSkin();
4448 # Give extensions a chance to select the file revision for us
4449 $skip = $time = $descQuery = false;
4450 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4453 return $sk->link( $title );
4457 $imagename = $title->getDBkey();
4458 if ( isset( $this->mFileCache
[$imagename][$time] ) ) {
4459 $file = $this->mFileCache
[$imagename][$time];
4461 $file = wfFindFile( $title, $time );
4462 if ( count( $this->mFileCache
) > 1000 ) {
4463 $this->mFileCache
= array();
4465 $this->mFileCache
[$imagename][$time] = $file;
4468 $handler = $file ?
$file->getHandler() : false;
4470 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4472 # Process the input parameters
4474 $params = array( 'frame' => array(), 'handler' => array(),
4475 'horizAlign' => array(), 'vertAlign' => array() );
4476 foreach( $parts as $part ) {
4477 $part = trim( $part );
4478 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4480 if( isset( $paramMap[$magicName] ) ) {
4481 list( $type, $paramName ) = $paramMap[$magicName];
4483 // Special case; width and height come in one variable together
4484 if( $type === 'handler' && $paramName === 'width' ) {
4486 # (bug 13500) In both cases (width/height and width only),
4487 # permit trailing "px" for backward compatibility.
4488 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4489 $width = intval( $m[1] );
4490 $height = intval( $m[2] );
4491 if ( $handler->validateParam( 'width', $width ) ) {
4492 $params[$type]['width'] = $width;
4495 if ( $handler->validateParam( 'height', $height ) ) {
4496 $params[$type]['height'] = $height;
4499 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4500 $width = intval( $value );
4501 if ( $handler->validateParam( 'width', $width ) ) {
4502 $params[$type]['width'] = $width;
4505 } // else no validation -- bug 13436
4507 if ( $type === 'handler' ) {
4508 # Validate handler parameter
4509 $validated = $handler->validateParam( $paramName, $value );
4511 # Validate internal parameters
4512 switch( $paramName ) {
4515 // @fixme - possibly check validity here for
4516 // manualthumb? downstream behavior seems odd with
4517 // missing manual thumbs.
4519 $value = $this->stripAltText( $value, $holders );
4522 $chars = self
::EXT_LINK_URL_CLASS
;
4523 $prots = $this->mUrlProtocols
;
4524 if ( $value === '' ) {
4525 $paramName = 'no-link';
4528 } elseif ( preg_match( "/^$prots/", $value ) ) {
4529 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4530 $paramName = 'link-url';
4531 $this->mOutput
->addExternalLink( $value );
4535 $linkTitle = Title
::newFromText( $value );
4537 $paramName = 'link-title';
4538 $value = $linkTitle;
4539 $this->mOutput
->addLink( $linkTitle );
4545 // Most other things appear to be empty or numeric...
4546 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4551 $params[$type][$paramName] = $value;
4555 if ( !$validated ) {
4560 # Process alignment parameters
4561 if ( $params['horizAlign'] ) {
4562 $params['frame']['align'] = key( $params['horizAlign'] );
4564 if ( $params['vertAlign'] ) {
4565 $params['frame']['valign'] = key( $params['vertAlign'] );
4568 $params['frame']['caption'] = $caption;
4570 # Will the image be presented in a frame, with the caption below?
4571 $imageIsFramed = isset( $params['frame']['frame'] ) ||
4572 isset( $params['frame']['framed'] ) ||
4573 isset( $params['frame']['thumbnail'] ) ||
4574 isset( $params['frame']['manualthumb'] );
4576 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4577 # came to also set the caption, ordinary text after the image -- which
4578 # makes no sense, because that just repeats the text multiple times in
4579 # screen readers. It *also* came to set the title attribute.
4581 # Now that we have an alt attribute, we should not set the alt text to
4582 # equal the caption: that's worse than useless, it just repeats the
4583 # text. This is the framed/thumbnail case. If there's no caption, we
4584 # use the unnamed parameter for alt text as well, just for the time be-
4585 # ing, if the unnamed param is set and the alt param is not.
4587 # For the future, we need to figure out if we want to tweak this more,
4588 # e.g., introducing a title= parameter for the title; ignoring the un-
4589 # named parameter entirely for images without a caption; adding an ex-
4590 # plicit caption= parameter and preserving the old magic unnamed para-
4592 if ( $imageIsFramed ) { # Framed image
4593 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
4594 # No caption or alt text, add the filename as the alt text so
4595 # that screen readers at least get some description of the image
4596 $params['frame']['alt'] = $title->getText();
4598 # Do not set $params['frame']['title'] because tooltips don't make sense
4600 } else { # Inline image
4601 if ( !isset( $params['frame']['alt'] ) ) {
4602 # No alt text, use the "caption" for the alt text
4603 if ( $caption !== '') {
4604 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
4606 # No caption, fall back to using the filename for the
4608 $params['frame']['alt'] = $title->getText();
4611 # Use the "caption" for the tooltip text
4612 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4615 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4617 # Linker does the rest
4618 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4620 # Give the handler a chance to modify the parser object
4622 $handler->parserTransformHook( $this, $file );
4628 protected function stripAltText( $caption, $holders ) {
4629 # Strip bad stuff out of the title (tooltip). We can't just use
4630 # replaceLinkHoldersText() here, because if this function is called
4631 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4633 $tooltip = $holders->replaceText( $caption );
4635 $tooltip = $this->replaceLinkHoldersText( $caption );
4638 # make sure there are no placeholders in thumbnail attributes
4639 # that are later expanded to html- so expand them now and
4641 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
4642 $tooltip = Sanitizer
::stripAllTags( $tooltip );
4648 * Set a flag in the output object indicating that the content is dynamic and
4649 * shouldn't be cached.
4651 function disableCache() {
4652 wfDebug( "Parser output marked as uncacheable.\n" );
4653 $this->mOutput
->mCacheTime
= -1;
4657 * Callback from the Sanitizer for expanding items found in HTML attribute
4658 * values, so they can be safely tested and escaped.
4659 * @param string $text
4660 * @param PPFrame $frame
4664 function attributeStripCallback( &$text, $frame = false ) {
4665 $text = $this->replaceVariables( $text, $frame );
4666 $text = $this->mStripState
->unstripBoth( $text );
4675 function Title( $x = NULL ) { return wfSetVar( $this->mTitle
, $x ); }
4676 function Options( $x = NULL ) { return wfSetVar( $this->mOptions
, $x ); }
4677 function OutputType( $x = NULL ) { return wfSetVar( $this->mOutputType
, $x ); }
4683 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4688 * Break wikitext input into sections, and either pull or replace
4689 * some particular section's text.
4691 * External callers should use the getSection and replaceSection methods.
4693 * @param string $text Page wikitext
4694 * @param string $section A section identifier string of the form:
4695 * <flag1> - <flag2> - ... - <section number>
4697 * Currently the only recognised flag is "T", which means the target section number
4698 * was derived during a template inclusion parse, in other words this is a template
4699 * section edit link. If no flags are given, it was an ordinary section edit link.
4700 * This flag is required to avoid a section numbering mismatch when a section is
4701 * enclosed by <includeonly> (bug 6563).
4703 * The section number 0 pulls the text before the first heading; other numbers will
4704 * pull the given section along with its lower-level subsections. If the section is
4705 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4707 * @param string $mode One of "get" or "replace"
4708 * @param string $newText Replacement text for section data.
4709 * @return string for "get", the extracted section text.
4710 * for "replace", the whole page with the section replaced.
4712 private function extractSections( $text, $section, $mode, $newText='' ) {
4714 $this->clearState();
4715 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4716 $this->mOptions
= new ParserOptions
;
4717 $this->setOutputType( self
::OT_WIKI
);
4719 $frame = $this->getPreprocessor()->newFrame();
4721 // Process section extraction flags
4723 $sectionParts = explode( '-', $section );
4724 $sectionIndex = array_pop( $sectionParts );
4725 foreach ( $sectionParts as $part ) {
4726 if ( $part === 'T' ) {
4727 $flags |
= self
::PTD_FOR_INCLUSION
;
4730 // Preprocess the text
4731 $root = $this->preprocessToDom( $text, $flags );
4733 // <h> nodes indicate section breaks
4734 // They can only occur at the top level, so we can find them by iterating the root's children
4735 $node = $root->getFirstChild();
4737 // Find the target section
4738 if ( $sectionIndex == 0 ) {
4739 // Section zero doesn't nest, level=big
4740 $targetLevel = 1000;
4743 if ( $node->getName() === 'h' ) {
4744 $bits = $node->splitHeading();
4745 if ( $bits['i'] == $sectionIndex ) {
4746 $targetLevel = $bits['level'];
4750 if ( $mode === 'replace' ) {
4751 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4753 $node = $node->getNextSibling();
4759 if ( $mode === 'get' ) {
4766 // Find the end of the section, including nested sections
4768 if ( $node->getName() === 'h' ) {
4769 $bits = $node->splitHeading();
4770 $curLevel = $bits['level'];
4771 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4775 if ( $mode === 'get' ) {
4776 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4778 $node = $node->getNextSibling();
4781 // Write out the remainder (in replace mode only)
4782 if ( $mode === 'replace' ) {
4783 // Output the replacement text
4784 // Add two newlines on -- trailing whitespace in $newText is conventionally
4785 // stripped by the editor, so we need both newlines to restore the paragraph gap
4786 // Only add trailing whitespace if there is newText
4787 if($newText != "") {
4788 $outText .= $newText . "\n\n";
4792 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4793 $node = $node->getNextSibling();
4797 if ( is_string( $outText ) ) {
4798 // Re-insert stripped tags
4799 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4806 * This function returns the text of a section, specified by a number ($section).
4807 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4808 * the first section before any such heading (section 0).
4810 * If a section contains subsections, these are also returned.
4812 * @param string $text text to look in
4813 * @param string $section section identifier
4814 * @param string $deftext default to return if section is not found
4815 * @return string text of the requested section
4817 public function getSection( $text, $section, $deftext='' ) {
4818 return $this->extractSections( $text, $section, "get", $deftext );
4821 public function replaceSection( $oldtext, $section, $text ) {
4822 return $this->extractSections( $oldtext, $section, "replace", $text );
4826 * Get the timestamp associated with the current revision, adjusted for
4827 * the default server-local timestamp
4829 function getRevisionTimestamp() {
4830 if ( is_null( $this->mRevisionTimestamp
) ) {
4831 wfProfileIn( __METHOD__
);
4833 $dbr = wfGetDB( DB_SLAVE
);
4834 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4835 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4837 // Normalize timestamp to internal MW format for timezone processing.
4838 // This has the added side-effect of replacing a null value with
4839 // the current time, which gives us more sensible behavior for
4841 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4843 // The cryptic '' timezone parameter tells to use the site-default
4844 // timezone offset instead of the user settings.
4846 // Since this value will be saved into the parser cache, served
4847 // to other users, and potentially even used inside links and such,
4848 // it needs to be consistent for all visitors.
4849 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4851 wfProfileOut( __METHOD__
);
4853 return $this->mRevisionTimestamp
;
4857 * Get the name of the user that edited the last revision
4859 function getRevisionUser() {
4860 // if this template is subst: the revision id will be blank,
4861 // so just use the current user's name
4862 if( $this->mRevisionId
) {
4863 $revision = Revision
::newFromId( $this->mRevisionId
);
4864 $revuser = $revision->getUserText();
4867 $revuser = $wgUser->getName();
4873 * Mutator for $mDefaultSort
4875 * @param $sort New value
4877 public function setDefaultSort( $sort ) {
4878 $this->mDefaultSort
= $sort;
4882 * Accessor for $mDefaultSort
4883 * Will use the title/prefixed title if none is set
4887 public function getDefaultSort() {
4888 global $wgCategoryPrefixedDefaultSortkey;
4889 if( $this->mDefaultSort
!== false ) {
4890 return $this->mDefaultSort
;
4891 } elseif ($this->mTitle
->getNamespace() == NS_CATEGORY ||
4892 !$wgCategoryPrefixedDefaultSortkey) {
4893 return $this->mTitle
->getText();
4895 return $this->mTitle
->getPrefixedText();
4900 * Accessor for $mDefaultSort
4901 * Unlike getDefaultSort(), will return false if none is set
4903 * @return string or false
4905 public function getCustomDefaultSort() {
4906 return $this->mDefaultSort
;
4910 * Try to guess the section anchor name based on a wikitext fragment
4911 * presumably extracted from a heading, for example "Header" from
4914 public function guessSectionNameFromWikiText( $text ) {
4915 # Strip out wikitext links(they break the anchor)
4916 $text = $this->stripSectionName( $text );
4917 $headline = Sanitizer
::decodeCharReferences( $text );
4919 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
4920 $headline = trim( $headline );
4921 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
4922 $replacearray = array(
4927 array_keys( $replacearray ),
4928 array_values( $replacearray ),
4933 * Strips a text string of wikitext for use in a section anchor
4935 * Accepts a text string and then removes all wikitext from the
4936 * string and leaves only the resultant text (i.e. the result of
4937 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
4938 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
4939 * to create valid section anchors by mimicing the output of the
4940 * parser when headings are parsed.
4942 * @param $text string Text string to be stripped of wikitext
4943 * for use in a Section anchor
4944 * @return Filtered text string
4946 public function stripSectionName( $text ) {
4947 # Strip internal link markup
4948 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
4949 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
4951 # Strip external link markup (FIXME: Not Tolerant to blank link text
4952 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
4953 # on how many empty links there are on the page - need to figure that out.
4954 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
4956 # Parse wikitext quotes (italics & bold)
4957 $text = $this->doQuotes($text);
4960 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
4964 function srvus( $text ) {
4965 return $this->testSrvus( $text, $this->mOutputType
);
4969 * strip/replaceVariables/unstrip for preprocessor regression testing
4971 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
4972 $this->clearState();
4973 if ( ! ( $title instanceof Title
) ) {
4974 $title = Title
::newFromText( $title );
4976 $this->mTitle
= $title;
4977 $this->mOptions
= $options;
4978 $this->setOutputType( $outputType );
4979 $text = $this->replaceVariables( $text );
4980 $text = $this->mStripState
->unstripBoth( $text );
4981 $text = Sanitizer
::removeHTMLtags( $text );
4985 function testPst( $text, $title, $options ) {
4987 if ( ! ( $title instanceof Title
) ) {
4988 $title = Title
::newFromText( $title );
4990 return $this->preSaveTransform( $text, $title, $wgUser, $options );
4993 function testPreprocess( $text, $title, $options ) {
4994 if ( ! ( $title instanceof Title
) ) {
4995 $title = Title
::newFromText( $title );
4997 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5000 function markerSkipCallback( $s, $callback ) {
5003 while ( $i < strlen( $s ) ) {
5004 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5005 if ( $markerStart === false ) {
5006 $out .= call_user_func( $callback, substr( $s, $i ) );
5009 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5010 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5011 if ( $markerEnd === false ) {
5012 $out .= substr( $s, $markerStart );
5015 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5016 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5024 function serialiseHalfParsedText( $text ) {
5026 $data['text'] = $text;
5028 // First, find all strip markers, and store their
5029 // data in an array.
5030 $stripState = new StripState
;
5032 while( ( $start_pos = strpos( $text, $this->mUniqPrefix
, $pos ) ) && ( $end_pos = strpos( $text, self
::MARKER_SUFFIX
, $pos ) ) ) {
5033 $end_pos +
= strlen( self
::MARKER_SUFFIX
);
5034 $marker = substr( $text, $start_pos, $end_pos-$start_pos );
5036 if ( !empty( $this->mStripState
->general
->data
[$marker] ) ) {
5037 $replaceArray = $stripState->general
;
5038 $stripText = $this->mStripState
->general
->data
[$marker];
5039 } elseif ( !empty( $this->mStripState
->nowiki
->data
[$marker] ) ) {
5040 $replaceArray = $stripState->nowiki
;
5041 $stripText = $this->mStripState
->nowiki
->data
[$marker];
5043 throw new MWException( "Hanging strip marker: '$marker'." );
5046 $replaceArray->setPair( $marker, $stripText );
5049 $data['stripstate'] = $stripState;
5051 // Now, find all of our links, and store THEIR
5052 // data in an array! :)
5053 $links = array( 'internal' => array(), 'interwiki' => array() );
5057 while( ( $start_pos = strpos( $text, '<!--LINK ', $pos ) ) ) {
5058 list( $ns, $trail ) = explode( ':', substr( $text, $start_pos +
strlen( '<!--LINK ' ) ), 2 );
5061 if (empty( $links['internal'][$ns] )) {
5062 $links['internal'][$ns] = array();
5065 $key = trim( substr( $trail, 0, strpos( $trail, '-->' ) ) );
5066 $links['internal'][$ns][] = $this->mLinkHolders
->internals
[$ns][$key];
5067 $pos = $start_pos +
strlen( "<!--LINK $ns:$key-->" );
5073 while( ( $start_pos = strpos( $text, '<!--IWLINK ', $pos ) ) ) {
5074 $data = substr( $text, $start_pos );
5075 $key = trim( substr( $data, 0, strpos( $data, '-->' ) ) );
5076 $links['interwiki'][] = $this->mLinkHolders
->interwiki
[$key];
5077 $pos = $start_pos +
strlen( "<!--IWLINK $key-->" );
5080 $data['linkholder'] = $links;
5085 function unserialiseHalfParsedText( $data, $intPrefix = null /* Unique identifying prefix */ ) {
5087 $intPrefix = $this->getRandomString();
5089 // First, extract the strip state.
5090 $stripState = $data['stripstate'];
5091 $this->mStripState
->general
->merge( $stripState->general
);
5092 $this->mStripState
->nowiki
->merge( $stripState->nowiki
);
5094 // Now, extract the text, and renumber links
5095 $text = $data['text'];
5096 $links = $data['linkholder'];
5099 foreach( $links['internal'] as $ns => $nsLinks ) {
5100 foreach( $nsLinks as $key => $entry ) {
5101 $newKey = $intPrefix . '-' . $key;
5102 $this->mLinkHolders
->internals
[$ns][$newKey] = $entry;
5104 $text = str_replace( "<!--LINK $ns:$key-->", "<!--LINK $ns:$newKey-->", $text );
5109 foreach( $links['interwiki'] as $key => $entry ) {
5110 $newKey = "$intPrefix-$key";
5111 $this->mLinkHolders
->interwikis
[$newKey] = $entry;
5113 $text = str_replace( "<!--IWLINK $key-->", "<!--IWLINK $newKey-->", $text );
5116 // Should be good to go.
5122 * @todo document, briefly.
5126 var $general, $nowiki;
5128 function __construct() {
5129 $this->general
= new ReplacementArray
;
5130 $this->nowiki
= new ReplacementArray
;
5133 function unstripGeneral( $text ) {
5134 wfProfileIn( __METHOD__
);
5137 $text = $this->general
->replace( $text );
5138 } while ( $text !== $oldText );
5139 wfProfileOut( __METHOD__
);
5143 function unstripNoWiki( $text ) {
5144 wfProfileIn( __METHOD__
);
5147 $text = $this->nowiki
->replace( $text );
5148 } while ( $text !== $oldText );
5149 wfProfileOut( __METHOD__
);
5153 function unstripBoth( $text ) {
5154 wfProfileIn( __METHOD__
);
5157 $text = $this->general
->replace( $text );
5158 $text = $this->nowiki
->replace( $text );
5159 } while ( $text !== $oldText );
5160 wfProfileOut( __METHOD__
);
5166 * @todo document, briefly.
5169 class OnlyIncludeReplacer
{
5172 function replace( $matches ) {
5173 if ( substr( $matches[1], -1 ) === "\n" ) {
5174 $this->output
.= substr( $matches[1], 0, -1 );
5176 $this->output
.= $matches[1];