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
30 * Removes <noinclude> sections, and <includeonly> tags.
33 * objects: $wgLang, $wgContLang
35 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
38 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
39 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
40 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
43 * * only within ParserOptions
50 * Update this version number when the ParserOutput format
51 * changes in an incompatible way, so the parser cache
52 * can automatically discard old data.
54 const VERSION
= '1.6.4';
56 # Flags for Parser::setFunctionHook
57 # Also available as global constants from Defines.php
58 const SFH_NO_HASH
= 1;
59 const SFH_OBJECT_ARGS
= 2;
61 # Constants needed for external link processing
62 # Everything except bracket, space, or control characters
63 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F]';
64 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
65 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
67 # State constants for the definition list colon extraction
68 const COLON_STATE_TEXT
= 0;
69 const COLON_STATE_TAG
= 1;
70 const COLON_STATE_TAGSTART
= 2;
71 const COLON_STATE_CLOSETAG
= 3;
72 const COLON_STATE_TAGSLASH
= 4;
73 const COLON_STATE_COMMENT
= 5;
74 const COLON_STATE_COMMENTDASH
= 6;
75 const COLON_STATE_COMMENTDASHDASH
= 7;
77 # Flags for preprocessToDom
78 const PTD_FOR_INCLUSION
= 1;
80 # Allowed values for $this->mOutputType
81 # Parameter to startExternalParse().
82 const OT_HTML
= 1; # like parse()
83 const OT_WIKI
= 2; # like preSaveTransform()
84 const OT_PREPROCESS
= 3; # like preprocess()
86 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
88 # Marker Suffix needs to be accessible staticly.
89 const MARKER_SUFFIX
= "-QINU\x7f";
92 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables;
93 var $mSubstWords, $mImageParams, $mImageParamsMagicArray, $mStripList, $mMarkerIndex;
94 var $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols, $mDefaultStripList;
95 var $mVarCache, $mConf, $mFunctionTagHooks;
98 # Cleared with clearState():
99 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
100 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
101 var $mLinkHolders, $mLinkID;
102 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
103 var $mTplExpandCache; # empty-frame expansion cache
104 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
105 var $mExpensiveFunctionCount; # number of expensive parser function calls
108 # These are variables reset at least once per parse regardless of $clearState
109 var $mOptions; # ParserOptions object
110 var $mTitle; # Title context, used for self-link rendering and similar things
111 var $mOutputType; # Output type, one of the OT_xxx constants
112 var $ot; # Shortcut alias, see setOutputType()
113 var $mRevisionId; # ID to display in {{REVISIONID}} tags
114 var $mRevisionTimestamp; # The timestamp of the specified revision ID
115 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp
122 function __construct( $conf = array() ) {
123 $this->mConf
= $conf;
124 $this->mTagHooks
= array();
125 $this->mTransparentTagHooks
= array();
126 $this->mFunctionHooks
= array();
127 $this->mFunctionTagHooks
= array();
128 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
129 $this->mDefaultStripList
= $this->mStripList
= array();
130 $this->mUrlProtocols
= wfUrlProtocols();
131 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
132 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
133 $this->mVarCache
= array();
134 if ( isset( $conf['preprocessorClass'] ) ) {
135 $this->mPreprocessorClass
= $conf['preprocessorClass'];
136 } elseif ( extension_loaded( 'domxml' ) ) {
137 # PECL extension that conflicts with the core DOM extension (bug 13770)
138 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
139 $this->mPreprocessorClass
= 'Preprocessor_Hash';
140 } elseif ( extension_loaded( 'dom' ) ) {
141 $this->mPreprocessorClass
= 'Preprocessor_DOM';
143 $this->mPreprocessorClass
= 'Preprocessor_Hash';
145 $this->mMarkerIndex
= 0;
146 $this->mFirstCall
= true;
150 * Reduce memory usage to reduce the impact of circular references
152 function __destruct() {
153 if ( isset( $this->mLinkHolders
) ) {
154 $this->mLinkHolders
->__destruct();
156 foreach ( $this as $name => $value ) {
157 unset( $this->$name );
162 * Do various kinds of initialisation on the first call of the parser
164 function firstCallInit() {
165 if ( !$this->mFirstCall
) {
168 $this->mFirstCall
= false;
170 wfProfileIn( __METHOD__
);
172 CoreParserFunctions
::register( $this );
173 CoreTagHooks
::register( $this );
174 $this->initialiseVariables();
176 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
177 wfProfileOut( __METHOD__
);
185 function clearState() {
186 wfProfileIn( __METHOD__
);
187 if ( $this->mFirstCall
) {
188 $this->firstCallInit();
190 $this->mOutput
= new ParserOutput
;
191 $this->mAutonumber
= 0;
192 $this->mLastSection
= '';
193 $this->mDTopen
= false;
194 $this->mIncludeCount
= array();
195 $this->mStripState
= new StripState
;
196 $this->mArgStack
= false;
197 $this->mInPre
= false;
198 $this->mLinkHolders
= new LinkHolderArray( $this );
200 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
201 $this->mVarCache
= array();
204 * Prefix for temporary replacement strings for the multipass parser.
205 * \x07 should never appear in input as it's disallowed in XML.
206 * Using it at the front also gives us a little extra robustness
207 * since it shouldn't match when butted up against identifier-like
210 * Must not consist of all title characters, or else it will change
211 * the behaviour of <nowiki> in a link.
213 # $this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
214 # Changed to \x7f to allow XML double-parsing -- TS
215 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
218 # Clear these on every parse, bug 4549
219 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
221 $this->mShowToc
= true;
222 $this->mForceTocPosition
= false;
223 $this->mIncludeSizes
= array(
227 $this->mPPNodeCount
= 0;
228 $this->mDefaultSort
= false;
229 $this->mHeadings
= array();
230 $this->mDoubleUnderscores
= array();
231 $this->mExpensiveFunctionCount
= 0;
234 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
235 $this->mPreprocessor
= null;
238 wfRunHooks( 'ParserClearState', array( &$this ) );
239 wfProfileOut( __METHOD__
);
242 function setOutputType( $ot ) {
243 $this->mOutputType
= $ot;
246 'html' => $ot == self
::OT_HTML
,
247 'wiki' => $ot == self
::OT_WIKI
,
248 'pre' => $ot == self
::OT_PREPROCESS
,
249 'plain' => $ot == self
::OT_PLAIN
,
254 * Set the context title
256 function setTitle( $t ) {
257 if ( !$t ||
$t instanceof FakeTitle
) {
258 $t = Title
::newFromText( 'NO TITLE' );
261 if ( strval( $t->getFragment() ) !== '' ) {
262 # Strip the fragment to avoid various odd effects
263 $this->mTitle
= clone $t;
264 $this->mTitle
->setFragment( '' );
271 * Accessor for mUniqPrefix.
275 function uniqPrefix() {
276 if ( !isset( $this->mUniqPrefix
) ) {
277 # @todo Fixme: this is probably *horribly wrong*
278 # LanguageConverter seems to want $wgParser's uniqPrefix, however
279 # if this is called for a parser cache hit, the parser may not
280 # have ever been initialized in the first place.
281 # Not really sure what the heck is supposed to be going on here.
283 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
285 return $this->mUniqPrefix
;
289 * Convert wikitext to HTML
290 * Do not call this function recursively.
292 * @param $text String: text we want to parse
293 * @param $title A title object
294 * @param $options ParserOptions
295 * @param $linestart boolean
296 * @param $clearState boolean
297 * @param $revid Int: number to pass in {{REVISIONID}}
298 * @return ParserOutput a ParserOutput
300 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
302 * First pass--just handle <nowiki> sections, pass the rest off
303 * to internalParse() which does all the real work.
306 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang, $wgDisableLangConversion;
307 $fname = __METHOD__
.'-' . wfGetCaller();
308 wfProfileIn( __METHOD__
);
309 wfProfileIn( $fname );
315 $this->mOptions
= $options;
316 $this->setTitle( $title ); # Page title has to be set for the pre-processor
318 $oldRevisionId = $this->mRevisionId
;
319 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
320 if ( $revid !== null ) {
321 $this->mRevisionId
= $revid;
322 $this->mRevisionTimestamp
= null;
324 $this->setOutputType( self
::OT_HTML
);
325 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
327 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
328 $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 convert() 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 if ( !( $wgDisableLangConversion
351 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
352 ||
$this->mTitle
->isTalkPage()
353 ||
$this->mTitle
->isConversionTable() ) ) {
354 $text = $wgContLang->convert( $text );
357 # A title may have been set in a conversion rule.
358 # Note that if a user tries to set a title in a conversion
359 # rule but content conversion was not done, then the parser
360 # won't pick it up. This is probably expected behavior.
361 if ( $wgContLang->getConvRuleTitle() ) {
362 $this->mOutput
->setTitleText( $wgContLang->getConvRuleTitle() );
365 $text = $this->mStripState
->unstripNoWiki( $text );
367 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
369 //!JF Move to its own function
371 $uniq_prefix = $this->mUniqPrefix
;
373 $elements = array_keys( $this->mTransparentTagHooks
);
374 $text = self
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
376 foreach ( $matches as $marker => $data ) {
377 list( $element, $content, $params, $tag ) = $data;
378 $tagName = strtolower( $element );
379 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
380 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
384 $this->mStripState
->general
->setPair( $marker, $output );
386 $text = $this->mStripState
->unstripGeneral( $text );
388 $text = Sanitizer
::normalizeCharReferences( $text );
390 if ( ( $wgUseTidy && $this->mOptions
->mTidy
) ||
$wgAlwaysUseTidy ) {
391 $text = MWTidy
::tidy( $text );
393 # attempt to sanitize at least some nesting problems
394 # (bug #2702 and quite a few others)
396 # ''Something [http://www.cool.com cool''] -->
397 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
398 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
399 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
400 # fix up an anchor inside another anchor, only
401 # at least for a single single nested link (bug 3695)
402 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
403 '\\1\\2</a>\\3</a>\\1\\4</a>',
404 # fix div inside inline elements- doBlockLevels won't wrap a line which
405 # contains a div, so fix it up here; replace
406 # div with escaped text
407 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
408 '\\1\\3<div\\5>\\6</div>\\8\\9',
409 # remove empty italic or bold tag pairs, some
410 # introduced by rules above
411 '/<([bi])><\/\\1>/' => '',
414 $text = preg_replace(
415 array_keys( $tidyregs ),
416 array_values( $tidyregs ),
419 global $wgExpensiveParserFunctionLimit;
420 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
421 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
424 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
426 # Information on include size limits, for the benefit of users who try to skirt them
427 if ( $this->mOptions
->getEnableLimitReport() ) {
428 $max = $this->mOptions
->getMaxIncludeSize();
429 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
431 "NewPP limit report\n" .
432 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
433 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
434 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
436 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
437 $text .= "\n<!-- \n$limitReport-->\n";
439 $this->mOutput
->setText( $text );
441 $this->mRevisionId
= $oldRevisionId;
442 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
443 wfProfileOut( $fname );
444 wfProfileOut( __METHOD__
);
446 return $this->mOutput
;
450 * Recursive parser entry point that can be called from an extension tag
453 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
455 * @param $text String: text extension wants to have parsed
456 * @param PPFrame $frame: The frame to use for expanding any template variables
458 function recursiveTagParse( $text, $frame=false ) {
459 wfProfileIn( __METHOD__
);
460 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
461 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
462 $text = $this->internalParse( $text, false, $frame );
463 wfProfileOut( __METHOD__
);
468 * Expand templates and variables in the text, producing valid, static wikitext.
469 * Also removes comments.
471 function preprocess( $text, $title, $options, $revid = null ) {
472 wfProfileIn( __METHOD__
);
474 $this->setOutputType( self
::OT_PREPROCESS
);
475 $this->mOptions
= $options;
476 $this->setTitle( $title );
477 if ( $revid !== null ) {
478 $this->mRevisionId
= $revid;
480 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
481 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
482 $text = $this->replaceVariables( $text );
483 $text = $this->mStripState
->unstripBoth( $text );
484 wfProfileOut( __METHOD__
);
489 * Process the wikitext for the ?preload= feature. (bug 5210)
491 * <noinclude>, <includeonly> etc. are parsed as for template transclusion,
492 * comments, templates, arguments, tags hooks and parser functions are untouched.
494 public function getPreloadText( $text, $title, $options ) {
495 # Parser (re)initialisation
497 $this->setOutputType( self
::OT_PLAIN
);
498 $this->mOptions
= $options;
499 $this->setTitle( $title );
501 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
502 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
503 return $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
507 * Get a random string
512 function getRandomString() {
513 return dechex( mt_rand( 0, 0x7fffffff ) ) . dechex( mt_rand( 0, 0x7fffffff ) );
516 function &getTitle() { return $this->mTitle
; }
517 function getOptions() { return $this->mOptions
; }
518 function getRevisionId() { return $this->mRevisionId
; }
519 function getOutput() { return $this->mOutput
; }
520 function nextLinkID() { return $this->mLinkID++
; }
522 function getFunctionLang() {
523 global $wgLang, $wgContLang;
525 $target = $this->mOptions
->getTargetLanguage();
526 if ( $target !== null ) {
529 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
534 * Get a preprocessor object
536 function getPreprocessor() {
537 if ( !isset( $this->mPreprocessor
) ) {
538 $class = $this->mPreprocessorClass
;
539 $this->mPreprocessor
= new $class( $this );
541 return $this->mPreprocessor
;
545 * Replaces all occurrences of HTML-style comments and the given tags
546 * in the text with a random marker and returns the next text. The output
547 * parameter $matches will be an associative array filled with data in
549 * 'UNIQ-xxxxx' => array(
552 * array( 'param' => 'x' ),
553 * '<element param="x">tag content</element>' ) )
555 * @param $elements list of element names. Comments are always extracted.
556 * @param $text Source text string.
557 * @param $uniq_prefix
562 function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
567 $taglist = implode( '|', $elements );
568 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
570 while ( $text != '' ) {
571 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
573 if ( count( $p ) < 5 ) {
576 if ( count( $p ) > 5 ) {
590 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
591 $stripped .= $marker;
593 if ( $close === '/>' ) {
594 # Empty element tag, <tag />
599 if ( $element === '!--' ) {
602 $end = "/(<\\/$element\\s*>)/i";
604 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
606 if ( count( $q ) < 3 ) {
607 # No end tag -- let it run out to the end of the text.
616 $matches[$marker] = array( $element,
618 Sanitizer
::decodeTagAttributes( $attributes ),
619 "<$element$attributes$close$content$tail" );
625 * Get a list of strippable XML-like elements
627 function getStripList() {
628 return $this->mStripList
;
632 * @deprecated use replaceVariables
634 function strip( $text, $state, $stripcomments = false , $dontstrip = array() ) {
639 * Restores pre, math, and other extensions removed by strip()
641 * always call unstripNoWiki() after this one
643 * @deprecated use $this->mStripState->unstrip()
645 function unstrip( $text, $state ) {
646 return $state->unstripGeneral( $text );
650 * Always call this after unstrip() to preserve the order
653 * @deprecated use $this->mStripState->unstrip()
655 function unstripNoWiki( $text, $state ) {
656 return $state->unstripNoWiki( $text );
660 * @deprecated use $this->mStripState->unstripBoth()
662 function unstripForHTML( $text ) {
663 return $this->mStripState
->unstripBoth( $text );
667 * Add an item to the strip state
668 * Returns the unique tag which must be inserted into the stripped text
669 * The tag will be replaced with the original text in unstrip()
673 function insertStripItem( $text ) {
674 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
675 $this->mMarkerIndex++
;
676 $this->mStripState
->general
->setPair( $rnd, $text );
681 * Interface with html tidy
682 * @deprecated Use MWTidy::tidy()
684 public static function tidy( $text ) {
685 wfDeprecated( __METHOD__
);
686 return MWTidy
::tidy( $text );
690 * parse the wiki syntax used to render tables
694 function doTableStuff( $text ) {
695 wfProfileIn( __METHOD__
);
697 $lines = StringUtils
::explode( "\n", $text );
699 $td_history = array(); # Is currently a td tag open?
700 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
701 $tr_history = array(); # Is currently a tr tag open?
702 $tr_attributes = array(); # history of tr attributes
703 $has_opened_tr = array(); # Did this table open a <tr> element?
704 $indent_level = 0; # indent level of the table
706 foreach ( $lines as $outLine ) {
707 $line = trim( $outLine );
709 if ( $line == '' ) { # empty line, go to next line
710 $out .= $outLine."\n";
713 $first_character = $line[0];
716 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
717 # First check if we are starting a new table
718 $indent_level = strlen( $matches[1] );
720 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
721 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
723 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
724 array_push( $td_history , false );
725 array_push( $last_tag_history , '' );
726 array_push( $tr_history , false );
727 array_push( $tr_attributes , '' );
728 array_push( $has_opened_tr , false );
729 } elseif ( count( $td_history ) == 0 ) {
730 # Don't do any of the following
731 $out .= $outLine."\n";
733 } elseif ( substr( $line , 0 , 2 ) === '|}' ) {
734 # We are ending a table
735 $line = '</table>' . substr( $line , 2 );
736 $last_tag = array_pop( $last_tag_history );
738 if ( !array_pop( $has_opened_tr ) ) {
739 $line = "<tr><td></td></tr>{$line}";
742 if ( array_pop( $tr_history ) ) {
743 $line = "</tr>{$line}";
746 if ( array_pop( $td_history ) ) {
747 $line = "</{$last_tag}>{$line}";
749 array_pop( $tr_attributes );
750 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
751 } elseif ( substr( $line , 0 , 2 ) === '|-' ) {
752 # Now we have a table row
753 $line = preg_replace( '#^\|-+#', '', $line );
755 # Whats after the tag is now only attributes
756 $attributes = $this->mStripState
->unstripBoth( $line );
757 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
758 array_pop( $tr_attributes );
759 array_push( $tr_attributes, $attributes );
762 $last_tag = array_pop( $last_tag_history );
763 array_pop( $has_opened_tr );
764 array_push( $has_opened_tr , true );
766 if ( array_pop( $tr_history ) ) {
770 if ( array_pop( $td_history ) ) {
771 $line = "</{$last_tag}>{$line}";
775 array_push( $tr_history , false );
776 array_push( $td_history , false );
777 array_push( $last_tag_history , '' );
778 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line , 0 , 2 ) === '|+' ) {
779 # This might be cell elements, td, th or captions
780 if ( substr( $line , 0 , 2 ) === '|+' ) {
781 $first_character = '+';
782 $line = substr( $line , 1 );
785 $line = substr( $line , 1 );
787 if ( $first_character === '!' ) {
788 $line = str_replace( '!!' , '||' , $line );
791 # Split up multiple cells on the same line.
792 # FIXME : This can result in improper nesting of tags processed
793 # by earlier parser steps, but should avoid splitting up eg
794 # attribute values containing literal "||".
795 $cells = StringUtils
::explodeMarkup( '||' , $line );
799 # Loop through each table cell
800 foreach ( $cells as $cell ) {
802 if ( $first_character !== '+' ) {
803 $tr_after = array_pop( $tr_attributes );
804 if ( !array_pop( $tr_history ) ) {
805 $previous = "<tr{$tr_after}>\n";
807 array_push( $tr_history , true );
808 array_push( $tr_attributes , '' );
809 array_pop( $has_opened_tr );
810 array_push( $has_opened_tr , true );
813 $last_tag = array_pop( $last_tag_history );
815 if ( array_pop( $td_history ) ) {
816 $previous = "</{$last_tag}>{$previous}";
819 if ( $first_character === '|' ) {
821 } elseif ( $first_character === '!' ) {
823 } elseif ( $first_character === '+' ) {
824 $last_tag = 'caption';
829 array_push( $last_tag_history , $last_tag );
831 # A cell could contain both parameters and data
832 $cell_data = explode( '|' , $cell , 2 );
834 # Bug 553: Note that a '|' inside an invalid link should not
835 # be mistaken as delimiting cell parameters
836 if ( strpos( $cell_data[0], '[[' ) !== false ) {
837 $cell = "{$previous}<{$last_tag}>{$cell}";
838 } elseif ( count( $cell_data ) == 1 ) {
839 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
841 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
842 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
843 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
847 array_push( $td_history , true );
850 $out .= $outLine . "\n";
853 # Closing open td, tr && table
854 while ( count( $td_history ) > 0 ) {
855 if ( array_pop( $td_history ) ) {
858 if ( array_pop( $tr_history ) ) {
861 if ( !array_pop( $has_opened_tr ) ) {
862 $out .= "<tr><td></td></tr>\n" ;
865 $out .= "</table>\n";
868 # Remove trailing line-ending (b/c)
869 if ( substr( $out, -1 ) === "\n" ) {
870 $out = substr( $out, 0, -1 );
873 # special case: don't return empty table
874 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
878 wfProfileOut( __METHOD__
);
884 * Helper function for parse() that transforms wiki markup into
885 * HTML. Only called for $mOutputType == self::OT_HTML.
889 function internalParse( $text, $isMain = true, $frame=false ) {
890 wfProfileIn( __METHOD__
);
894 # Hook to suspend the parser in this state
895 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
896 wfProfileOut( __METHOD__
);
900 # if $frame is provided, then use $frame for replacing any variables
902 # use frame depth to infer how include/noinclude tags should be handled
903 # depth=0 means this is the top-level document; otherwise it's an included document
904 if ( !$frame->depth
) {
907 $flag = Parser
::PTD_FOR_INCLUSION
;
908 $dom = $this->preprocessToDom( $text, $flag );
909 $text = $frame->expand( $dom );
912 # if $frame is not provided, then use old-style replaceVariables
913 $text = $this->replaceVariables( $text );
916 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
917 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
919 # Tables need to come after variable replacement for things to work
920 # properly; putting them before other transformations should keep
921 # exciting things like link expansions from showing up in surprising
923 $text = $this->doTableStuff( $text );
925 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
927 $text = $this->doDoubleUnderscore( $text );
929 $text = $this->doHeadings( $text );
930 if ( $this->mOptions
->getUseDynamicDates() ) {
931 $df = DateFormatter
::getInstance();
932 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
934 $text = $this->doAllQuotes( $text );
935 $text = $this->replaceInternalLinks( $text );
936 $text = $this->replaceExternalLinks( $text );
938 # replaceInternalLinks may sometimes leave behind
939 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
940 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
942 $text = $this->doMagicLinks( $text );
943 $text = $this->formatHeadings( $text, $origText, $isMain );
945 wfProfileOut( __METHOD__
);
950 * Replace special strings like "ISBN xxx" and "RFC xxx" with
951 * magic external links.
956 function doMagicLinks( $text ) {
957 wfProfileIn( __METHOD__
);
958 $prots = $this->mUrlProtocols
;
959 $urlChar = self
::EXT_LINK_URL_CLASS
;
960 $text = preg_replace_callback(
962 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
963 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
964 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
965 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
966 ISBN\s+(\b # m[5]: ISBN, capture number
967 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
968 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
969 [0-9Xx] # check digit
971 )!x', array( &$this, 'magicLinkCallback' ), $text );
972 wfProfileOut( __METHOD__
);
976 function magicLinkCallback( $m ) {
977 if ( isset( $m[1] ) && $m[1] !== '' ) {
980 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
983 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
985 return $this->makeFreeExternalLink( $m[0] );
986 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
989 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
992 $CssClass = 'mw-magiclink-rfc';
994 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
996 $urlmsg = 'pubmedurl';
997 $CssClass = 'mw-magiclink-pmid';
1000 throw new MWException( __METHOD__
.': unrecognised match type "' .
1001 substr( $m[0], 0, 20 ) . '"' );
1003 $url = wfMsg( $urlmsg, $id);
1004 $sk = $this->mOptions
->getSkin();
1005 $la = $sk->getExternalLinkAttributes( "external $CssClass" );
1006 return "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1007 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1010 $num = strtr( $isbn, array(
1015 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1017 $titleObj->escapeLocalUrl() .
1018 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1025 * Make a free external link, given a user-supplied URL
1029 function makeFreeExternalLink( $url ) {
1031 wfProfileIn( __METHOD__
);
1033 $sk = $this->mOptions
->getSkin();
1036 # The characters '<' and '>' (which were escaped by
1037 # removeHTMLtags()) should not be included in
1038 # URLs, per RFC 2396.
1040 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1041 $trail = substr( $url, $m2[0][1] ) . $trail;
1042 $url = substr( $url, 0, $m2[0][1] );
1045 # Move trailing punctuation to $trail
1047 # If there is no left bracket, then consider right brackets fair game too
1048 if ( strpos( $url, '(' ) === false ) {
1052 $numSepChars = strspn( strrev( $url ), $sep );
1053 if ( $numSepChars ) {
1054 $trail = substr( $url, -$numSepChars ) . $trail;
1055 $url = substr( $url, 0, -$numSepChars );
1058 $url = Sanitizer
::cleanUrl( $url );
1060 # Is this an external image?
1061 $text = $this->maybeMakeExternalImage( $url );
1062 if ( $text === false ) {
1063 # Not an image, make a link
1064 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1065 $this->getExternalLinkAttribs( $url ) );
1066 # Register it in the output object...
1067 # Replace unnecessary URL escape codes with their equivalent characters
1068 $pasteurized = self
::replaceUnusualEscapes( $url );
1069 $this->mOutput
->addExternalLink( $pasteurized );
1071 wfProfileOut( __METHOD__
);
1072 return $text . $trail;
1077 * Parse headers and return html
1081 function doHeadings( $text ) {
1082 wfProfileIn( __METHOD__
);
1083 for ( $i = 6; $i >= 1; --$i ) {
1084 $h = str_repeat( '=', $i );
1085 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1086 "<h$i>\\1</h$i>", $text );
1088 wfProfileOut( __METHOD__
);
1093 * Replace single quotes with HTML markup
1095 * @return string the altered text
1097 function doAllQuotes( $text ) {
1098 wfProfileIn( __METHOD__
);
1100 $lines = StringUtils
::explode( "\n", $text );
1101 foreach ( $lines as $line ) {
1102 $outtext .= $this->doQuotes( $line ) . "\n";
1104 $outtext = substr( $outtext, 0,-1 );
1105 wfProfileOut( __METHOD__
);
1110 * Helper function for doAllQuotes()
1112 public function doQuotes( $text ) {
1113 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1114 if ( count( $arr ) == 1 ) {
1117 # First, do some preliminary work. This may shift some apostrophes from
1118 # being mark-up to being text. It also counts the number of occurrences
1119 # of bold and italics mark-ups.
1123 foreach ( $arr as $r ) {
1124 if ( ( $i %
2 ) == 1 ) {
1125 # If there are ever four apostrophes, assume the first is supposed to
1126 # be text, and the remaining three constitute mark-up for bold text.
1127 if ( strlen( $arr[$i] ) == 4 ) {
1130 } elseif ( strlen( $arr[$i] ) > 5 ) {
1131 # If there are more than 5 apostrophes in a row, assume they're all
1132 # text except for the last 5.
1133 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1136 # Count the number of occurrences of bold and italics mark-ups.
1137 # We are not counting sequences of five apostrophes.
1138 if ( strlen( $arr[$i] ) == 2 ) {
1140 } elseif ( strlen( $arr[$i] ) == 3 ) {
1142 } elseif ( strlen( $arr[$i] ) == 5 ) {
1150 # If there is an odd number of both bold and italics, it is likely
1151 # that one of the bold ones was meant to be an apostrophe followed
1152 # by italics. Which one we cannot know for certain, but it is more
1153 # likely to be one that has a single-letter word before it.
1154 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1156 $firstsingleletterword = -1;
1157 $firstmultiletterword = -1;
1159 foreach ( $arr as $r ) {
1160 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1161 $x1 = substr( $arr[$i-1], -1 );
1162 $x2 = substr( $arr[$i-1], -2, 1 );
1163 if ( $x1 === ' ' ) {
1164 if ( $firstspace == -1 ) {
1167 } elseif ( $x2 === ' ') {
1168 if ( $firstsingleletterword == -1 ) {
1169 $firstsingleletterword = $i;
1172 if ( $firstmultiletterword == -1 ) {
1173 $firstmultiletterword = $i;
1180 # If there is a single-letter word, use it!
1181 if ( $firstsingleletterword > -1 ) {
1182 $arr[$firstsingleletterword] = "''";
1183 $arr[$firstsingleletterword-1] .= "'";
1184 } elseif ( $firstmultiletterword > -1 ) {
1185 # If not, but there's a multi-letter word, use that one.
1186 $arr[$firstmultiletterword] = "''";
1187 $arr[$firstmultiletterword-1] .= "'";
1188 } elseif ( $firstspace > -1 ) {
1189 # ... otherwise use the first one that has neither.
1190 # (notice that it is possible for all three to be -1 if, for example,
1191 # there is only one pentuple-apostrophe in the line)
1192 $arr[$firstspace] = "''";
1193 $arr[$firstspace-1] .= "'";
1197 # Now let's actually convert our apostrophic mush to HTML!
1202 foreach ( $arr as $r ) {
1203 if ( ( $i %
2 ) == 0 ) {
1204 if ( $state === 'both' ) {
1210 if ( strlen( $r ) == 2 ) {
1211 if ( $state === 'i' ) {
1212 $output .= '</i>'; $state = '';
1213 } elseif ( $state === 'bi' ) {
1214 $output .= '</i>'; $state = 'b';
1215 } elseif ( $state === 'ib' ) {
1216 $output .= '</b></i><b>'; $state = 'b';
1217 } elseif ( $state === 'both' ) {
1218 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1219 } else { # $state can be 'b' or ''
1220 $output .= '<i>'; $state .= 'i';
1222 } elseif ( strlen( $r ) == 3 ) {
1223 if ( $state === 'b' ) {
1224 $output .= '</b>'; $state = '';
1225 } elseif ( $state === 'bi' ) {
1226 $output .= '</i></b><i>'; $state = 'i';
1227 } elseif ( $state === 'ib' ) {
1228 $output .= '</b>'; $state = 'i';
1229 } elseif ( $state === 'both' ) {
1230 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1231 } else { # $state can be 'i' or ''
1232 $output .= '<b>'; $state .= 'b';
1234 } elseif ( strlen( $r ) == 5 ) {
1235 if ( $state === 'b' ) {
1236 $output .= '</b><i>'; $state = 'i';
1237 } elseif ( $state === 'i' ) {
1238 $output .= '</i><b>'; $state = 'b';
1239 } elseif ( $state === 'bi' ) {
1240 $output .= '</i></b>'; $state = '';
1241 } elseif ( $state === 'ib' ) {
1242 $output .= '</b></i>'; $state = '';
1243 } elseif ( $state === 'both' ) {
1244 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1245 } else { # ($state == '')
1246 $buffer = ''; $state = 'both';
1252 # Now close all remaining tags. Notice that the order is important.
1253 if ( $state === 'b' ||
$state === 'ib' ) {
1256 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1259 if ( $state === 'bi' ) {
1262 # There might be lonely ''''', so make sure we have a buffer
1263 if ( $state === 'both' && $buffer ) {
1264 $output .= '<b><i>'.$buffer.'</i></b>';
1271 * Replace external links (REL)
1273 * Note: this is all very hackish and the order of execution matters a lot.
1274 * Make sure to run maintenance/parserTests.php if you change this code.
1278 function replaceExternalLinks( $text ) {
1280 wfProfileIn( __METHOD__
);
1282 $sk = $this->mOptions
->getSkin();
1284 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1285 $s = array_shift( $bits );
1288 while ( $i<count( $bits ) ) {
1290 $protocol = $bits[$i++
];
1291 $text = $bits[$i++
];
1292 $trail = $bits[$i++
];
1294 # The characters '<' and '>' (which were escaped by
1295 # removeHTMLtags()) should not be included in
1296 # URLs, per RFC 2396.
1298 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1299 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1300 $url = substr( $url, 0, $m2[0][1] );
1303 # If the link text is an image URL, replace it with an <img> tag
1304 # This happened by accident in the original parser, but some people used it extensively
1305 $img = $this->maybeMakeExternalImage( $text );
1306 if ( $img !== false ) {
1312 # Set linktype for CSS - if URL==text, link is essentially free
1313 $linktype = ( $text === $url ) ?
'free' : 'text';
1315 # No link text, e.g. [http://domain.tld/some.link]
1316 if ( $text == '' ) {
1317 # Autonumber if allowed. See bug #5918
1318 if ( strpos( wfUrlProtocols(), substr( $protocol, 0, strpos( $protocol, ':' ) ) ) !== false ) {
1319 $langObj = $this->getFunctionLang();
1320 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1321 $linktype = 'autonumber';
1323 # Otherwise just use the URL
1324 $text = htmlspecialchars( $url );
1328 # Have link text, e.g. [http://domain.tld/some.link text]s
1330 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1333 $text = $wgContLang->markNoConversion( $text );
1335 $url = Sanitizer
::cleanUrl( $url );
1337 # Use the encoded URL
1338 # This means that users can paste URLs directly into the text
1339 # Funny characters like ö aren't valid in URLs anyway
1340 # This was changed in August 2004
1341 $s .= $sk->makeExternalLink( $url, $text, false, $linktype,
1342 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1344 # Register link in the output object.
1345 # Replace unnecessary URL escape codes with the referenced character
1346 # This prevents spammers from hiding links from the filters
1347 $pasteurized = self
::replaceUnusualEscapes( $url );
1348 $this->mOutput
->addExternalLink( $pasteurized );
1351 wfProfileOut( __METHOD__
);
1356 * Get an associative array of additional HTML attributes appropriate for a
1357 * particular external link. This currently may include rel => nofollow
1358 * (depending on configuration, namespace, and the URL's domain) and/or a
1359 * target attribute (depending on configuration).
1361 * @param string $url Optional URL, to extract the domain from for rel =>
1362 * nofollow if appropriate
1363 * @return array Associative array of HTML attributes
1365 function getExternalLinkAttribs( $url = false ) {
1367 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1368 $ns = $this->mTitle
->getNamespace();
1369 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) ) {
1370 $attribs['rel'] = 'nofollow';
1372 global $wgNoFollowDomainExceptions;
1373 if ( $wgNoFollowDomainExceptions ) {
1374 $bits = wfParseUrl( $url );
1375 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1376 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1377 if ( substr( $bits['host'], -strlen( $domain ) ) == $domain ) {
1378 unset( $attribs['rel'] );
1385 if ( $this->mOptions
->getExternalLinkTarget() ) {
1386 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1393 * Replace unusual URL escape codes with their equivalent characters
1397 * @todo This can merge genuinely required bits in the path or query string,
1398 * breaking legit URLs. A proper fix would treat the various parts of
1399 * the URL differently; as a workaround, just use the output for
1400 * statistical records, not for actual linking/output.
1402 static function replaceUnusualEscapes( $url ) {
1403 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1404 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1408 * Callback function used in replaceUnusualEscapes().
1409 * Replaces unusual URL escape codes with their equivalent character
1413 private static function replaceUnusualEscapesCallback( $matches ) {
1414 $char = urldecode( $matches[0] );
1415 $ord = ord( $char );
1416 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1417 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1418 # No, shouldn't be escaped
1421 # Yes, leave it escaped
1427 * make an image if it's allowed, either through the global
1428 * option, through the exception, or through the on-wiki whitelist
1431 function maybeMakeExternalImage( $url ) {
1432 $sk = $this->mOptions
->getSkin();
1433 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1434 $imagesexception = !empty( $imagesfrom );
1436 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1437 if ( $imagesexception && is_array( $imagesfrom ) ) {
1438 $imagematch = false;
1439 foreach ( $imagesfrom as $match ) {
1440 if ( strpos( $url, $match ) === 0 ) {
1445 } elseif ( $imagesexception ) {
1446 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1448 $imagematch = false;
1450 if ( $this->mOptions
->getAllowExternalImages()
1451 ||
( $imagesexception && $imagematch ) ) {
1452 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1454 $text = $sk->makeExternalImage( $url );
1457 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1458 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1459 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1460 foreach ( $whitelist as $entry ) {
1461 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1462 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1465 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1466 # Image matches a whitelist entry
1467 $text = $sk->makeExternalImage( $url );
1476 * Process [[ ]] wikilinks
1477 * @return processed text
1481 function replaceInternalLinks( $s ) {
1482 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1487 * Process [[ ]] wikilinks (RIL)
1488 * @return LinkHolderArray
1492 function replaceInternalLinks2( &$s ) {
1495 wfProfileIn( __METHOD__
);
1497 wfProfileIn( __METHOD__
.'-setup' );
1498 static $tc = FALSE, $e1, $e1_img;
1499 # the % is needed to support urlencoded titles as well
1501 $tc = Title
::legalChars() . '#%';
1502 # Match a link having the form [[namespace:link|alternate]]trail
1503 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1504 # Match cases where there is no "]]", which might still be images
1505 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1508 $sk = $this->mOptions
->getSkin();
1509 $holders = new LinkHolderArray( $this );
1511 # split the entire text string on occurences of [[
1512 $a = StringUtils
::explode( '[[', ' ' . $s );
1513 # get the first element (all text up to first [[), and remove the space we added
1516 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1517 $s = substr( $s, 1 );
1519 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1521 if ( $useLinkPrefixExtension ) {
1522 # Match the end of a line for a word that's not followed by whitespace,
1523 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1524 $e2 = wfMsgForContent( 'linkprefix' );
1527 if ( is_null( $this->mTitle
) ) {
1528 wfProfileOut( __METHOD__
.'-setup' );
1529 wfProfileOut( __METHOD__
);
1530 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1532 $nottalk = !$this->mTitle
->isTalkPage();
1534 if ( $useLinkPrefixExtension ) {
1536 if ( preg_match( $e2, $s, $m ) ) {
1537 $first_prefix = $m[2];
1539 $first_prefix = false;
1545 if ( $wgContLang->hasVariants() ) {
1546 $selflink = $wgContLang->convertLinkToAllVariants( $this->mTitle
->getPrefixedText() );
1548 $selflink = array( $this->mTitle
->getPrefixedText() );
1550 $useSubpages = $this->areSubpagesAllowed();
1551 wfProfileOut( __METHOD__
.'-setup' );
1553 # Loop for each link
1554 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1555 # Check for excessive memory usage
1556 if ( $holders->isBig() ) {
1558 # Do the existence check, replace the link holders and clear the array
1559 $holders->replace( $s );
1563 if ( $useLinkPrefixExtension ) {
1564 wfProfileIn( __METHOD__
.'-prefixhandling' );
1565 if ( preg_match( $e2, $s, $m ) ) {
1572 if ( $first_prefix ) {
1573 $prefix = $first_prefix;
1574 $first_prefix = false;
1576 wfProfileOut( __METHOD__
.'-prefixhandling' );
1579 $might_be_img = false;
1581 wfProfileIn( __METHOD__
."-e1" );
1582 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1584 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1585 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1586 # the real problem is with the $e1 regex
1589 # Still some problems for cases where the ] is meant to be outside punctuation,
1590 # and no image is in sight. See bug 2095.
1592 if ( $text !== '' &&
1593 substr( $m[3], 0, 1 ) === ']' &&
1594 strpos( $text, '[' ) !== false
1597 $text .= ']'; # so that replaceExternalLinks($text) works later
1598 $m[3] = substr( $m[3], 1 );
1600 # fix up urlencoded title texts
1601 if ( strpos( $m[1], '%' ) !== false ) {
1602 # Should anchors '#' also be rejected?
1603 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode( $m[1] ) );
1606 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1607 $might_be_img = true;
1609 if ( strpos( $m[1], '%' ) !== false ) {
1610 $m[1] = urldecode( $m[1] );
1613 } else { # Invalid form; output directly
1614 $s .= $prefix . '[[' . $line ;
1615 wfProfileOut( __METHOD__
."-e1" );
1618 wfProfileOut( __METHOD__
."-e1" );
1619 wfProfileIn( __METHOD__
."-misc" );
1621 # Don't allow internal links to pages containing
1622 # PROTO: where PROTO is a valid URL protocol; these
1623 # should be external links.
1624 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1625 $s .= $prefix . '[[' . $line ;
1626 wfProfileOut( __METHOD__
."-misc" );
1630 # Make subpage if necessary
1631 if ( $useSubpages ) {
1632 $link = $this->maybeDoSubpageLink( $m[1], $text );
1637 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1639 # Strip off leading ':'
1640 $link = substr( $link, 1 );
1643 wfProfileOut( __METHOD__
."-misc" );
1644 wfProfileIn( __METHOD__
."-title" );
1645 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1646 if ( $nt === null ) {
1647 $s .= $prefix . '[[' . $line;
1648 wfProfileOut( __METHOD__
."-title" );
1652 $ns = $nt->getNamespace();
1653 $iw = $nt->getInterWiki();
1654 wfProfileOut( __METHOD__
."-title" );
1656 if ( $might_be_img ) { # if this is actually an invalid link
1657 wfProfileIn( __METHOD__
."-might_be_img" );
1658 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1661 # look at the next 'line' to see if we can close it there
1663 $next_line = $a->current();
1664 if ( $next_line === false ||
$next_line === null ) {
1667 $m = explode( ']]', $next_line, 3 );
1668 if ( count( $m ) == 3 ) {
1669 # the first ]] closes the inner link, the second the image
1671 $text .= "[[{$m[0]}]]{$m[1]}";
1674 } elseif ( count( $m ) == 2 ) {
1675 # if there's exactly one ]] that's fine, we'll keep looking
1676 $text .= "[[{$m[0]}]]{$m[1]}";
1678 # if $next_line is invalid too, we need look no further
1679 $text .= '[[' . $next_line;
1684 # we couldn't find the end of this imageLink, so output it raw
1685 # but don't ignore what might be perfectly normal links in the text we've examined
1686 $holders->merge( $this->replaceInternalLinks2( $text ) );
1687 $s .= "{$prefix}[[$link|$text";
1688 # note: no $trail, because without an end, there *is* no trail
1689 wfProfileOut( __METHOD__
."-might_be_img" );
1692 } else { # it's not an image, so output it raw
1693 $s .= "{$prefix}[[$link|$text";
1694 # note: no $trail, because without an end, there *is* no trail
1695 wfProfileOut( __METHOD__
."-might_be_img" );
1698 wfProfileOut( __METHOD__
."-might_be_img" );
1701 $wasblank = ( $text == '' );
1706 # Link not escaped by : , create the various objects
1710 wfProfileIn( __METHOD__
."-interwiki" );
1711 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1712 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1713 $s = rtrim( $s . $prefix );
1714 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1715 wfProfileOut( __METHOD__
."-interwiki" );
1718 wfProfileOut( __METHOD__
."-interwiki" );
1720 if ( $ns == NS_FILE
) {
1721 wfProfileIn( __METHOD__
."-image" );
1722 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1724 # if no parameters were passed, $text
1725 # becomes something like "File:Foo.png",
1726 # which we don't want to pass on to the
1730 # recursively parse links inside the image caption
1731 # actually, this will parse them in any other parameters, too,
1732 # but it might be hard to fix that, and it doesn't matter ATM
1733 $text = $this->replaceExternalLinks( $text );
1734 $holders->merge( $this->replaceInternalLinks2( $text ) );
1736 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1737 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1739 $s .= $prefix . $trail;
1741 $this->mOutput
->addImage( $nt->getDBkey() );
1742 wfProfileOut( __METHOD__
."-image" );
1747 if ( $ns == NS_CATEGORY
) {
1748 wfProfileIn( __METHOD__
."-category" );
1749 $s = rtrim( $s . "\n" ); # bug 87
1752 $sortkey = $this->getDefaultSort();
1756 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1757 $sortkey = str_replace( "\n", '', $sortkey );
1758 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1759 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1762 * Strip the whitespace Category links produce, see bug 87
1763 * @todo We might want to use trim($tmp, "\n") here.
1765 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'': $prefix . $trail;
1767 wfProfileOut( __METHOD__
."-category" );
1772 # Self-link checking
1773 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1774 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1775 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1780 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1781 # FIXME: Should do batch file existence checks, see comment below
1782 if ( $ns == NS_MEDIA
) {
1783 wfProfileIn( __METHOD__
."-media" );
1784 # Give extensions a chance to select the file revision for us
1785 $skip = $time = false;
1786 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1788 $link = $sk->link( $nt );
1790 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1792 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1793 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1794 $this->mOutput
->addImage( $nt->getDBkey() );
1795 wfProfileOut( __METHOD__
."-media" );
1799 wfProfileIn( __METHOD__
."-always_known" );
1800 # Some titles, such as valid special pages or files in foreign repos, should
1801 # be shown as bluelinks even though they're not included in the page table
1803 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1804 # batch file existence checks for NS_FILE and NS_MEDIA
1805 if ( $iw == '' && $nt->isAlwaysKnown() ) {
1806 $this->mOutput
->addLink( $nt );
1807 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1809 # Links will be added to the output link list after checking
1810 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1812 wfProfileOut( __METHOD__
."-always_known" );
1814 wfProfileOut( __METHOD__
);
1819 * Make a link placeholder. The text returned can be later resolved to a real link with
1820 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1821 * parsing of interwiki links, and secondly to allow all existence checks and
1822 * article length checks (for stub links) to be bundled into a single query.
1826 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1827 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1831 * Render a forced-blue link inline; protect against double expansion of
1832 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1833 * Since this little disaster has to split off the trail text to avoid
1834 * breaking URLs in the following text without breaking trails on the
1835 * wiki links, it's been made into a horrible function.
1838 * @param string $text
1839 * @param string $query
1840 * @param string $trail
1841 * @param string $prefix
1842 * @return string HTML-wikitext mix oh yuck
1844 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1845 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1846 $sk = $this->mOptions
->getSkin();
1847 # FIXME: use link() instead of deprecated makeKnownLinkObj()
1848 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1849 return $this->armorLinks( $link ) . $trail;
1853 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1854 * going to go through further parsing steps before inline URL expansion.
1856 * Not needed quite as much as it used to be since free links are a bit
1857 * more sensible these days. But bracketed links are still an issue.
1859 * @param string more-or-less HTML
1860 * @return string less-or-more HTML with NOPARSE bits
1862 function armorLinks( $text ) {
1863 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1864 "{$this->mUniqPrefix}NOPARSE$1", $text );
1868 * Return true if subpage links should be expanded on this page.
1871 function areSubpagesAllowed() {
1872 # Some namespaces don't allow subpages
1873 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
1877 * Handle link to subpage if necessary
1878 * @param string $target the source of the link
1879 * @param string &$text the link text, modified as necessary
1880 * @return string the full name of the link
1883 function maybeDoSubpageLink( $target, &$text ) {
1884 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
1888 * Used by doBlockLevels()
1891 function closeParagraph() {
1893 if ( $this->mLastSection
!= '' ) {
1894 $result = '</' . $this->mLastSection
. ">\n";
1896 $this->mInPre
= false;
1897 $this->mLastSection
= '';
1901 * getCommon() returns the length of the longest common substring
1902 * of both arguments, starting at the beginning of both.
1905 function getCommon( $st1, $st2 ) {
1906 $fl = strlen( $st1 );
1907 $shorter = strlen( $st2 );
1908 if ( $fl < $shorter ) {
1912 for ( $i = 0; $i < $shorter; ++
$i ) {
1913 if ( $st1{$i} != $st2{$i} ) {
1920 * These next three functions open, continue, and close the list
1921 * element appropriate to the prefix character passed into them.
1924 function openList( $char ) {
1925 $result = $this->closeParagraph();
1927 if ( '*' === $char ) {
1928 $result .= '<ul><li>';
1929 } elseif ( '#' === $char ) {
1930 $result .= '<ol><li>';
1931 } elseif ( ':' === $char ) {
1932 $result .= '<dl><dd>';
1933 } elseif ( ';' === $char ) {
1934 $result .= '<dl><dt>';
1935 $this->mDTopen
= true;
1937 $result = '<!-- ERR 1 -->';
1945 * @param $char String
1948 function nextItem( $char ) {
1949 if ( '*' === $char ||
'#' === $char ) {
1951 } elseif ( ':' === $char ||
';' === $char ) {
1953 if ( $this->mDTopen
) {
1956 if ( ';' === $char ) {
1957 $this->mDTopen
= true;
1958 return $close . '<dt>';
1960 $this->mDTopen
= false;
1961 return $close . '<dd>';
1964 return '<!-- ERR 2 -->';
1969 * @param $char String
1972 function closeList( $char ) {
1973 if ( '*' === $char ) {
1974 $text = '</li></ul>';
1975 } elseif ( '#' === $char ) {
1976 $text = '</li></ol>';
1977 } elseif ( ':' === $char ) {
1978 if ( $this->mDTopen
) {
1979 $this->mDTopen
= false;
1980 $text = '</dt></dl>';
1982 $text = '</dd></dl>';
1985 return '<!-- ERR 3 -->';
1992 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
1994 * @param $linestart bool whether or not this is at the start of a line.
1996 * @return string the lists rendered as HTML
1998 function doBlockLevels( $text, $linestart ) {
1999 wfProfileIn( __METHOD__
);
2001 # Parsing through the text line by line. The main thing
2002 # happening here is handling of block-level elements p, pre,
2003 # and making lists from lines starting with * # : etc.
2005 $textLines = StringUtils
::explode( "\n", $text );
2007 $lastPrefix = $output = '';
2008 $this->mDTopen
= $inBlockElem = false;
2010 $paragraphStack = false;
2012 foreach ( $textLines as $oLine ) {
2014 if ( !$linestart ) {
2024 $lastPrefixLength = strlen( $lastPrefix );
2025 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2026 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2027 # If not in a <pre> element, scan for and figure out what prefixes are there.
2028 if ( !$this->mInPre
) {
2029 # Multiple prefixes may abut each other for nested lists.
2030 $prefixLength = strspn( $oLine, '*#:;' );
2031 $prefix = substr( $oLine, 0, $prefixLength );
2034 # ; and : are both from definition-lists, so they're equivalent
2035 # for the purposes of determining whether or not we need to open/close
2037 $prefix2 = str_replace( ';', ':', $prefix );
2038 $t = substr( $oLine, $prefixLength );
2039 $this->mInPre
= (bool)$preOpenMatch;
2041 # Don't interpret any other prefixes in preformatted text
2043 $prefix = $prefix2 = '';
2048 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2049 # Same as the last item, so no need to deal with nesting or opening stuff
2050 $output .= $this->nextItem( substr( $prefix, -1 ) );
2051 $paragraphStack = false;
2053 if ( substr( $prefix, -1 ) === ';') {
2054 # The one nasty exception: definition lists work like this:
2055 # ; title : definition text
2056 # So we check for : in the remainder text to split up the
2057 # title and definition, without b0rking links.
2059 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2061 $output .= $term . $this->nextItem( ':' );
2064 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2065 # We need to open or close prefixes, or both.
2067 # Either open or close a level...
2068 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2069 $paragraphStack = false;
2071 # Close all the prefixes which aren't shared.
2072 while ( $commonPrefixLength < $lastPrefixLength ) {
2073 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2074 --$lastPrefixLength;
2077 # Continue the current prefix if appropriate.
2078 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2079 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2082 # Open prefixes where appropriate.
2083 while ( $prefixLength > $commonPrefixLength ) {
2084 $char = substr( $prefix, $commonPrefixLength, 1 );
2085 $output .= $this->openList( $char );
2087 if ( ';' === $char ) {
2088 # FIXME: This is dupe of code above
2089 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2091 $output .= $term . $this->nextItem( ':' );
2094 ++
$commonPrefixLength;
2096 $lastPrefix = $prefix2;
2099 # If we have no prefixes, go to paragraph mode.
2100 if ( 0 == $prefixLength ) {
2101 wfProfileIn( __METHOD__
."-paragraph" );
2102 # No prefix (not in list)--go to paragraph mode
2103 # XXX: use a stack for nestable elements like span, table and div
2104 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2105 $closematch = preg_match(
2106 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2107 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2108 if ( $openmatch or $closematch ) {
2109 $paragraphStack = false;
2110 #Â TODO bug 5718: paragraph closed
2111 $output .= $this->closeParagraph();
2112 if ( $preOpenMatch and !$preCloseMatch ) {
2113 $this->mInPre
= true;
2115 if ( $closematch ) {
2116 $inBlockElem = false;
2118 $inBlockElem = true;
2120 } elseif ( !$inBlockElem && !$this->mInPre
) {
2121 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2123 if ( $this->mLastSection
!== 'pre' ) {
2124 $paragraphStack = false;
2125 $output .= $this->closeParagraph().'<pre>';
2126 $this->mLastSection
= 'pre';
2128 $t = substr( $t, 1 );
2131 if ( trim( $t ) == '' ) {
2132 if ( $paragraphStack ) {
2133 $output .= $paragraphStack.'<br />';
2134 $paragraphStack = false;
2135 $this->mLastSection
= 'p';
2137 if ( $this->mLastSection
!== 'p' ) {
2138 $output .= $this->closeParagraph();
2139 $this->mLastSection
= '';
2140 $paragraphStack = '<p>';
2142 $paragraphStack = '</p><p>';
2146 if ( $paragraphStack ) {
2147 $output .= $paragraphStack;
2148 $paragraphStack = false;
2149 $this->mLastSection
= 'p';
2150 } elseif ( $this->mLastSection
!== 'p' ) {
2151 $output .= $this->closeParagraph().'<p>';
2152 $this->mLastSection
= 'p';
2157 wfProfileOut( __METHOD__
."-paragraph" );
2159 # somewhere above we forget to get out of pre block (bug 785)
2160 if ( $preCloseMatch && $this->mInPre
) {
2161 $this->mInPre
= false;
2163 if ( $paragraphStack === false ) {
2167 while ( $prefixLength ) {
2168 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2171 if ( $this->mLastSection
!= '' ) {
2172 $output .= '</' . $this->mLastSection
. '>';
2173 $this->mLastSection
= '';
2176 wfProfileOut( __METHOD__
);
2181 * Split up a string on ':', ignoring any occurences inside tags
2182 * to prevent illegal overlapping.
2183 * @param string $str the string to split
2184 * @param string &$before set to everything before the ':'
2185 * @param string &$after set to everything after the ':'
2186 * return string the position of the ':', or false if none found
2188 function findColonNoLinks( $str, &$before, &$after ) {
2189 wfProfileIn( __METHOD__
);
2191 $pos = strpos( $str, ':' );
2192 if ( $pos === false ) {
2194 wfProfileOut( __METHOD__
);
2198 $lt = strpos( $str, '<' );
2199 if ( $lt === false ||
$lt > $pos ) {
2200 # Easy; no tag nesting to worry about
2201 $before = substr( $str, 0, $pos );
2202 $after = substr( $str, $pos+
1 );
2203 wfProfileOut( __METHOD__
);
2207 # Ugly state machine to walk through avoiding tags.
2208 $state = self
::COLON_STATE_TEXT
;
2210 $len = strlen( $str );
2211 for( $i = 0; $i < $len; $i++
) {
2215 # (Using the number is a performance hack for common cases)
2216 case 0: # self::COLON_STATE_TEXT:
2219 # Could be either a <start> tag or an </end> tag
2220 $state = self
::COLON_STATE_TAGSTART
;
2223 if ( $stack == 0 ) {
2225 $before = substr( $str, 0, $i );
2226 $after = substr( $str, $i +
1 );
2227 wfProfileOut( __METHOD__
);
2230 # Embedded in a tag; don't break it.
2233 # Skip ahead looking for something interesting
2234 $colon = strpos( $str, ':', $i );
2235 if ( $colon === false ) {
2236 # Nothing else interesting
2237 wfProfileOut( __METHOD__
);
2240 $lt = strpos( $str, '<', $i );
2241 if ( $stack === 0 ) {
2242 if ( $lt === false ||
$colon < $lt ) {
2244 $before = substr( $str, 0, $colon );
2245 $after = substr( $str, $colon +
1 );
2246 wfProfileOut( __METHOD__
);
2250 if ( $lt === false ) {
2251 # Nothing else interesting to find; abort!
2252 # We're nested, but there's no close tags left. Abort!
2255 # Skip ahead to next tag start
2257 $state = self
::COLON_STATE_TAGSTART
;
2260 case 1: # self::COLON_STATE_TAG:
2265 $state = self
::COLON_STATE_TEXT
;
2268 # Slash may be followed by >?
2269 $state = self
::COLON_STATE_TAGSLASH
;
2275 case 2: # self::COLON_STATE_TAGSTART:
2278 $state = self
::COLON_STATE_CLOSETAG
;
2281 $state = self
::COLON_STATE_COMMENT
;
2284 # Illegal early close? This shouldn't happen D:
2285 $state = self
::COLON_STATE_TEXT
;
2288 $state = self
::COLON_STATE_TAG
;
2291 case 3: # self::COLON_STATE_CLOSETAG:
2296 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2297 wfProfileOut( __METHOD__
);
2300 $state = self
::COLON_STATE_TEXT
;
2303 case self
::COLON_STATE_TAGSLASH
:
2305 # Yes, a self-closed tag <blah/>
2306 $state = self
::COLON_STATE_TEXT
;
2308 # Probably we're jumping the gun, and this is an attribute
2309 $state = self
::COLON_STATE_TAG
;
2312 case 5: # self::COLON_STATE_COMMENT:
2314 $state = self
::COLON_STATE_COMMENTDASH
;
2317 case self
::COLON_STATE_COMMENTDASH
:
2319 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2321 $state = self
::COLON_STATE_COMMENT
;
2324 case self
::COLON_STATE_COMMENTDASHDASH
:
2326 $state = self
::COLON_STATE_TEXT
;
2328 $state = self
::COLON_STATE_COMMENT
;
2332 throw new MWException( "State machine error in " . __METHOD__
);
2336 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2339 wfProfileOut( __METHOD__
);
2344 * Return value of a magic variable (like PAGENAME)
2348 function getVariableValue( $index, $frame=false ) {
2349 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2350 global $wgScriptPath, $wgStylePath;
2353 * Some of these require message or data lookups and can be
2354 * expensive to check many times.
2356 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2357 if ( isset( $this->mVarCache
[$index] ) ) {
2358 return $this->mVarCache
[$index];
2362 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2363 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2366 global $wgLocaltimezone;
2367 if ( isset( $wgLocaltimezone ) ) {
2368 $oldtz = date_default_timezone_get();
2369 date_default_timezone_set( $wgLocaltimezone );
2372 $localTimestamp = date( 'YmdHis', $ts );
2373 $localMonth = date( 'm', $ts );
2374 $localMonth1 = date( 'n', $ts );
2375 $localMonthName = date( 'n', $ts );
2376 $localDay = date( 'j', $ts );
2377 $localDay2 = date( 'd', $ts );
2378 $localDayOfWeek = date( 'w', $ts );
2379 $localWeek = date( 'W', $ts );
2380 $localYear = date( 'Y', $ts );
2381 $localHour = date( 'H', $ts );
2382 if ( isset( $wgLocaltimezone ) ) {
2383 date_default_timezone_set( $oldtz );
2387 case 'currentmonth':
2388 $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2390 case 'currentmonth1':
2391 $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2393 case 'currentmonthname':
2394 $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2396 case 'currentmonthnamegen':
2397 $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2399 case 'currentmonthabbrev':
2400 $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2403 $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2406 $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2409 $value = $wgContLang->formatNum( $localMonth );
2412 $value = $wgContLang->formatNum( $localMonth1 );
2414 case 'localmonthname':
2415 $value = $wgContLang->getMonthName( $localMonthName );
2417 case 'localmonthnamegen':
2418 $value = $wgContLang->getMonthNameGen( $localMonthName );
2420 case 'localmonthabbrev':
2421 $value = $wgContLang->getMonthAbbreviation( $localMonthName );
2424 $value = $wgContLang->formatNum( $localDay );
2427 $value = $wgContLang->formatNum( $localDay2 );
2430 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2433 $value = $this->mTitle
->getPartialURL();
2435 case 'fullpagename':
2436 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2438 case 'fullpagenamee':
2439 $value = $this->mTitle
->getPrefixedURL();
2442 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2444 case 'subpagenamee':
2445 $value = $this->mTitle
->getSubpageUrlForm();
2447 case 'basepagename':
2448 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2450 case 'basepagenamee':
2451 $value = wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2453 case 'talkpagename':
2454 if ( $this->mTitle
->canTalk() ) {
2455 $talkPage = $this->mTitle
->getTalkPage();
2456 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2461 case 'talkpagenamee':
2462 if ( $this->mTitle
->canTalk() ) {
2463 $talkPage = $this->mTitle
->getTalkPage();
2464 $value = $talkPage->getPrefixedUrl();
2469 case 'subjectpagename':
2470 $subjPage = $this->mTitle
->getSubjectPage();
2471 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2473 case 'subjectpagenamee':
2474 $subjPage = $this->mTitle
->getSubjectPage();
2475 $value = $subjPage->getPrefixedUrl();
2478 # Let the edit saving system know we should parse the page
2479 # *after* a revision ID has been assigned.
2480 $this->mOutput
->setFlag( 'vary-revision' );
2481 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2482 $value = $this->mRevisionId
;
2485 # Let the edit saving system know we should parse the page
2486 # *after* a revision ID has been assigned. This is for null edits.
2487 $this->mOutput
->setFlag( 'vary-revision' );
2488 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2489 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2491 case 'revisionday2':
2492 # Let the edit saving system know we should parse the page
2493 # *after* a revision ID has been assigned. This is for null edits.
2494 $this->mOutput
->setFlag( 'vary-revision' );
2495 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2496 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2498 case 'revisionmonth':
2499 # Let the edit saving system know we should parse the page
2500 # *after* a revision ID has been assigned. This is for null edits.
2501 $this->mOutput
->setFlag( 'vary-revision' );
2502 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2503 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2505 case 'revisionyear':
2506 # Let the edit saving system know we should parse the page
2507 # *after* a revision ID has been assigned. This is for null edits.
2508 $this->mOutput
->setFlag( 'vary-revision' );
2509 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2510 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2512 case 'revisiontimestamp':
2513 # Let the edit saving system know we should parse the page
2514 # *after* a revision ID has been assigned. This is for null edits.
2515 $this->mOutput
->setFlag( 'vary-revision' );
2516 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2517 $value = $this->getRevisionTimestamp();
2519 case 'revisionuser':
2520 # Let the edit saving system know we should parse the page
2521 # *after* a revision ID has been assigned. This is for null edits.
2522 $this->mOutput
->setFlag( 'vary-revision' );
2523 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2524 $value = $this->getRevisionUser();
2527 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2530 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2533 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2536 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2538 case 'subjectspace':
2539 $value = $this->mTitle
->getSubjectNsText();
2541 case 'subjectspacee':
2542 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2544 case 'currentdayname':
2545 $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2548 $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2551 $value = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2554 $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2557 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2558 # int to remove the padding
2559 $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2562 $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2564 case 'localdayname':
2565 $value = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2568 $value = $wgContLang->formatNum( $localYear, true );
2571 $value = $wgContLang->time( $localTimestamp, false, false );
2574 $value = $wgContLang->formatNum( $localHour, true );
2577 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2578 # int to remove the padding
2579 $value = $wgContLang->formatNum( (int)$localWeek );
2582 $value = $wgContLang->formatNum( $localDayOfWeek );
2584 case 'numberofarticles':
2585 $value = $wgContLang->formatNum( SiteStats
::articles() );
2587 case 'numberoffiles':
2588 $value = $wgContLang->formatNum( SiteStats
::images() );
2590 case 'numberofusers':
2591 $value = $wgContLang->formatNum( SiteStats
::users() );
2593 case 'numberofactiveusers':
2594 $value = $wgContLang->formatNum( SiteStats
::activeUsers() );
2596 case 'numberofpages':
2597 $value = $wgContLang->formatNum( SiteStats
::pages() );
2599 case 'numberofadmins':
2600 $value = $wgContLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2602 case 'numberofedits':
2603 $value = $wgContLang->formatNum( SiteStats
::edits() );
2605 case 'numberofviews':
2606 $value = $wgContLang->formatNum( SiteStats
::views() );
2608 case 'currenttimestamp':
2609 $value = wfTimestamp( TS_MW
, $ts );
2611 case 'localtimestamp':
2612 $value = $localTimestamp;
2614 case 'currentversion':
2615 $value = SpecialVersion
::getVersion();
2622 return $wgServerName;
2624 return $wgScriptPath;
2626 return $wgStylePath;
2627 case 'directionmark':
2628 return $wgContLang->getDirMark();
2629 case 'contentlanguage':
2630 global $wgContLanguageCode;
2631 return $wgContLanguageCode;
2634 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2642 $this->mVarCache
[$index] = $value;
2648 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2652 function initialiseVariables() {
2653 wfProfileIn( __METHOD__
);
2654 $variableIDs = MagicWord
::getVariableIDs();
2655 $substIDs = MagicWord
::getSubstIDs();
2657 $this->mVariables
= new MagicWordArray( $variableIDs );
2658 $this->mSubstWords
= new MagicWordArray( $substIDs );
2659 wfProfileOut( __METHOD__
);
2663 * Preprocess some wikitext and return the document tree.
2664 * This is the ghost of replace_variables().
2666 * @param string $text The text to parse
2667 * @param integer flags Bitwise combination of:
2668 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2669 * included. Default is to assume a direct page view.
2671 * The generated DOM tree must depend only on the input text and the flags.
2672 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2674 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2675 * change in the DOM tree for a given text, must be passed through the section identifier
2676 * in the section edit link and thus back to extractSections().
2678 * The output of this function is currently only cached in process memory, but a persistent
2679 * cache may be implemented at a later date which takes further advantage of these strict
2680 * dependency requirements.
2684 function preprocessToDom( $text, $flags = 0 ) {
2685 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2690 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2692 public static function splitWhitespace( $s ) {
2693 $ltrimmed = ltrim( $s );
2694 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2695 $trimmed = rtrim( $ltrimmed );
2696 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2698 $w2 = substr( $ltrimmed, -$diff );
2702 return array( $w1, $trimmed, $w2 );
2706 * Replace magic variables, templates, and template arguments
2707 * with the appropriate text. Templates are substituted recursively,
2708 * taking care to avoid infinite loops.
2710 * Note that the substitution depends on value of $mOutputType:
2711 * self::OT_WIKI: only {{subst:}} templates
2712 * self::OT_PREPROCESS: templates but not extension tags
2713 * self::OT_HTML: all templates and extension tags
2715 * @param string $tex The text to transform
2716 * @param PPFrame $frame Object describing the arguments passed to the template.
2717 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2718 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2719 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2722 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2723 # Is there any text? Also, Prevent too big inclusions!
2724 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2727 wfProfileIn( __METHOD__
);
2729 if ( $frame === false ) {
2730 $frame = $this->getPreprocessor()->newFrame();
2731 } elseif ( !( $frame instanceof PPFrame
) ) {
2732 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2733 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2736 $dom = $this->preprocessToDom( $text );
2737 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2738 $text = $frame->expand( $dom, $flags );
2740 wfProfileOut( __METHOD__
);
2744 # Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2745 static function createAssocArgs( $args ) {
2746 $assocArgs = array();
2748 foreach ( $args as $arg ) {
2749 $eqpos = strpos( $arg, '=' );
2750 if ( $eqpos === false ) {
2751 $assocArgs[$index++
] = $arg;
2753 $name = trim( substr( $arg, 0, $eqpos ) );
2754 $value = trim( substr( $arg, $eqpos+
1 ) );
2755 if ( $value === false ) {
2758 if ( $name !== false ) {
2759 $assocArgs[$name] = $value;
2768 * Warn the user when a parser limitation is reached
2769 * Will warn at most once the user per limitation type
2771 * @param string $limitationType, should be one of:
2772 * 'expensive-parserfunction' (corresponding messages:
2773 * 'expensive-parserfunction-warning',
2774 * 'expensive-parserfunction-category')
2775 * 'post-expand-template-argument' (corresponding messages:
2776 * 'post-expand-template-argument-warning',
2777 * 'post-expand-template-argument-category')
2778 * 'post-expand-template-inclusion' (corresponding messages:
2779 * 'post-expand-template-inclusion-warning',
2780 * 'post-expand-template-inclusion-category')
2781 * @params int $current, $max When an explicit limit has been
2782 * exceeded, provide the values (optional)
2784 function limitationWarn( $limitationType, $current=null, $max=null) {
2785 # does no harm if $current and $max are present but are unnecessary for the message
2786 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
2787 $this->mOutput
->addWarning( $warning );
2788 $this->addTrackingCategory( "$limitationType-category" );
2792 * Return the text of a template, after recursively
2793 * replacing any variables or templates within the template.
2795 * @param array $piece The parts of the template
2796 * $piece['title']: the title, i.e. the part before the |
2797 * $piece['parts']: the parameter array
2798 * $piece['lineStart']: whether the brace was at the start of a line
2799 * @param PPFrame The current frame, contains template arguments
2800 * @return string the text of the template
2803 function braceSubstitution( $piece, $frame ) {
2804 global $wgContLang, $wgNonincludableNamespaces;
2805 wfProfileIn( __METHOD__
);
2806 wfProfileIn( __METHOD__
.'-setup' );
2809 $found = false; # $text has been filled
2810 $nowiki = false; # wiki markup in $text should be escaped
2811 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2812 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2813 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2814 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2816 # Title object, where $text came from
2819 # $part1 is the bit before the first |, and must contain only title characters.
2820 # Various prefixes will be stripped from it later.
2821 $titleWithSpaces = $frame->expand( $piece['title'] );
2822 $part1 = trim( $titleWithSpaces );
2825 # Original title text preserved for various purposes
2826 $originalTitle = $part1;
2828 # $args is a list of argument nodes, starting from index 0, not including $part1
2829 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
2830 wfProfileOut( __METHOD__
.'-setup' );
2833 wfProfileIn( __METHOD__
.'-modifiers' );
2836 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
2838 # Possibilities for substMatch: "subst", "safesubst" or FALSE
2839 # Decide whether to expand template or keep wikitext as-is.
2840 if ( $this->ot
['wiki'] ) {
2841 if ( $substMatch === false ) {
2842 $literal = true; # literal when in PST with no prefix
2844 $literal = false; # expand when in PST with subst: or safesubst:
2847 if ( $substMatch == 'subst' ) {
2848 $literal = true; # literal when not in PST with plain subst:
2850 $literal = false; # expand when not in PST with safesubst: or no prefix
2854 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2861 if ( !$found && $args->getLength() == 0 ) {
2862 $id = $this->mVariables
->matchStartToEnd( $part1 );
2863 if ( $id !== false ) {
2864 $text = $this->getVariableValue( $id, $frame );
2865 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
2866 $this->mOutput
->mContainsOldMagic
= true;
2872 # MSG, MSGNW and RAW
2875 $mwMsgnw = MagicWord
::get( 'msgnw' );
2876 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2879 # Remove obsolete MSG:
2880 $mwMsg = MagicWord
::get( 'msg' );
2881 $mwMsg->matchStartAndRemove( $part1 );
2885 $mwRaw = MagicWord
::get( 'raw' );
2886 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2887 $forceRawInterwiki = true;
2890 wfProfileOut( __METHOD__
.'-modifiers' );
2894 wfProfileIn( __METHOD__
. '-pfunc' );
2896 $colonPos = strpos( $part1, ':' );
2897 if ( $colonPos !== false ) {
2898 # Case sensitive functions
2899 $function = substr( $part1, 0, $colonPos );
2900 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2901 $function = $this->mFunctionSynonyms
[1][$function];
2903 # Case insensitive functions
2904 $function = $wgContLang->lc( $function );
2905 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2906 $function = $this->mFunctionSynonyms
[0][$function];
2912 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2913 $initialArgs = array( &$this );
2914 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2915 if ( $flags & SFH_OBJECT_ARGS
) {
2916 # Add a frame parameter, and pass the arguments as an array
2917 $allArgs = $initialArgs;
2918 $allArgs[] = $frame;
2919 for ( $i = 0; $i < $args->getLength(); $i++
) {
2920 $funcArgs[] = $args->item( $i );
2922 $allArgs[] = $funcArgs;
2924 # Convert arguments to plain text
2925 for ( $i = 0; $i < $args->getLength(); $i++
) {
2926 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2928 $allArgs = array_merge( $initialArgs, $funcArgs );
2931 # Workaround for PHP bug 35229 and similar
2932 if ( !is_callable( $callback ) ) {
2933 wfProfileOut( __METHOD__
. '-pfunc' );
2934 wfProfileOut( __METHOD__
);
2935 throw new MWException( "Tag hook for $function is not callable\n" );
2937 $result = call_user_func_array( $callback, $allArgs );
2940 $preprocessFlags = 0;
2942 if ( is_array( $result ) ) {
2943 if ( isset( $result[0] ) ) {
2945 unset( $result[0] );
2948 # Extract flags into the local scope
2949 # This allows callers to set flags such as nowiki, found, etc.
2955 $text = $this->preprocessToDom( $text, $preprocessFlags );
2960 wfProfileOut( __METHOD__
. '-pfunc' );
2963 # Finish mangling title and then check for loops.
2964 # Set $title to a Title object and $titleText to the PDBK
2967 # Split the title into page and subpage
2969 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2970 if ( $subpage !== '' ) {
2971 $ns = $this->mTitle
->getNamespace();
2973 $title = Title
::newFromText( $part1, $ns );
2975 $titleText = $title->getPrefixedText();
2976 # Check for language variants if the template is not found
2977 if ( $wgContLang->hasVariants() && $title->getArticleID() == 0 ) {
2978 $wgContLang->findVariantLink( $part1, $title, true );
2980 # Do recursion depth check
2981 $limit = $this->mOptions
->getMaxTemplateDepth();
2982 if ( $frame->depth
>= $limit ) {
2984 $text = '<span class="error">'
2985 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
2991 # Load from database
2992 if ( !$found && $title ) {
2993 wfProfileIn( __METHOD__
. '-loadtpl' );
2994 if ( !$title->isExternal() ) {
2995 if ( $title->getNamespace() == NS_SPECIAL
2996 && $this->mOptions
->getAllowSpecialInclusion()
2997 && $this->ot
['html'] )
2999 $text = SpecialPage
::capturePath( $title );
3000 if ( is_string( $text ) ) {
3003 $this->disableCache();
3005 } elseif ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3006 $found = false; # access denied
3007 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3009 list( $text, $title ) = $this->getTemplateDom( $title );
3010 if ( $text !== false ) {
3016 # If the title is valid but undisplayable, make a link to it
3017 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3018 $text = "[[:$titleText]]";
3021 } elseif ( $title->isTrans() ) {
3022 # Interwiki transclusion
3023 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3024 $text = $this->interwikiTransclude( $title, 'render' );
3027 $text = $this->interwikiTransclude( $title, 'raw' );
3028 # Preprocess it like a template
3029 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3035 # Do infinite loop check
3036 # This has to be done after redirect resolution to avoid infinite loops via redirects
3037 if ( !$frame->loopCheck( $title ) ) {
3039 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3040 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3042 wfProfileOut( __METHOD__
. '-loadtpl' );
3045 # If we haven't found text to substitute by now, we're done
3046 # Recover the source wikitext and return it
3048 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3049 wfProfileOut( __METHOD__
);
3050 return array( 'object' => $text );
3053 # Expand DOM-style return values in a child frame
3054 if ( $isChildObj ) {
3055 # Clean up argument array
3056 $newFrame = $frame->newChild( $args, $title );
3059 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3060 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3061 # Expansion is eligible for the empty-frame cache
3062 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3063 $text = $this->mTplExpandCache
[$titleText];
3065 $text = $newFrame->expand( $text );
3066 $this->mTplExpandCache
[$titleText] = $text;
3069 # Uncached expansion
3070 $text = $newFrame->expand( $text );
3073 if ( $isLocalObj && $nowiki ) {
3074 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3075 $isLocalObj = false;
3078 # Replace raw HTML by a placeholder
3079 # Add a blank line preceding, to prevent it from mucking up
3080 # immediately preceding headings
3082 $text = "\n\n" . $this->insertStripItem( $text );
3083 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3084 # Escape nowiki-style return values
3085 $text = wfEscapeWikiText( $text );
3086 } elseif ( is_string( $text )
3087 && !$piece['lineStart']
3088 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3090 # Bug 529: if the template begins with a table or block-level
3091 # element, it should be treated as beginning a new line.
3092 # This behaviour is somewhat controversial.
3093 $text = "\n" . $text;
3096 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3097 # Error, oversize inclusion
3098 $text = "[[$originalTitle]]" .
3099 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3100 $this->limitationWarn( 'post-expand-template-inclusion' );
3103 if ( $isLocalObj ) {
3104 $ret = array( 'object' => $text );
3106 $ret = array( 'text' => $text );
3109 wfProfileOut( __METHOD__
);
3114 * Get the semi-parsed DOM representation of a template with a given title,
3115 * and its redirect destination title. Cached.
3117 function getTemplateDom( $title ) {
3118 $cacheTitle = $title;
3119 $titleText = $title->getPrefixedDBkey();
3121 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3122 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3123 $title = Title
::makeTitle( $ns, $dbk );
3124 $titleText = $title->getPrefixedDBkey();
3126 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3127 return array( $this->mTplDomCache
[$titleText], $title );
3130 # Cache miss, go to the database
3131 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3133 if ( $text === false ) {
3134 $this->mTplDomCache
[$titleText] = false;
3135 return array( false, $title );
3138 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3139 $this->mTplDomCache
[ $titleText ] = $dom;
3141 if ( !$title->equals( $cacheTitle ) ) {
3142 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3143 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3146 return array( $dom, $title );
3150 * Fetch the unparsed text of a template and register a reference to it.
3152 function fetchTemplateAndTitle( $title ) {
3153 $templateCb = $this->mOptions
->getTemplateCallback();
3154 $stuff = call_user_func( $templateCb, $title, $this );
3155 $text = $stuff['text'];
3156 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3157 if ( isset( $stuff['deps'] ) ) {
3158 foreach ( $stuff['deps'] as $dep ) {
3159 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3162 return array( $text, $finalTitle );
3165 function fetchTemplate( $title ) {
3166 $rv = $this->fetchTemplateAndTitle( $title );
3171 * Static function to get a template
3172 * Can be overridden via ParserOptions::setTemplateCallback().
3174 static function statelessFetchTemplate( $title, $parser=false ) {
3175 $text = $skip = false;
3176 $finalTitle = $title;
3179 # Loop to fetch the article, with up to 1 redirect
3180 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3181 # Give extensions a chance to select the revision instead
3182 $id = false; # Assume current
3183 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3189 'page_id' => $title->getArticleID(),
3193 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3194 $rev_id = $rev ?
$rev->getId() : 0;
3195 # If there is no current revision, there is no page
3196 if ( $id === false && !$rev ) {
3197 $linkCache = LinkCache
::singleton();
3198 $linkCache->addBadLinkObj( $title );
3203 'page_id' => $title->getArticleID(),
3204 'rev_id' => $rev_id );
3207 $text = $rev->getText();
3208 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3210 $message = $wgContLang->lcfirst( $title->getText() );
3211 $text = wfMsgForContentNoTrans( $message );
3212 if ( wfEmptyMsg( $message, $text ) ) {
3219 if ( $text === false ) {
3223 $finalTitle = $title;
3224 $title = Title
::newFromRedirect( $text );
3228 'finalTitle' => $finalTitle,
3233 * Transclude an interwiki link.
3235 function interwikiTransclude( $title, $action ) {
3236 global $wgEnableScaryTranscluding;
3238 if ( !$wgEnableScaryTranscluding ) {
3239 return wfMsg('scarytranscludedisabled');
3242 $url = $title->getFullUrl( "action=$action" );
3244 if ( strlen( $url ) > 255 ) {
3245 return wfMsg( 'scarytranscludetoolong' );
3247 return $this->fetchScaryTemplateMaybeFromCache( $url );
3250 function fetchScaryTemplateMaybeFromCache( $url ) {
3251 global $wgTranscludeCacheExpiry;
3252 $dbr = wfGetDB( DB_SLAVE
);
3253 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3254 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3255 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3257 return $obj->tc_contents
;
3260 $text = Http
::get( $url );
3262 return wfMsg( 'scarytranscludefailed', $url );
3265 $dbw = wfGetDB( DB_MASTER
);
3266 $dbw->replace( 'transcache', array('tc_url'), array(
3268 'tc_time' => $dbw->timestamp( time() ),
3269 'tc_contents' => $text)
3276 * Triple brace replacement -- used for template arguments
3279 function argSubstitution( $piece, $frame ) {
3280 wfProfileIn( __METHOD__
);
3283 $parts = $piece['parts'];
3284 $nameWithSpaces = $frame->expand( $piece['title'] );
3285 $argName = trim( $nameWithSpaces );
3287 $text = $frame->getArgument( $argName );
3288 if ( $text === false && $parts->getLength() > 0
3292 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3295 # No match in frame, use the supplied default
3296 $object = $parts->item( 0 )->getChildren();
3298 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3299 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3300 $this->limitationWarn( 'post-expand-template-argument' );
3303 if ( $text === false && $object === false ) {
3305 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3307 if ( $error !== false ) {
3310 if ( $object !== false ) {
3311 $ret = array( 'object' => $object );
3313 $ret = array( 'text' => $text );
3316 wfProfileOut( __METHOD__
);
3321 * Return the text to be used for a given extension tag.
3322 * This is the ghost of strip().
3324 * @param array $params Associative array of parameters:
3325 * name PPNode for the tag name
3326 * attr PPNode for unparsed text where tag attributes are thought to be
3327 * attributes Optional associative array of parsed attributes
3328 * inner Contents of extension element
3329 * noClose Original text did not have a close tag
3330 * @param PPFrame $frame
3332 function extensionSubstitution( $params, $frame ) {
3333 global $wgRawHtml, $wgContLang;
3335 $name = $frame->expand( $params['name'] );
3336 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3337 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3338 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3340 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3341 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3342 if ( $isFunctionTag ) {
3343 $markerType = 'none';
3345 $markerType = 'general';
3347 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3348 $name = strtolower( $name );
3349 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3350 if ( isset( $params['attributes'] ) ) {
3351 $attributes = $attributes +
$params['attributes'];
3354 if ( isset( $this->mTagHooks
[$name] ) ) {
3355 # Workaround for PHP bug 35229 and similar
3356 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3357 throw new MWException( "Tag hook for $name is not callable\n" );
3359 $output = call_user_func_array( $this->mTagHooks
[$name],
3360 array( $content, $attributes, $this, $frame ) );
3361 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3362 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3363 if ( !is_callable( $callback ) ) {
3364 throw new MWException( "Tag hook for $name is not callable\n" );
3367 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3369 $output = '<span class="error">Invalid tag extension name: ' .
3370 htmlspecialchars( $name ) . '</span>';
3373 if ( is_array( $output ) ) {
3374 # Extract flags to local scope (to override $markerType)
3376 $output = $flags[0];
3381 if ( is_null( $attrText ) ) {
3384 if ( isset( $params['attributes'] ) ) {
3385 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3386 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3387 htmlspecialchars( $attrValue ) . '"';
3390 if ( $content === null ) {
3391 $output = "<$name$attrText/>";
3393 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3394 $output = "<$name$attrText>$content$close";
3398 if ( $markerType === 'none' ) {
3400 } elseif ( $markerType === 'nowiki' ) {
3401 $this->mStripState
->nowiki
->setPair( $marker, $output );
3402 } elseif ( $markerType === 'general' ) {
3403 $this->mStripState
->general
->setPair( $marker, $output );
3405 throw new MWException( __METHOD__
.': invalid marker type' );
3411 * Increment an include size counter
3413 * @param string $type The type of expansion
3414 * @param integer $size The size of the text
3415 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3417 function incrementIncludeSize( $type, $size ) {
3418 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3421 $this->mIncludeSizes
[$type] +
= $size;
3427 * Increment the expensive function count
3429 * @return boolean False if the limit has been exceeded
3431 function incrementExpensiveFunctionCount() {
3432 global $wgExpensiveParserFunctionLimit;
3433 $this->mExpensiveFunctionCount++
;
3434 if ( $this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit ) {
3441 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3442 * Fills $this->mDoubleUnderscores, returns the modified text
3444 function doDoubleUnderscore( $text ) {
3445 wfProfileIn( __METHOD__
);
3447 # The position of __TOC__ needs to be recorded
3448 $mw = MagicWord
::get( 'toc' );
3449 if ( $mw->match( $text ) ) {
3450 $this->mShowToc
= true;
3451 $this->mForceTocPosition
= true;
3453 # Set a placeholder. At the end we'll fill it in with the TOC.
3454 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3456 # Only keep the first one.
3457 $text = $mw->replace( '', $text );
3460 # Now match and remove the rest of them
3461 $mwa = MagicWord
::getDoubleUnderscoreArray();
3462 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3464 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3465 $this->mOutput
->mNoGallery
= true;
3467 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3468 $this->mShowToc
= false;
3470 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3471 $this->mOutput
->setProperty( 'hiddencat', 'y' );
3472 $this->addTrackingCategory( 'hidden-category-category' );
3474 # (bug 8068) Allow control over whether robots index a page.
3476 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3477 # is not desirable, the last one on the page should win.
3478 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3479 $this->mOutput
->setIndexPolicy( 'noindex' );
3480 $this->addTrackingCategory( 'noindex-category' );
3482 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3483 $this->mOutput
->setIndexPolicy( 'index' );
3484 $this->addTrackingCategory( 'index-category' );
3487 wfProfileOut( __METHOD__
);
3492 * Add a tracking category, getting the title from a system message,
3493 * or print a debug message if the title is invalid.
3494 * @param $msg String message key
3495 * @return Bool whether the addition was successful
3497 protected function addTrackingCategory( $msg ) {
3498 $cat = wfMsgForContent( $msg );
3500 # Allow tracking categories to be disabled by setting them to "-"
3501 if ( $cat === '-' ) {
3505 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3506 if ( $containerCategory ) {
3507 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3510 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3516 * This function accomplishes several tasks:
3517 * 1) Auto-number headings if that option is enabled
3518 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3519 * 3) Add a Table of contents on the top for users who have enabled the option
3520 * 4) Auto-anchor headings
3522 * It loops through all headlines, collects the necessary data, then splits up the
3523 * string and re-inserts the newly formatted headlines.
3525 * @param string $text
3526 * @param string $origText Original, untouched wikitext
3527 * @param boolean $isMain
3530 function formatHeadings( $text, $origText, $isMain=true ) {
3531 global $wgMaxTocLevel, $wgContLang, $wgHtml5, $wgExperimentalHtmlIds;
3533 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3534 $showEditLink = $this->mOptions
->getEditSection();
3536 # Do not call quickUserCan unless necessary
3537 if ( $showEditLink && !$this->mTitle
->quickUserCan( 'edit' ) ) {
3541 # Inhibit editsection links if requested in the page
3542 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ||
$this->mOptions
->getIsPrintable() ) {
3546 # Get all headlines for numbering them and adding funky stuff like [edit]
3547 # links - this is for later, but we need the number of headlines right now
3549 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3551 # if there are fewer than 4 headlines in the article, do not show TOC
3552 # unless it's been explicitly enabled.
3553 $enoughToc = $this->mShowToc
&&
3554 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
3556 # Allow user to stipulate that a page should have a "new section"
3557 # link added via __NEWSECTIONLINK__
3558 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3559 $this->mOutput
->setNewSection( true );
3562 # Allow user to remove the "new section"
3563 # link via __NONEWSECTIONLINK__
3564 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3565 $this->mOutput
->hideNewSection( true );
3568 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3569 # override above conditions and always show TOC above first header
3570 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3571 $this->mShowToc
= true;
3575 # We need this to perform operations on the HTML
3576 $sk = $this->mOptions
->getSkin();
3582 # Ugh .. the TOC should have neat indentation levels which can be
3583 # passed to the skin functions. These are determined here
3587 $sublevelCount = array();
3588 $levelCount = array();
3594 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3595 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3596 $oldType = $this->mOutputType
;
3597 $this->setOutputType( self
::OT_WIKI
);
3598 $frame = $this->getPreprocessor()->newFrame();
3599 $root = $this->preprocessToDom( $origText );
3600 $node = $root->getFirstChild();
3604 foreach ( $matches[3] as $headline ) {
3605 $isTemplate = false;
3607 $sectionIndex = false;
3609 $markerMatches = array();
3610 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
3611 $serial = $markerMatches[1];
3612 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3613 $isTemplate = ( $titleText != $baseTitleText );
3614 $headline = preg_replace( "/^$markerRegex/", "", $headline );
3618 $prevlevel = $level;
3619 $prevtoclevel = $toclevel;
3621 $level = $matches[1][$headlineCount];
3623 if ( $level > $prevlevel ) {
3624 # Increase TOC level
3626 $sublevelCount[$toclevel] = 0;
3627 if ( $toclevel<$wgMaxTocLevel ) {
3628 $prevtoclevel = $toclevel;
3629 $toc .= $sk->tocIndent();
3632 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
3633 # Decrease TOC level, find level to jump to
3635 for ( $i = $toclevel; $i > 0; $i-- ) {
3636 if ( $levelCount[$i] == $level ) {
3637 # Found last matching level
3640 } elseif ( $levelCount[$i] < $level ) {
3641 # Found first matching level below current level
3649 if ( $toclevel<$wgMaxTocLevel ) {
3650 if ( $prevtoclevel < $wgMaxTocLevel ) {
3651 # Unindent only if the previous toc level was shown :p
3652 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3653 $prevtoclevel = $toclevel;
3655 $toc .= $sk->tocLineEnd();
3659 # No change in level, end TOC line
3660 if ( $toclevel<$wgMaxTocLevel ) {
3661 $toc .= $sk->tocLineEnd();
3665 $levelCount[$toclevel] = $level;
3667 # count number of headlines for each level
3668 @$sublevelCount[$toclevel]++
;
3670 for( $i = 1; $i <= $toclevel; $i++
) {
3671 if ( !empty( $sublevelCount[$i] ) ) {
3675 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3680 # The safe header is a version of the header text safe to use for links
3681 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3682 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3684 # Remove link placeholders by the link text.
3685 # <!--LINK number-->
3687 # link text with suffix
3688 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3690 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3691 $tocline = preg_replace(
3692 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3693 array( '', '<$1>' ),
3696 $tocline = trim( $tocline );
3698 # For the anchor, strip out HTML-y stuff period
3699 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3700 $safeHeadline = preg_replace( '/[ _]+/', ' ', $safeHeadline );
3701 $safeHeadline = trim( $safeHeadline );
3703 # Save headline for section edit hint before it's escaped
3704 $headlineHint = $safeHeadline;
3706 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
3707 # For reverse compatibility, provide an id that's
3708 # HTML4-compatible, like we used to.
3710 # It may be worth noting, academically, that it's possible for
3711 # the legacy anchor to conflict with a non-legacy headline
3712 # anchor on the page. In this case likely the "correct" thing
3713 # would be to either drop the legacy anchors or make sure
3714 # they're numbered first. However, this would require people
3715 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3716 # manually, so let's not bother worrying about it.
3717 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
3718 array( 'noninitial', 'legacy' ) );
3719 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3721 if ( $legacyHeadline == $safeHeadline ) {
3722 # No reason to have both (in fact, we can't)
3723 $legacyHeadline = false;
3726 $legacyHeadline = false;
3727 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
3731 # HTML names must be case-insensitively unique (bug 10721). FIXME:
3732 # Does this apply to Unicode characters? Because we aren't
3733 # handling those here.
3734 $arrayKey = strtolower( $safeHeadline );
3735 if ( $legacyHeadline === false ) {
3736 $legacyArrayKey = false;
3738 $legacyArrayKey = strtolower( $legacyHeadline );
3741 # count how many in assoc. array so we can track dupes in anchors
3742 if ( isset( $refers[$arrayKey] ) ) {
3743 $refers[$arrayKey]++
;
3745 $refers[$arrayKey] = 1;
3747 if ( isset( $refers[$legacyArrayKey] ) ) {
3748 $refers[$legacyArrayKey]++
;
3750 $refers[$legacyArrayKey] = 1;
3753 # Don't number the heading if it is the only one (looks silly)
3754 if ( $doNumberHeadings && count( $matches[3] ) > 1) {
3755 # the two are different if the line contains a link
3756 $headline = $numbering . ' ' . $headline;
3759 # Create the anchor for linking from the TOC to the section
3760 $anchor = $safeHeadline;
3761 $legacyAnchor = $legacyHeadline;
3762 if ( $refers[$arrayKey] > 1 ) {
3763 $anchor .= '_' . $refers[$arrayKey];
3765 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3766 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3768 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
3769 $toc .= $sk->tocLine( $anchor, $tocline,
3770 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
3773 # Add the section to the section tree
3774 # Find the DOM node for this header
3775 while ( $node && !$isTemplate ) {
3776 if ( $node->getName() === 'h' ) {
3777 $bits = $node->splitHeading();
3778 if ( $bits['i'] == $sectionIndex )
3781 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
3782 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
3783 $node = $node->getNextSibling();
3786 'toclevel' => $toclevel,
3789 'number' => $numbering,
3790 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
3791 'fromtitle' => $titleText,
3792 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
3793 'anchor' => $anchor,
3796 # give headline the correct <h#> tag
3797 if ( $showEditLink && $sectionIndex !== false ) {
3798 if ( $isTemplate ) {
3799 # Put a T flag in the section identifier, to indicate to extractSections()
3800 # that sections inside <includeonly> should be counted.
3801 $editlink = $sk->doEditSectionLink( Title
::newFromText( $titleText ), "T-$sectionIndex" );
3803 $editlink = $sk->doEditSectionLink( $this->mTitle
, $sectionIndex, $headlineHint );
3808 $head[$headlineCount] = $sk->makeHeadline( $level,
3809 $matches['attrib'][$headlineCount], $anchor, $headline,
3810 $editlink, $legacyAnchor );
3815 $this->setOutputType( $oldType );
3817 # Never ever show TOC if no headers
3818 if ( $numVisible < 1 ) {
3823 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3824 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3826 $toc = $sk->tocList( $toc );
3827 $this->mOutput
->setTOCHTML( $toc );
3831 $this->mOutput
->setSections( $tocraw );
3834 # split up and insert constructed headlines
3836 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3839 foreach ( $blocks as $block ) {
3840 if ( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3841 # This is the [edit] link that appears for the top block of text when
3842 # section editing is enabled
3844 # Disabled because it broke block formatting
3845 # For example, a bullet point in the top line
3846 # $full .= $sk->editSectionLink(0);
3849 if ( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3850 # Top anchor now in skin
3854 if ( !empty( $head[$i] ) ) {
3859 if ( $this->mForceTocPosition
) {
3860 return str_replace( '<!--MWTOC-->', $toc, $full );
3867 * Merge $tree2 into $tree1 by replacing the section with index
3868 * $section in $tree1 and its descendants with the sections in $tree2.
3869 * Note that in the returned section tree, only the 'index' and
3870 * 'byteoffset' fields are guaranteed to be correct.
3871 * @param $tree1 array Section tree from ParserOutput::getSectons()
3872 * @param $tree2 array Section tree
3873 * @param $section int Section index
3874 * @param $title Title Title both section trees come from
3875 * @param $len2 int Length of the original wikitext for $tree2
3876 * @return array Merged section tree
3878 public static function mergeSectionTrees( $tree1, $tree2, $section, $title, $len2 ) {
3881 $targetLevel = false;
3885 $numbering = array( 0 );
3886 $titletext = $title->getPrefixedDBkey();
3887 foreach ( $tree1 as $s ) {
3888 if ( $targetLevel !== false ) {
3889 if ( $s['level'] <= $targetLevel ) {
3890 # We've skipped enough
3891 $targetLevel = false;
3896 if ( $s['index'] != $section ||
3897 $s['fromtitle'] != $titletext ) {
3898 self
::incrementNumbering( $numbering,
3899 $s['toclevel'], $lastLevel );
3901 # Rewrite index, byteoffset and number
3902 if ( $s['fromtitle'] == $titletext ) {
3903 $s['index'] = $nextIndex++
;
3905 $s['byteoffset'] +
= $len2;
3908 $s['number'] = implode( '.', array_map(
3909 array( $wgContLang, 'formatnum' ),
3911 $lastLevel = $s['toclevel'];
3915 # Insert sections from $tree2 here
3916 foreach ( $tree2 as $s2 ) {
3917 # Rewrite the fields in $s2
3918 # before inserting it
3919 $s2['toclevel'] +
= $s['toclevel'] - 1;
3920 $s2['level'] +
= $s['level'] - 1;
3921 $s2['index'] = $nextIndex++
;
3922 $s2['byteoffset'] +
= $s['byteoffset'];
3924 self
::incrementNumbering( $numbering,
3925 $s2['toclevel'], $lastLevel );
3926 $s2['number'] = implode( '.', array_map(
3927 array( $wgContLang, 'formatnum' ),
3929 $lastLevel = $s2['toclevel'];
3932 # Skip all descendants of $section in $tree1
3933 $targetLevel = $s['level'];
3941 * Increment a section number. Helper function for mergeSectionTrees()
3942 * @param $number array Array representing a section number
3943 * @param $level int Current TOC level (depth)
3944 * @param $lastLevel int Level of previous TOC entry
3946 private static function incrementNumbering( &$number, $level, $lastLevel ) {
3947 if ( $level > $lastLevel ) {
3948 $number[$level - 1] = 1;
3949 } elseif ( $level < $lastLevel ) {
3950 foreach ( $number as $key => $unused )
3951 if ( $key >= $level ) {
3952 unset( $number[$key] );
3954 $number[$level - 1]++
;
3956 $number[$level - 1]++
;
3961 * Transform wiki markup when saving a page by doing \r\n -> \n
3962 * conversion, substitting signatures, {{subst:}} templates, etc.
3964 * @param string $text the text to transform
3965 * @param Title &$title the Title object for the current article
3966 * @param User $user the User object describing the current user
3967 * @param ParserOptions $options parsing options
3968 * @param bool $clearState whether to clear the parser state first
3969 * @return string the altered wiki markup
3972 function preSaveTransform( $text, Title
$title, $user, $options, $clearState = true ) {
3973 $this->mOptions
= $options;
3974 $this->setTitle( $title );
3975 $this->setOutputType( self
::OT_WIKI
);
3977 if ( $clearState ) {
3978 $this->clearState();
3984 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3985 $text = $this->pstPass2( $text, $user );
3986 $text = $this->mStripState
->unstripBoth( $text );
3991 * Pre-save transform helper function
3994 function pstPass2( $text, $user ) {
3995 global $wgContLang, $wgLocaltimezone;
3997 # Note: This is the timestamp saved as hardcoded wikitext to
3998 # the database, we use $wgContLang here in order to give
3999 # everyone the same signature and use the default one rather
4000 # than the one selected in each user's preferences.
4001 # (see also bug 12815)
4002 $ts = $this->mOptions
->getTimestamp();
4003 if ( isset( $wgLocaltimezone ) ) {
4004 $tz = $wgLocaltimezone;
4006 $tz = date_default_timezone_get();
4009 $unixts = wfTimestamp( TS_UNIX
, $ts );
4010 $oldtz = date_default_timezone_get();
4011 date_default_timezone_set( $tz );
4012 $ts = date( 'YmdHis', $unixts );
4013 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4015 # Allow translation of timezones trough wiki. date() can return
4016 # whatever crap the system uses, localised or not, so we cannot
4017 # ship premade translations.
4018 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4019 $value = wfMsgForContent( $key );
4020 if ( !wfEmptyMsg( $key, $value ) ) {
4024 date_default_timezone_set( $oldtz );
4026 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4028 # Variable replacement
4029 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4030 $text = $this->replaceVariables( $text );
4033 $sigText = $this->getUserSig( $user );
4034 $text = strtr( $text, array(
4036 '~~~~' => "$sigText $d",
4040 # Context links: [[|name]] and [[name (context)|]]
4041 global $wgLegalTitleChars;
4042 $tc = "[$wgLegalTitleChars]";
4043 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4045 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4046 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
4047 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4048 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4050 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4051 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4052 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4053 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4055 $t = $this->mTitle
->getText();
4057 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4058 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4059 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4060 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4062 # if there's no context, don't bother duplicating the title
4063 $text = preg_replace( $p2, '[[\\1]]', $text );
4066 # Trim trailing whitespace
4067 $text = rtrim( $text );
4073 * Fetch the user's signature text, if any, and normalize to
4074 * validated, ready-to-insert wikitext.
4075 * If you have pre-fetched the nickname or the fancySig option, you can
4076 * specify them here to save a database query.
4081 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4082 global $wgMaxSigChars;
4084 $username = $user->getName();
4086 # If not given, retrieve from the user object.
4087 if ( $nickname === false )
4088 $nickname = $user->getOption( 'nickname' );
4090 if ( is_null( $fancySig ) ) {
4091 $fancySig = $user->getBoolOption( 'fancysig' );
4094 $nickname = $nickname == null ?
$username : $nickname;
4096 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4097 $nickname = $username;
4098 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4099 } elseif ( $fancySig !== false ) {
4100 # Sig. might contain markup; validate this
4101 if ( $this->validateSig( $nickname ) !== false ) {
4102 # Validated; clean up (if needed) and return it
4103 return $this->cleanSig( $nickname, true );
4105 # Failed to validate; fall back to the default
4106 $nickname = $username;
4107 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4111 # Make sure nickname doesnt get a sig in a sig
4112 $nickname = $this->cleanSigInSig( $nickname );
4114 # If we're still here, make it a link to the user page
4115 $userText = wfEscapeWikiText( $username );
4116 $nickText = wfEscapeWikiText( $nickname );
4117 if ( $user->isAnon() ) {
4118 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4120 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4125 * Check that the user's signature contains no bad XML
4127 * @param string $text
4128 * @return mixed An expanded string, or false if invalid.
4130 function validateSig( $text ) {
4131 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4135 * Clean up signature text
4137 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4138 * 2) Substitute all transclusions
4140 * @param string $text
4141 * @param $parsing Whether we're cleaning (preferences save) or parsing
4142 * @return string Signature text
4144 function cleanSig( $text, $parsing = false ) {
4147 $this->clearState();
4148 $this->setTitle( $wgTitle );
4149 $this->mOptions
= new ParserOptions
;
4150 $this->setOutputType
= self
::OT_PREPROCESS
;
4153 # Option to disable this feature
4154 if ( !$this->mOptions
->getCleanSignatures() ) {
4158 # FIXME: regex doesn't respect extension tags or nowiki
4159 # => Move this logic to braceSubstitution()
4160 $substWord = MagicWord
::get( 'subst' );
4161 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4162 $substText = '{{' . $substWord->getSynonym( 0 );
4164 $text = preg_replace( $substRegex, $substText, $text );
4165 $text = $this->cleanSigInSig( $text );
4166 $dom = $this->preprocessToDom( $text );
4167 $frame = $this->getPreprocessor()->newFrame();
4168 $text = $frame->expand( $dom );
4171 $text = $this->mStripState
->unstripBoth( $text );
4178 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4179 * @param string $text
4180 * @return string Signature text with /~{3,5}/ removed
4182 function cleanSigInSig( $text ) {
4183 $text = preg_replace( '/~{3,5}/', '', $text );
4188 * Set up some variables which are usually set up in parse()
4189 * so that an external function can call some class members with confidence
4192 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
4193 $this->setTitle( $title );
4194 $this->mOptions
= $options;
4195 $this->setOutputType( $outputType );
4196 if ( $clearState ) {
4197 $this->clearState();
4202 * Wrapper for preprocess()
4204 * @param string $text the text to preprocess
4205 * @param ParserOptions $options options
4209 function transformMsg( $text, $options ) {
4211 static $executing = false;
4213 # Guard against infinite recursion
4219 wfProfileIn( __METHOD__
);
4220 $text = $this->preprocess( $text, $wgTitle, $options );
4223 wfProfileOut( __METHOD__
);
4228 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4229 * The callback should have the following form:
4230 * function myParserHook( $text, $params, $parser ) { ... }
4232 * Transform and return $text. Use $parser for any required context, e.g. use
4233 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4237 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
4238 * @param mixed $callback The callback function (and object) to use for the tag
4240 * @return The old value of the mTagHooks array associated with the hook
4242 function setHook( $tag, $callback ) {
4243 $tag = strtolower( $tag );
4244 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4245 $this->mTagHooks
[$tag] = $callback;
4246 if ( !in_array( $tag, $this->mStripList
) ) {
4247 $this->mStripList
[] = $tag;
4253 function setTransparentTagHook( $tag, $callback ) {
4254 $tag = strtolower( $tag );
4255 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4256 $this->mTransparentTagHooks
[$tag] = $callback;
4262 * Remove all tag hooks
4264 function clearTagHooks() {
4265 $this->mTagHooks
= array();
4266 $this->mStripList
= $this->mDefaultStripList
;
4270 * Create a function, e.g. {{sum:1|2|3}}
4271 * The callback function should have the form:
4272 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4274 * Or with SFH_OBJECT_ARGS:
4275 * function myParserFunction( $parser, $frame, $args ) { ... }
4277 * The callback may either return the text result of the function, or an array with the text
4278 * in element 0, and a number of flags in the other elements. The names of the flags are
4279 * specified in the keys. Valid flags are:
4280 * found The text returned is valid, stop processing the template. This
4282 * nowiki Wiki markup in the return value should be escaped
4283 * isHTML The returned text is HTML, armour it against wikitext transformation
4287 * @param string $id The magic word ID
4288 * @param mixed $callback The callback function (and object) to use
4289 * @param integer $flags a combination of the following flags:
4290 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4292 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4293 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4294 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4295 * the arguments, and to control the way they are expanded.
4297 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4298 * arguments, for instance:
4299 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4301 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4302 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4303 * working if/when this is changed.
4305 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4308 * Please read the documentation in includes/parser/Preprocessor.php for more information
4309 * about the methods available in PPFrame and PPNode.
4311 * @return The old callback function for this name, if any
4313 function setFunctionHook( $id, $callback, $flags = 0 ) {
4316 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4317 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4319 # Add to function cache
4320 $mw = MagicWord
::get( $id );
4322 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4324 $synonyms = $mw->getSynonyms();
4325 $sensitive = intval( $mw->isCaseSensitive() );
4327 foreach ( $synonyms as $syn ) {
4329 if ( !$sensitive ) {
4330 $syn = $wgContLang->lc( $syn );
4333 if ( !( $flags & SFH_NO_HASH
) ) {
4336 # Remove trailing colon
4337 if ( substr( $syn, -1, 1 ) === ':' ) {
4338 $syn = substr( $syn, 0, -1 );
4340 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4346 * Get all registered function hook identifiers
4350 function getFunctionHooks() {
4351 return array_keys( $this->mFunctionHooks
);
4355 * Create a tag function, e.g. <test>some stuff</test>.
4356 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4357 * Unlike parser functions, their content is not preprocessed.
4359 function setFunctionTagHook( $tag, $callback, $flags ) {
4360 $tag = strtolower( $tag );
4361 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4362 $this->mFunctionTagHooks
[$tag] : null;
4363 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4365 if ( !in_array( $tag, $this->mStripList
) ) {
4366 $this->mStripList
[] = $tag;
4373 * FIXME: update documentation. makeLinkObj() is deprecated.
4374 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4375 * Placeholders created in Skin::makeLinkObj()
4376 * Returns an array of link CSS classes, indexed by PDBK.
4378 function replaceLinkHolders( &$text, $options = 0 ) {
4379 return $this->mLinkHolders
->replace( $text );
4383 * Replace <!--LINK--> link placeholders with plain text of links
4384 * (not HTML-formatted).
4385 * @param string $text
4388 function replaceLinkHoldersText( $text ) {
4389 return $this->mLinkHolders
->replaceText( $text );
4393 * Renders an image gallery from a text with one line per image.
4394 * text labels may be given by using |-style alternative text. E.g.
4395 * Image:one.jpg|The number "1"
4396 * Image:tree.jpg|A tree
4397 * given as text will return the HTML of a gallery with two images,
4398 * labeled 'The number "1"' and
4401 function renderImageGallery( $text, $params ) {
4402 $ig = new ImageGallery();
4403 $ig->setContextTitle( $this->mTitle
);
4404 $ig->setShowBytes( false );
4405 $ig->setShowFilename( false );
4406 $ig->setParser( $this );
4407 $ig->setHideBadImages();
4408 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4409 $ig->useSkin( $this->mOptions
->getSkin() );
4410 $ig->mRevisionId
= $this->mRevisionId
;
4412 if ( isset( $params['showfilename'] ) ) {
4413 $ig->setShowFilename( true );
4415 $ig->setShowFilename( false );
4417 if ( isset( $params['caption'] ) ) {
4418 $caption = $params['caption'];
4419 $caption = htmlspecialchars( $caption );
4420 $caption = $this->replaceInternalLinks( $caption );
4421 $ig->setCaptionHtml( $caption );
4423 if ( isset( $params['perrow'] ) ) {
4424 $ig->setPerRow( $params['perrow'] );
4426 if ( isset( $params['widths'] ) ) {
4427 $ig->setWidths( $params['widths'] );
4429 if ( isset( $params['heights'] ) ) {
4430 $ig->setHeights( $params['heights'] );
4433 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4435 $lines = StringUtils
::explode( "\n", $text );
4436 foreach ( $lines as $line ) {
4437 # match lines like these:
4438 # Image:someimage.jpg|This is some image
4440 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4442 if ( count( $matches ) == 0 ) {
4446 if ( strpos( $matches[0], '%' ) !== false ) {
4447 $matches[1] = urldecode( $matches[1] );
4449 $tp = Title
::newFromText( $matches[1] );
4451 if ( is_null( $nt ) ) {
4452 # Bogus title. Ignore these so we don't bomb out later.
4455 if ( isset( $matches[3] ) ) {
4456 $label = $matches[3];
4461 $html = $this->recursiveTagParse( trim( $label ) );
4463 $ig->add( $nt, $html );
4465 # Only add real images (bug #5586)
4466 if ( $nt->getNamespace() == NS_FILE
) {
4467 $this->mOutput
->addImage( $nt->getDBkey() );
4470 return $ig->toHTML();
4473 function getImageParams( $handler ) {
4475 $handlerClass = get_class( $handler );
4479 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4480 # Initialise static lists
4481 static $internalParamNames = array(
4482 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4483 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4484 'bottom', 'text-bottom' ),
4485 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4486 'upright', 'border', 'link', 'alt' ),
4488 static $internalParamMap;
4489 if ( !$internalParamMap ) {
4490 $internalParamMap = array();
4491 foreach ( $internalParamNames as $type => $names ) {
4492 foreach ( $names as $name ) {
4493 $magicName = str_replace( '-', '_', "img_$name" );
4494 $internalParamMap[$magicName] = array( $type, $name );
4499 # Add handler params
4500 $paramMap = $internalParamMap;
4502 $handlerParamMap = $handler->getParamMap();
4503 foreach ( $handlerParamMap as $magic => $paramName ) {
4504 $paramMap[$magic] = array( 'handler', $paramName );
4507 $this->mImageParams
[$handlerClass] = $paramMap;
4508 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4510 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4514 * Parse image options text and use it to make an image
4515 * @param Title $title
4516 * @param string $options
4517 * @param LinkHolderArray $holders
4519 function makeImage( $title, $options, $holders = false ) {
4520 # Check if the options text is of the form "options|alt text"
4522 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4523 # * left no resizing, just left align. label is used for alt= only
4524 # * right same, but right aligned
4525 # * none same, but not aligned
4526 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4527 # * center center the image
4528 # * frame Keep original image size, no magnify-button.
4529 # * framed Same as "frame"
4530 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4531 # * upright reduce width for upright images, rounded to full __0 px
4532 # * border draw a 1px border around the image
4533 # * alt Text for HTML alt attribute (defaults to empty)
4534 # * link Set the target of the image link. Can be external, interwiki, or local
4535 # vertical-align values (no % or length right now):
4545 $parts = StringUtils
::explode( "|", $options );
4546 $sk = $this->mOptions
->getSkin();
4548 # Give extensions a chance to select the file revision for us
4549 $skip = $time = $descQuery = false;
4550 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4553 return $sk->link( $title );
4557 $imagename = $title->getDBkey();
4558 $file = wfFindFile( $title, array( 'time' => $time ) );
4560 $handler = $file ?
$file->getHandler() : false;
4562 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4564 # Process the input parameters
4566 $params = array( 'frame' => array(), 'handler' => array(),
4567 'horizAlign' => array(), 'vertAlign' => array() );
4568 foreach ( $parts as $part ) {
4569 $part = trim( $part );
4570 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4572 if ( isset( $paramMap[$magicName] ) ) {
4573 list( $type, $paramName ) = $paramMap[$magicName];
4575 # Special case; width and height come in one variable together
4576 if ( $type === 'handler' && $paramName === 'width' ) {
4578 # (bug 13500) In both cases (width/height and width only),
4579 # permit trailing "px" for backward compatibility.
4580 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4581 $width = intval( $m[1] );
4582 $height = intval( $m[2] );
4583 if ( $handler->validateParam( 'width', $width ) ) {
4584 $params[$type]['width'] = $width;
4587 if ( $handler->validateParam( 'height', $height ) ) {
4588 $params[$type]['height'] = $height;
4591 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4592 $width = intval( $value );
4593 if ( $handler->validateParam( 'width', $width ) ) {
4594 $params[$type]['width'] = $width;
4597 } # else no validation -- bug 13436
4599 if ( $type === 'handler' ) {
4600 # Validate handler parameter
4601 $validated = $handler->validateParam( $paramName, $value );
4603 # Validate internal parameters
4604 switch( $paramName ) {
4607 # @todo Fixme: possibly check validity here for
4608 # manualthumb? downstream behavior seems odd with
4609 # missing manual thumbs.
4611 $value = $this->stripAltText( $value, $holders );
4614 $chars = self
::EXT_LINK_URL_CLASS
;
4615 $prots = $this->mUrlProtocols
;
4616 if ( $value === '' ) {
4617 $paramName = 'no-link';
4620 } elseif ( preg_match( "/^$prots/", $value ) ) {
4621 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4622 $paramName = 'link-url';
4623 $this->mOutput
->addExternalLink( $value );
4627 $linkTitle = Title
::newFromText( $value );
4629 $paramName = 'link-title';
4630 $value = $linkTitle;
4631 $this->mOutput
->addLink( $linkTitle );
4637 # Most other things appear to be empty or numeric...
4638 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4643 $params[$type][$paramName] = $value;
4647 if ( !$validated ) {
4652 # Process alignment parameters
4653 if ( $params['horizAlign'] ) {
4654 $params['frame']['align'] = key( $params['horizAlign'] );
4656 if ( $params['vertAlign'] ) {
4657 $params['frame']['valign'] = key( $params['vertAlign'] );
4660 $params['frame']['caption'] = $caption;
4662 # Will the image be presented in a frame, with the caption below?
4663 $imageIsFramed = isset( $params['frame']['frame'] ) ||
4664 isset( $params['frame']['framed'] ) ||
4665 isset( $params['frame']['thumbnail'] ) ||
4666 isset( $params['frame']['manualthumb'] );
4668 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4669 # came to also set the caption, ordinary text after the image -- which
4670 # makes no sense, because that just repeats the text multiple times in
4671 # screen readers. It *also* came to set the title attribute.
4673 # Now that we have an alt attribute, we should not set the alt text to
4674 # equal the caption: that's worse than useless, it just repeats the
4675 # text. This is the framed/thumbnail case. If there's no caption, we
4676 # use the unnamed parameter for alt text as well, just for the time be-
4677 # ing, if the unnamed param is set and the alt param is not.
4679 # For the future, we need to figure out if we want to tweak this more,
4680 # e.g., introducing a title= parameter for the title; ignoring the un-
4681 # named parameter entirely for images without a caption; adding an ex-
4682 # plicit caption= parameter and preserving the old magic unnamed para-
4684 if ( $imageIsFramed ) { # Framed image
4685 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
4686 # No caption or alt text, add the filename as the alt text so
4687 # that screen readers at least get some description of the image
4688 $params['frame']['alt'] = $title->getText();
4690 # Do not set $params['frame']['title'] because tooltips don't make sense
4692 } else { # Inline image
4693 if ( !isset( $params['frame']['alt'] ) ) {
4694 # No alt text, use the "caption" for the alt text
4695 if ( $caption !== '') {
4696 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
4698 # No caption, fall back to using the filename for the
4700 $params['frame']['alt'] = $title->getText();
4703 # Use the "caption" for the tooltip text
4704 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4707 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4709 # Linker does the rest
4710 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4712 # Give the handler a chance to modify the parser object
4714 $handler->parserTransformHook( $this, $file );
4720 protected function stripAltText( $caption, $holders ) {
4721 # Strip bad stuff out of the title (tooltip). We can't just use
4722 # replaceLinkHoldersText() here, because if this function is called
4723 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4725 $tooltip = $holders->replaceText( $caption );
4727 $tooltip = $this->replaceLinkHoldersText( $caption );
4730 # make sure there are no placeholders in thumbnail attributes
4731 # that are later expanded to html- so expand them now and
4733 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
4734 $tooltip = Sanitizer
::stripAllTags( $tooltip );
4740 * Set a flag in the output object indicating that the content is dynamic and
4741 * shouldn't be cached.
4743 function disableCache() {
4744 wfDebug( "Parser output marked as uncacheable.\n" );
4745 $this->mOutput
->mCacheTime
= -1;
4749 * Callback from the Sanitizer for expanding items found in HTML attribute
4750 * values, so they can be safely tested and escaped.
4751 * @param string $text
4752 * @param PPFrame $frame
4756 function attributeStripCallback( &$text, $frame = false ) {
4757 $text = $this->replaceVariables( $text, $frame );
4758 $text = $this->mStripState
->unstripBoth( $text );
4767 function Title( $x = null ) { return wfSetVar( $this->mTitle
, $x ); }
4768 function Options( $x = null ) { return wfSetVar( $this->mOptions
, $x ); }
4769 function OutputType( $x = null ) { return wfSetVar( $this->mOutputType
, $x ); }
4775 function getTags() {
4776 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) );
4782 * Break wikitext input into sections, and either pull or replace
4783 * some particular section's text.
4785 * External callers should use the getSection and replaceSection methods.
4787 * @param string $text Page wikitext
4788 * @param string $section A section identifier string of the form:
4789 * <flag1> - <flag2> - ... - <section number>
4791 * Currently the only recognised flag is "T", which means the target section number
4792 * was derived during a template inclusion parse, in other words this is a template
4793 * section edit link. If no flags are given, it was an ordinary section edit link.
4794 * This flag is required to avoid a section numbering mismatch when a section is
4795 * enclosed by <includeonly> (bug 6563).
4797 * The section number 0 pulls the text before the first heading; other numbers will
4798 * pull the given section along with its lower-level subsections. If the section is
4799 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4801 * @param string $mode One of "get" or "replace"
4802 * @param string $newText Replacement text for section data.
4803 * @return string for "get", the extracted section text.
4804 * for "replace", the whole page with the section replaced.
4806 private function extractSections( $text, $section, $mode, $newText='' ) {
4808 $this->clearState();
4809 $this->setTitle( $wgTitle ); # not generally used but removes an ugly failure mode
4810 $this->mOptions
= new ParserOptions
;
4811 $this->setOutputType( self
::OT_PLAIN
);
4813 $frame = $this->getPreprocessor()->newFrame();
4815 # Process section extraction flags
4817 $sectionParts = explode( '-', $section );
4818 $sectionIndex = array_pop( $sectionParts );
4819 foreach ( $sectionParts as $part ) {
4820 if ( $part === 'T' ) {
4821 $flags |
= self
::PTD_FOR_INCLUSION
;
4824 # Preprocess the text
4825 $root = $this->preprocessToDom( $text, $flags );
4827 # <h> nodes indicate section breaks
4828 # They can only occur at the top level, so we can find them by iterating the root's children
4829 $node = $root->getFirstChild();
4831 # Find the target section
4832 if ( $sectionIndex == 0 ) {
4833 # Section zero doesn't nest, level=big
4834 $targetLevel = 1000;
4837 if ( $node->getName() === 'h' ) {
4838 $bits = $node->splitHeading();
4839 if ( $bits['i'] == $sectionIndex ) {
4840 $targetLevel = $bits['level'];
4844 if ( $mode === 'replace' ) {
4845 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4847 $node = $node->getNextSibling();
4853 if ( $mode === 'get' ) {
4860 # Find the end of the section, including nested sections
4862 if ( $node->getName() === 'h' ) {
4863 $bits = $node->splitHeading();
4864 $curLevel = $bits['level'];
4865 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4869 if ( $mode === 'get' ) {
4870 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4872 $node = $node->getNextSibling();
4875 # Write out the remainder (in replace mode only)
4876 if ( $mode === 'replace' ) {
4877 # Output the replacement text
4878 # Add two newlines on -- trailing whitespace in $newText is conventionally
4879 # stripped by the editor, so we need both newlines to restore the paragraph gap
4880 # Only add trailing whitespace if there is newText
4881 if ( $newText != "" ) {
4882 $outText .= $newText . "\n\n";
4886 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4887 $node = $node->getNextSibling();
4891 if ( is_string( $outText ) ) {
4892 # Re-insert stripped tags
4893 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4900 * This function returns the text of a section, specified by a number ($section).
4901 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4902 * the first section before any such heading (section 0).
4904 * If a section contains subsections, these are also returned.
4906 * @param string $text text to look in
4907 * @param string $section section identifier
4908 * @param string $deftext default to return if section is not found
4909 * @return string text of the requested section
4911 public function getSection( $text, $section, $deftext='' ) {
4912 return $this->extractSections( $text, $section, "get", $deftext );
4915 public function replaceSection( $oldtext, $section, $text ) {
4916 return $this->extractSections( $oldtext, $section, "replace", $text );
4920 * Get the timestamp associated with the current revision, adjusted for
4921 * the default server-local timestamp
4923 function getRevisionTimestamp() {
4924 if ( is_null( $this->mRevisionTimestamp
) ) {
4925 wfProfileIn( __METHOD__
);
4927 $dbr = wfGetDB( DB_SLAVE
);
4928 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4929 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4931 # Normalize timestamp to internal MW format for timezone processing.
4932 # This has the added side-effect of replacing a null value with
4933 # the current time, which gives us more sensible behavior for
4935 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4937 # The cryptic '' timezone parameter tells to use the site-default
4938 # timezone offset instead of the user settings.
4940 # Since this value will be saved into the parser cache, served
4941 # to other users, and potentially even used inside links and such,
4942 # it needs to be consistent for all visitors.
4943 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4945 wfProfileOut( __METHOD__
);
4947 return $this->mRevisionTimestamp
;
4951 * Get the name of the user that edited the last revision
4953 function getRevisionUser() {
4954 # if this template is subst: the revision id will be blank,
4955 # so just use the current user's name
4956 if ( $this->mRevisionId
) {
4957 $revision = Revision
::newFromId( $this->mRevisionId
);
4958 $revuser = $revision->getUserText();
4961 $revuser = $wgUser->getName();
4967 * Mutator for $mDefaultSort
4969 * @param $sort New value
4971 public function setDefaultSort( $sort ) {
4972 $this->mDefaultSort
= $sort;
4976 * Accessor for $mDefaultSort
4977 * Will use the title/prefixed title if none is set
4981 public function getDefaultSort() {
4982 global $wgCategoryPrefixedDefaultSortkey;
4983 if ( $this->mDefaultSort
!== false ) {
4984 return $this->mDefaultSort
;
4985 } elseif ( $this->mTitle
->getNamespace() == NS_CATEGORY ||
4986 !$wgCategoryPrefixedDefaultSortkey )
4988 return $this->mTitle
->getText();
4990 return $this->mTitle
->getPrefixedText();
4995 * Accessor for $mDefaultSort
4996 * Unlike getDefaultSort(), will return false if none is set
4998 * @return string or false
5000 public function getCustomDefaultSort() {
5001 return $this->mDefaultSort
;
5005 * Try to guess the section anchor name based on a wikitext fragment
5006 * presumably extracted from a heading, for example "Header" from
5009 public function guessSectionNameFromWikiText( $text ) {
5010 # Strip out wikitext links(they break the anchor)
5011 $text = $this->stripSectionName( $text );
5012 $headline = Sanitizer
::decodeCharReferences( $text );
5014 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
5015 $headline = trim( $headline );
5016 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
5017 $replacearray = array(
5022 array_keys( $replacearray ),
5023 array_values( $replacearray ),
5028 * Strips a text string of wikitext for use in a section anchor
5030 * Accepts a text string and then removes all wikitext from the
5031 * string and leaves only the resultant text (i.e. the result of
5032 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5033 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5034 * to create valid section anchors by mimicing the output of the
5035 * parser when headings are parsed.
5037 * @param $text string Text string to be stripped of wikitext
5038 * for use in a Section anchor
5039 * @return Filtered text string
5041 public function stripSectionName( $text ) {
5042 # Strip internal link markup
5043 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5044 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5046 # Strip external link markup (FIXME: Not Tolerant to blank link text
5047 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5048 # on how many empty links there are on the page - need to figure that out.
5049 $text = preg_replace( '/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5051 # Parse wikitext quotes (italics & bold)
5052 $text = $this->doQuotes( $text );
5055 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5059 function srvus( $text ) {
5060 return $this->testSrvus( $text, $this->mOutputType
);
5064 * strip/replaceVariables/unstrip for preprocessor regression testing
5066 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
5067 $this->clearState();
5068 if ( !$title instanceof Title
) {
5069 $title = Title
::newFromText( $title );
5071 $this->mTitle
= $title;
5072 $this->mOptions
= $options;
5073 $this->setOutputType( $outputType );
5074 $text = $this->replaceVariables( $text );
5075 $text = $this->mStripState
->unstripBoth( $text );
5076 $text = Sanitizer
::removeHTMLtags( $text );
5080 function testPst( $text, $title, $options ) {
5082 if ( !$title instanceof Title
) {
5083 $title = Title
::newFromText( $title );
5085 return $this->preSaveTransform( $text, $title, $wgUser, $options );
5088 function testPreprocess( $text, $title, $options ) {
5089 if ( !$title instanceof Title
) {
5090 $title = Title
::newFromText( $title );
5092 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5095 function markerSkipCallback( $s, $callback ) {
5098 while ( $i < strlen( $s ) ) {
5099 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5100 if ( $markerStart === false ) {
5101 $out .= call_user_func( $callback, substr( $s, $i ) );
5104 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5105 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5106 if ( $markerEnd === false ) {
5107 $out .= substr( $s, $markerStart );
5110 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5111 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5119 function serialiseHalfParsedText( $text ) {
5121 $data['text'] = $text;
5123 # First, find all strip markers, and store their
5125 $stripState = new StripState
;
5127 while ( ( $start_pos = strpos( $text, $this->mUniqPrefix
, $pos ) )
5128 && ( $end_pos = strpos( $text, self
::MARKER_SUFFIX
, $pos ) ) )
5130 $end_pos +
= strlen( self
::MARKER_SUFFIX
);
5131 $marker = substr( $text, $start_pos, $end_pos-$start_pos );
5133 if ( !empty( $this->mStripState
->general
->data
[$marker] ) ) {
5134 $replaceArray = $stripState->general
;
5135 $stripText = $this->mStripState
->general
->data
[$marker];
5136 } elseif ( !empty( $this->mStripState
->nowiki
->data
[$marker] ) ) {
5137 $replaceArray = $stripState->nowiki
;
5138 $stripText = $this->mStripState
->nowiki
->data
[$marker];
5140 throw new MWException( "Hanging strip marker: '$marker'." );
5143 $replaceArray->setPair( $marker, $stripText );
5146 $data['stripstate'] = $stripState;
5148 # Now, find all of our links, and store THEIR
5149 # data in an array! :)
5150 $links = array( 'internal' => array(), 'interwiki' => array() );
5154 while ( ( $start_pos = strpos( $text, '<!--LINK ', $pos ) ) ) {
5155 list( $ns, $trail ) = explode( ':', substr( $text, $start_pos +
strlen( '<!--LINK ' ) ), 2 );
5158 if ( empty( $links['internal'][$ns] ) ) {
5159 $links['internal'][$ns] = array();
5162 $key = trim( substr( $trail, 0, strpos( $trail, '-->' ) ) );
5163 $links['internal'][$ns][] = $this->mLinkHolders
->internals
[$ns][$key];
5164 $pos = $start_pos +
strlen( "<!--LINK $ns:$key-->" );
5170 while ( ( $start_pos = strpos( $text, '<!--IWLINK ', $pos ) ) ) {
5171 $data = substr( $text, $start_pos );
5172 $key = trim( substr( $data, 0, strpos( $data, '-->' ) ) );
5173 $links['interwiki'][] = $this->mLinkHolders
->interwiki
[$key];
5174 $pos = $start_pos +
strlen( "<!--IWLINK $key-->" );
5177 $data['linkholder'] = $links;
5184 * @param $data Array
5185 * @param $intPrefix String unique identifying prefix
5188 function unserialiseHalfParsedText( $data, $intPrefix = null ) {
5189 if ( !$intPrefix ) {
5190 $intPrefix = $this->getRandomString();
5193 # First, extract the strip state.
5194 $stripState = $data['stripstate'];
5195 $this->mStripState
->general
->merge( $stripState->general
);
5196 $this->mStripState
->nowiki
->merge( $stripState->nowiki
);
5198 # Now, extract the text, and renumber links
5199 $text = $data['text'];
5200 $links = $data['linkholder'];
5203 foreach ( $links['internal'] as $ns => $nsLinks ) {
5204 foreach ( $nsLinks as $key => $entry ) {
5205 $newKey = $intPrefix . '-' . $key;
5206 $this->mLinkHolders
->internals
[$ns][$newKey] = $entry;
5208 $text = str_replace( "<!--LINK $ns:$key-->", "<!--LINK $ns:$newKey-->", $text );
5213 foreach ( $links['interwiki'] as $key => $entry ) {
5214 $newKey = "$intPrefix-$key";
5215 $this->mLinkHolders
->interwikis
[$newKey] = $entry;
5217 $text = str_replace( "<!--IWLINK $key-->", "<!--IWLINK $newKey-->", $text );
5220 # Should be good to go.
5226 * @todo document, briefly.
5230 var $general, $nowiki;
5232 function __construct() {
5233 $this->general
= new ReplacementArray
;
5234 $this->nowiki
= new ReplacementArray
;
5237 function unstripGeneral( $text ) {
5238 wfProfileIn( __METHOD__
);
5241 $text = $this->general
->replace( $text );
5242 } while ( $text !== $oldText );
5243 wfProfileOut( __METHOD__
);
5247 function unstripNoWiki( $text ) {
5248 wfProfileIn( __METHOD__
);
5251 $text = $this->nowiki
->replace( $text );
5252 } while ( $text !== $oldText );
5253 wfProfileOut( __METHOD__
);
5257 function unstripBoth( $text ) {
5258 wfProfileIn( __METHOD__
);
5261 $text = $this->general
->replace( $text );
5262 $text = $this->nowiki
->replace( $text );
5263 } while ( $text !== $oldText );
5264 wfProfileOut( __METHOD__
);
5270 * @todo document, briefly.
5273 class OnlyIncludeReplacer
{
5276 function replace( $matches ) {
5277 if ( substr( $matches[1], -1 ) === "\n" ) {
5278 $this->output
.= substr( $matches[1], 0, -1 );
5280 $this->output
.= $matches[1];