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";
95 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables;
96 var $mSubstWords, $mImageParams, $mImageParamsMagicArray, $mStripList, $mMarkerIndex;
97 var $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols, $mDefaultStripList;
98 var $mVarCache, $mConf, $mFunctionTagHooks;
101 # Cleared with clearState():
102 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
103 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
104 var $mLinkHolders, $mLinkID;
105 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
106 var $mTplExpandCache; // empty-frame expansion cache
107 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
108 var $mExpensiveFunctionCount; // number of expensive parser function calls
111 # These are variables reset at least once per parse regardless of $clearState
112 var $mOptions; // ParserOptions object
113 var $mTitle; // Title context, used for self-link rendering and similar things
114 var $mOutputType; // Output type, one of the OT_xxx constants
115 var $ot; // Shortcut alias, see setOutputType()
116 var $mRevisionId; // ID to display in {{REVISIONID}} tags
117 var $mRevisionTimestamp; // The timestamp of the specified revision ID
118 var $mRevIdForTs; // The revision ID which was used to fetch the timestamp
127 function __construct( $conf = array() ) {
128 $this->mConf
= $conf;
129 $this->mTagHooks
= array();
130 $this->mTransparentTagHooks
= array();
131 $this->mFunctionHooks
= array();
132 $this->mFunctionTagHooks
= array();
133 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
134 $this->mDefaultStripList
= $this->mStripList
= array();
135 $this->mUrlProtocols
= wfUrlProtocols();
136 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
137 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
138 $this->mVarCache
= array();
139 if ( isset( $conf['preprocessorClass'] ) ) {
140 $this->mPreprocessorClass
= $conf['preprocessorClass'];
141 } elseif ( extension_loaded( 'domxml' ) ) {
142 // PECL extension that conflicts with the core DOM extension (bug 13770)
143 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
144 $this->mPreprocessorClass
= 'Preprocessor_Hash';
145 } elseif ( extension_loaded( 'dom' ) ) {
146 $this->mPreprocessorClass
= 'Preprocessor_DOM';
148 $this->mPreprocessorClass
= 'Preprocessor_Hash';
150 $this->mMarkerIndex
= 0;
151 $this->mFirstCall
= true;
155 * Reduce memory usage to reduce the impact of circular references
157 function __destruct() {
158 if ( isset( $this->mLinkHolders
) ) {
159 $this->mLinkHolders
->__destruct();
161 foreach ( $this as $name => $value ) {
162 unset( $this->$name );
167 * Do various kinds of initialisation on the first call of the parser
169 function firstCallInit() {
170 if ( !$this->mFirstCall
) {
173 $this->mFirstCall
= false;
175 wfProfileIn( __METHOD__
);
177 CoreParserFunctions
::register( $this );
178 CoreTagHooks
::register( $this );
179 $this->initialiseVariables();
181 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
182 wfProfileOut( __METHOD__
);
190 function clearState() {
191 wfProfileIn( __METHOD__
);
192 if ( $this->mFirstCall
) {
193 $this->firstCallInit();
195 $this->mOutput
= new ParserOutput
;
196 $this->mAutonumber
= 0;
197 $this->mLastSection
= '';
198 $this->mDTopen
= false;
199 $this->mIncludeCount
= array();
200 $this->mStripState
= new StripState
;
201 $this->mArgStack
= false;
202 $this->mInPre
= false;
203 $this->mLinkHolders
= new LinkHolderArray( $this );
205 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
206 $this->mVarCache
= array();
209 * Prefix for temporary replacement strings for the multipass parser.
210 * \x07 should never appear in input as it's disallowed in XML.
211 * Using it at the front also gives us a little extra robustness
212 * since it shouldn't match when butted up against identifier-like
215 * Must not consist of all title characters, or else it will change
216 * the behaviour of <nowiki> in a link.
218 # $this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
219 # Changed to \x7f to allow XML double-parsing -- TS
220 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
223 # Clear these on every parse, bug 4549
224 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
226 $this->mShowToc
= true;
227 $this->mForceTocPosition
= false;
228 $this->mIncludeSizes
= array(
232 $this->mPPNodeCount
= 0;
233 $this->mDefaultSort
= false;
234 $this->mHeadings
= array();
235 $this->mDoubleUnderscores
= array();
236 $this->mExpensiveFunctionCount
= 0;
239 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
240 $this->mPreprocessor
= null;
243 wfRunHooks( 'ParserClearState', array( &$this ) );
244 wfProfileOut( __METHOD__
);
247 function setOutputType( $ot ) {
248 $this->mOutputType
= $ot;
251 'html' => $ot == self
::OT_HTML
,
252 'wiki' => $ot == self
::OT_WIKI
,
253 'pre' => $ot == self
::OT_PREPROCESS
,
254 'plain' => $ot == self
::OT_PLAIN
,
259 * Set the context title
261 function setTitle( $t ) {
262 if ( !$t ||
$t instanceof FakeTitle
) {
263 $t = Title
::newFromText( 'NO TITLE' );
266 if ( strval( $t->getFragment() ) !== '' ) {
267 # Strip the fragment to avoid various odd effects
268 $this->mTitle
= clone $t;
269 $this->mTitle
->setFragment( '' );
276 * Accessor for mUniqPrefix.
280 function uniqPrefix() {
281 if ( !isset( $this->mUniqPrefix
) ) {
282 // @todo Fixme: this is probably *horribly wrong*
283 // LanguageConverter seems to want $wgParser's uniqPrefix, however
284 // if this is called for a parser cache hit, the parser may not
285 // have ever been initialized in the first place.
286 // Not really sure what the heck is supposed to be going on here.
288 // throw new MWException( "Accessing uninitialized mUniqPrefix" );
290 return $this->mUniqPrefix
;
294 * Convert wikitext to HTML
295 * Do not call this function recursively.
297 * @param $text String: text we want to parse
298 * @param $title A title object
299 * @param $options ParserOptions
300 * @param $linestart boolean
301 * @param $clearState boolean
302 * @param $revid Int: number to pass in {{REVISIONID}}
303 * @return ParserOutput a ParserOutput
305 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
307 * First pass--just handle <nowiki> sections, pass the rest off
308 * to internalParse() which does all the real work.
311 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang, $wgDisableLangConversion;
312 $fname = __METHOD__
.'-' . wfGetCaller();
313 wfProfileIn( __METHOD__
);
314 wfProfileIn( $fname );
320 $this->mOptions
= $options;
321 $this->setTitle( $title ); // Page title has to be set for the pre-processor
323 $oldRevisionId = $this->mRevisionId
;
324 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
325 if ( $revid !== null ) {
326 $this->mRevisionId
= $revid;
327 $this->mRevisionTimestamp
= null;
329 $this->setOutputType( self
::OT_HTML
);
330 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
332 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
333 $text = $this->internalParse( $text );
335 $text = $this->mStripState
->unstripGeneral( $text );
337 # Clean up special characters, only run once, next-to-last before doBlockLevels
339 # french spaces, last one Guillemet-left
340 # only if there is something before the space
341 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
342 # french spaces, Guillemet-right
343 '/(\\302\\253) /' => '\\1 ',
344 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
346 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
348 $text = $this->doBlockLevels( $text, $linestart );
350 $this->replaceLinkHolders( $text );
352 // The position of the convert() call should not be changed. it
353 // assumes that the links are all replaced and the only thing left
354 // is the <nowiki> mark.
355 if ( !( $wgDisableLangConversion
356 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
357 ||
$this->mTitle
->isTalkPage()
358 ||
$this->mTitle
->isConversionTable() ) ) {
359 $text = $wgContLang->convert( $text );
362 // A title may have been set in a conversion rule.
363 // Note that if a user tries to set a title in a conversion
364 // rule but content conversion was not done, then the parser
365 // won't pick it up. This is probably expected behavior.
366 if ( $wgContLang->getConvRuleTitle() ) {
367 $this->mOutput
->setTitleText( $wgContLang->getConvRuleTitle() );
370 $text = $this->mStripState
->unstripNoWiki( $text );
372 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
374 //!JF Move to its own function
376 $uniq_prefix = $this->mUniqPrefix
;
378 $elements = array_keys( $this->mTransparentTagHooks
);
379 $text = self
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
381 foreach ( $matches as $marker => $data ) {
382 list( $element, $content, $params, $tag ) = $data;
383 $tagName = strtolower( $element );
384 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
385 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
389 $this->mStripState
->general
->setPair( $marker, $output );
391 $text = $this->mStripState
->unstripGeneral( $text );
393 $text = Sanitizer
::normalizeCharReferences( $text );
395 if ( ( $wgUseTidy && $this->mOptions
->mTidy
) ||
$wgAlwaysUseTidy ) {
396 $text = MWTidy
::tidy( $text );
398 # attempt to sanitize at least some nesting problems
399 # (bug #2702 and quite a few others)
401 # ''Something [http://www.cool.com cool''] -->
402 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
403 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
404 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
405 # fix up an anchor inside another anchor, only
406 # at least for a single single nested link (bug 3695)
407 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
408 '\\1\\2</a>\\3</a>\\1\\4</a>',
409 # fix div inside inline elements- doBlockLevels won't wrap a line which
410 # contains a div, so fix it up here; replace
411 # div with escaped text
412 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
413 '\\1\\3<div\\5>\\6</div>\\8\\9',
414 # remove empty italic or bold tag pairs, some
415 # introduced by rules above
416 '/<([bi])><\/\\1>/' => '',
419 $text = preg_replace(
420 array_keys( $tidyregs ),
421 array_values( $tidyregs ),
424 global $wgExpensiveParserFunctionLimit;
425 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
426 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
429 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
431 # Information on include size limits, for the benefit of users who try to skirt them
432 if ( $this->mOptions
->getEnableLimitReport() ) {
433 $max = $this->mOptions
->getMaxIncludeSize();
434 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
436 "NewPP limit report\n" .
437 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
438 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
439 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
441 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
442 $text .= "\n<!-- \n$limitReport-->\n";
444 $this->mOutput
->setText( $text );
446 $this->mRevisionId
= $oldRevisionId;
447 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
448 wfProfileOut( $fname );
449 wfProfileOut( __METHOD__
);
451 return $this->mOutput
;
455 * Recursive parser entry point that can be called from an extension tag
458 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
460 * @param $text String: text extension wants to have parsed
461 * @param PPFrame $frame: The frame to use for expanding any template variables
463 function recursiveTagParse( $text, $frame=false ) {
464 wfProfileIn( __METHOD__
);
465 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
466 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
467 $text = $this->internalParse( $text, false, $frame );
468 wfProfileOut( __METHOD__
);
473 * Expand templates and variables in the text, producing valid, static wikitext.
474 * Also removes comments.
476 function preprocess( $text, $title, $options, $revid = null ) {
477 wfProfileIn( __METHOD__
);
479 $this->setOutputType( self
::OT_PREPROCESS
);
480 $this->mOptions
= $options;
481 $this->setTitle( $title );
482 if ( $revid !== null ) {
483 $this->mRevisionId
= $revid;
485 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
486 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
487 $text = $this->replaceVariables( $text );
488 $text = $this->mStripState
->unstripBoth( $text );
489 wfProfileOut( __METHOD__
);
494 * Process the wikitext for the ?preload= feature. (bug 5210)
496 * <noinclude>, <includeonly> etc. are parsed as for template transclusion,
497 * comments, templates, arguments, tags hooks and parser functions are untouched.
499 public function getPreloadText( $text, $title, $options ) {
500 // Parser (re)initialisation
502 $this->setOutputType( self
::OT_PLAIN
);
503 $this->mOptions
= $options;
504 $this->setTitle( $title );
506 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
507 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
508 return $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
512 * Get a random string
517 function getRandomString() {
518 return dechex( mt_rand( 0, 0x7fffffff ) ) . dechex( mt_rand( 0, 0x7fffffff ) );
521 function &getTitle() { return $this->mTitle
; }
522 function getOptions() { return $this->mOptions
; }
523 function getRevisionId() { return $this->mRevisionId
; }
524 function getOutput() { return $this->mOutput
; }
525 function nextLinkID() { return $this->mLinkID++
; }
527 function getFunctionLang() {
528 global $wgLang, $wgContLang;
530 $target = $this->mOptions
->getTargetLanguage();
531 if ( $target !== null ) {
534 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
539 * Get a preprocessor object
541 function getPreprocessor() {
542 if ( !isset( $this->mPreprocessor
) ) {
543 $class = $this->mPreprocessorClass
;
544 $this->mPreprocessor
= new $class( $this );
546 return $this->mPreprocessor
;
550 * Replaces all occurrences of HTML-style comments and the given tags
551 * in the text with a random marker and returns the next text. The output
552 * parameter $matches will be an associative array filled with data in
554 * 'UNIQ-xxxxx' => array(
557 * array( 'param' => 'x' ),
558 * '<element param="x">tag content</element>' ) )
560 * @param $elements list of element names. Comments are always extracted.
561 * @param $text Source text string.
562 * @param $uniq_prefix
567 function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
572 $taglist = implode( '|', $elements );
573 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
575 while ( $text != '' ) {
576 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
578 if ( count( $p ) < 5 ) {
581 if ( count( $p ) > 5 ) {
595 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
596 $stripped .= $marker;
598 if ( $close === '/>' ) {
599 // Empty element tag, <tag />
604 if ( $element === '!--' ) {
607 $end = "/(<\\/$element\\s*>)/i";
609 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
611 if ( count( $q ) < 3 ) {
612 # No end tag -- let it run out to the end of the text.
621 $matches[$marker] = array( $element,
623 Sanitizer
::decodeTagAttributes( $attributes ),
624 "<$element$attributes$close$content$tail" );
630 * Get a list of strippable XML-like elements
632 function getStripList() {
633 return $this->mStripList
;
637 * @deprecated use replaceVariables
639 function strip( $text, $state, $stripcomments = false , $dontstrip = array() ) {
644 * Restores pre, math, and other extensions removed by strip()
646 * always call unstripNoWiki() after this one
648 * @deprecated use $this->mStripState->unstrip()
650 function unstrip( $text, $state ) {
651 return $state->unstripGeneral( $text );
655 * Always call this after unstrip() to preserve the order
658 * @deprecated use $this->mStripState->unstrip()
660 function unstripNoWiki( $text, $state ) {
661 return $state->unstripNoWiki( $text );
665 * @deprecated use $this->mStripState->unstripBoth()
667 function unstripForHTML( $text ) {
668 return $this->mStripState
->unstripBoth( $text );
672 * Add an item to the strip state
673 * Returns the unique tag which must be inserted into the stripped text
674 * The tag will be replaced with the original text in unstrip()
678 function insertStripItem( $text ) {
679 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
680 $this->mMarkerIndex++
;
681 $this->mStripState
->general
->setPair( $rnd, $text );
686 * Interface with html tidy
687 * @deprecated Use MWTidy::tidy()
689 public static function tidy( $text ) {
690 wfDeprecated( __METHOD__
);
691 return MWTidy
::tidy( $text );
695 * parse the wiki syntax used to render tables
699 function doTableStuff( $text ) {
700 wfProfileIn( __METHOD__
);
702 $lines = StringUtils
::explode( "\n", $text );
704 $td_history = array(); // Is currently a td tag open?
705 $last_tag_history = array(); // Save history of last lag activated (td, th or caption)
706 $tr_history = array(); // Is currently a tr tag open?
707 $tr_attributes = array(); // history of tr attributes
708 $has_opened_tr = array(); // Did this table open a <tr> element?
709 $indent_level = 0; // indent level of the table
711 foreach ( $lines as $outLine ) {
712 $line = trim( $outLine );
714 if ( $line == '' ) { // empty line, go to next line
715 $out .= $outLine."\n";
718 $first_character = $line[0];
721 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
722 // First check if we are starting a new table
723 $indent_level = strlen( $matches[1] );
725 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
726 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
728 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
729 array_push( $td_history , false );
730 array_push( $last_tag_history , '' );
731 array_push( $tr_history , false );
732 array_push( $tr_attributes , '' );
733 array_push( $has_opened_tr , false );
734 } elseif ( count( $td_history ) == 0 ) {
735 // Don't do any of the following
736 $out .= $outLine."\n";
738 } elseif ( substr( $line , 0 , 2 ) === '|}' ) {
739 // We are ending a table
740 $line = '</table>' . substr( $line , 2 );
741 $last_tag = array_pop( $last_tag_history );
743 if ( !array_pop( $has_opened_tr ) ) {
744 $line = "<tr><td></td></tr>{$line}";
747 if ( array_pop( $tr_history ) ) {
748 $line = "</tr>{$line}";
751 if ( array_pop( $td_history ) ) {
752 $line = "</{$last_tag}>{$line}";
754 array_pop( $tr_attributes );
755 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
756 } elseif ( substr( $line , 0 , 2 ) === '|-' ) {
757 // Now we have a table row
758 $line = preg_replace( '#^\|-+#', '', $line );
760 // Whats after the tag is now only attributes
761 $attributes = $this->mStripState
->unstripBoth( $line );
762 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
763 array_pop( $tr_attributes );
764 array_push( $tr_attributes, $attributes );
767 $last_tag = array_pop( $last_tag_history );
768 array_pop( $has_opened_tr );
769 array_push( $has_opened_tr , true );
771 if ( array_pop( $tr_history ) ) {
775 if ( array_pop( $td_history ) ) {
776 $line = "</{$last_tag}>{$line}";
780 array_push( $tr_history , false );
781 array_push( $td_history , false );
782 array_push( $last_tag_history , '' );
783 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line , 0 , 2 ) === '|+' ) {
784 // This might be cell elements, td, th or captions
785 if ( substr( $line , 0 , 2 ) === '|+' ) {
786 $first_character = '+';
787 $line = substr( $line , 1 );
790 $line = substr( $line , 1 );
792 if ( $first_character === '!' ) {
793 $line = str_replace( '!!' , '||' , $line );
796 // Split up multiple cells on the same line.
797 // FIXME : This can result in improper nesting of tags processed
798 // by earlier parser steps, but should avoid splitting up eg
799 // attribute values containing literal "||".
800 $cells = StringUtils
::explodeMarkup( '||' , $line );
804 // Loop through each table cell
805 foreach ( $cells as $cell ) {
807 if ( $first_character !== '+' ) {
808 $tr_after = array_pop( $tr_attributes );
809 if ( !array_pop( $tr_history ) ) {
810 $previous = "<tr{$tr_after}>\n";
812 array_push( $tr_history , true );
813 array_push( $tr_attributes , '' );
814 array_pop( $has_opened_tr );
815 array_push( $has_opened_tr , true );
818 $last_tag = array_pop( $last_tag_history );
820 if ( array_pop( $td_history ) ) {
821 $previous = "</{$last_tag}>{$previous}";
824 if ( $first_character === '|' ) {
826 } elseif ( $first_character === '!' ) {
828 } elseif ( $first_character === '+' ) {
829 $last_tag = 'caption';
834 array_push( $last_tag_history , $last_tag );
836 // A cell could contain both parameters and data
837 $cell_data = explode( '|' , $cell , 2 );
839 // Bug 553: Note that a '|' inside an invalid link should not
840 // be mistaken as delimiting cell parameters
841 if ( strpos( $cell_data[0], '[[' ) !== false ) {
842 $cell = "{$previous}<{$last_tag}>{$cell}";
843 } elseif ( count( $cell_data ) == 1 ) {
844 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
846 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
847 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
848 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
852 array_push( $td_history , true );
855 $out .= $outLine . "\n";
858 // Closing open td, tr && table
859 while ( count( $td_history ) > 0 ) {
860 if ( array_pop( $td_history ) ) {
863 if ( array_pop( $tr_history ) ) {
866 if ( !array_pop( $has_opened_tr ) ) {
867 $out .= "<tr><td></td></tr>\n" ;
870 $out .= "</table>\n";
873 // Remove trailing line-ending (b/c)
874 if ( substr( $out, -1 ) === "\n" ) {
875 $out = substr( $out, 0, -1 );
878 // special case: don't return empty table
879 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
883 wfProfileOut( __METHOD__
);
889 * Helper function for parse() that transforms wiki markup into
890 * HTML. Only called for $mOutputType == self::OT_HTML.
894 function internalParse( $text, $isMain = true, $frame=false ) {
895 wfProfileIn( __METHOD__
);
899 # Hook to suspend the parser in this state
900 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
901 wfProfileOut( __METHOD__
);
905 // if $frame is provided, then use $frame for replacing any variables
907 // use frame depth to infer how include/noinclude tags should be handled
908 // depth=0 means this is the top-level document; otherwise it's an included document
909 if ( !$frame->depth
) {
912 $flag = Parser
::PTD_FOR_INCLUSION
;
913 $dom = $this->preprocessToDom( $text, $flag );
914 $text = $frame->expand( $dom );
917 // if $frame is not provided, then use old-style replaceVariables
918 $text = $this->replaceVariables( $text );
921 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
922 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
924 // Tables need to come after variable replacement for things to work
925 // properly; putting them before other transformations should keep
926 // exciting things like link expansions from showing up in surprising
928 $text = $this->doTableStuff( $text );
930 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
932 $text = $this->doDoubleUnderscore( $text );
934 $text = $this->doHeadings( $text );
935 if ( $this->mOptions
->getUseDynamicDates() ) {
936 $df = DateFormatter
::getInstance();
937 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
939 $text = $this->doAllQuotes( $text );
940 $text = $this->replaceInternalLinks( $text );
941 $text = $this->replaceExternalLinks( $text );
943 # replaceInternalLinks may sometimes leave behind
944 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
945 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
947 $text = $this->doMagicLinks( $text );
948 $text = $this->formatHeadings( $text, $origText, $isMain );
950 wfProfileOut( __METHOD__
);
955 * Replace special strings like "ISBN xxx" and "RFC xxx" with
956 * magic external links.
961 function doMagicLinks( $text ) {
962 wfProfileIn( __METHOD__
);
963 $prots = $this->mUrlProtocols
;
964 $urlChar = self
::EXT_LINK_URL_CLASS
;
965 $text = preg_replace_callback(
967 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
968 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
969 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
970 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
971 ISBN\s+(\b # m[5]: ISBN, capture number
972 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
973 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
974 [0-9Xx] # check digit
976 )!x', array( &$this, 'magicLinkCallback' ), $text );
977 wfProfileOut( __METHOD__
);
981 function magicLinkCallback( $m ) {
982 if ( isset( $m[1] ) && $m[1] !== '' ) {
985 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
988 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
990 return $this->makeFreeExternalLink( $m[0] );
991 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
994 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
997 $CssClass = 'mw-magiclink-rfc';
999 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1001 $urlmsg = 'pubmedurl';
1002 $CssClass = 'mw-magiclink-pmid';
1005 throw new MWException( __METHOD__
.': unrecognised match type "' .
1006 substr( $m[0], 0, 20 ) . '"' );
1008 $url = wfMsg( $urlmsg, $id);
1009 $sk = $this->mOptions
->getSkin();
1010 $la = $sk->getExternalLinkAttributes( "external $CssClass" );
1011 return "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1012 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1015 $num = strtr( $isbn, array(
1020 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1022 $titleObj->escapeLocalUrl() .
1023 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1030 * Make a free external link, given a user-supplied URL
1034 function makeFreeExternalLink( $url ) {
1036 wfProfileIn( __METHOD__
);
1038 $sk = $this->mOptions
->getSkin();
1041 # The characters '<' and '>' (which were escaped by
1042 # removeHTMLtags()) should not be included in
1043 # URLs, per RFC 2396.
1045 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1046 $trail = substr( $url, $m2[0][1] ) . $trail;
1047 $url = substr( $url, 0, $m2[0][1] );
1050 # Move trailing punctuation to $trail
1052 # If there is no left bracket, then consider right brackets fair game too
1053 if ( strpos( $url, '(' ) === false ) {
1057 $numSepChars = strspn( strrev( $url ), $sep );
1058 if ( $numSepChars ) {
1059 $trail = substr( $url, -$numSepChars ) . $trail;
1060 $url = substr( $url, 0, -$numSepChars );
1063 $url = Sanitizer
::cleanUrl( $url );
1065 # Is this an external image?
1066 $text = $this->maybeMakeExternalImage( $url );
1067 if ( $text === false ) {
1068 # Not an image, make a link
1069 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1070 $this->getExternalLinkAttribs( $url ) );
1071 # Register it in the output object...
1072 # Replace unnecessary URL escape codes with their equivalent characters
1073 $pasteurized = self
::replaceUnusualEscapes( $url );
1074 $this->mOutput
->addExternalLink( $pasteurized );
1076 wfProfileOut( __METHOD__
);
1077 return $text . $trail;
1082 * Parse headers and return html
1086 function doHeadings( $text ) {
1087 wfProfileIn( __METHOD__
);
1088 for ( $i = 6; $i >= 1; --$i ) {
1089 $h = str_repeat( '=', $i );
1090 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1091 "<h$i>\\1</h$i>", $text );
1093 wfProfileOut( __METHOD__
);
1098 * Replace single quotes with HTML markup
1100 * @return string the altered text
1102 function doAllQuotes( $text ) {
1103 wfProfileIn( __METHOD__
);
1105 $lines = StringUtils
::explode( "\n", $text );
1106 foreach ( $lines as $line ) {
1107 $outtext .= $this->doQuotes( $line ) . "\n";
1109 $outtext = substr( $outtext, 0,-1 );
1110 wfProfileOut( __METHOD__
);
1115 * Helper function for doAllQuotes()
1117 public function doQuotes( $text ) {
1118 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1119 if ( count( $arr ) == 1 ) {
1122 # First, do some preliminary work. This may shift some apostrophes from
1123 # being mark-up to being text. It also counts the number of occurrences
1124 # of bold and italics mark-ups.
1128 foreach ( $arr as $r ) {
1129 if ( ( $i %
2 ) == 1 ) {
1130 # If there are ever four apostrophes, assume the first is supposed to
1131 # be text, and the remaining three constitute mark-up for bold text.
1132 if ( strlen( $arr[$i] ) == 4 ) {
1135 } elseif ( strlen( $arr[$i] ) > 5 ) {
1136 # If there are more than 5 apostrophes in a row, assume they're all
1137 # text except for the last 5.
1138 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1141 # Count the number of occurrences of bold and italics mark-ups.
1142 # We are not counting sequences of five apostrophes.
1143 if ( strlen( $arr[$i] ) == 2 ) {
1145 } elseif ( strlen( $arr[$i] ) == 3 ) {
1147 } elseif ( strlen( $arr[$i] ) == 5 ) {
1155 # If there is an odd number of both bold and italics, it is likely
1156 # that one of the bold ones was meant to be an apostrophe followed
1157 # by italics. Which one we cannot know for certain, but it is more
1158 # likely to be one that has a single-letter word before it.
1159 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1161 $firstsingleletterword = -1;
1162 $firstmultiletterword = -1;
1164 foreach ( $arr as $r ) {
1165 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1166 $x1 = substr( $arr[$i-1], -1 );
1167 $x2 = substr( $arr[$i-1], -2, 1 );
1168 if ( $x1 === ' ' ) {
1169 if ( $firstspace == -1 ) {
1172 } elseif ( $x2 === ' ') {
1173 if ( $firstsingleletterword == -1 ) {
1174 $firstsingleletterword = $i;
1177 if ( $firstmultiletterword == -1 ) {
1178 $firstmultiletterword = $i;
1185 # If there is a single-letter word, use it!
1186 if ( $firstsingleletterword > -1 ) {
1187 $arr[$firstsingleletterword] = "''";
1188 $arr[$firstsingleletterword-1] .= "'";
1189 } elseif ( $firstmultiletterword > -1 ) {
1190 # If not, but there's a multi-letter word, use that one.
1191 $arr[$firstmultiletterword] = "''";
1192 $arr[$firstmultiletterword-1] .= "'";
1193 } elseif ( $firstspace > -1 ) {
1194 # ... otherwise use the first one that has neither.
1195 # (notice that it is possible for all three to be -1 if, for example,
1196 # there is only one pentuple-apostrophe in the line)
1197 $arr[$firstspace] = "''";
1198 $arr[$firstspace-1] .= "'";
1202 # Now let's actually convert our apostrophic mush to HTML!
1207 foreach ( $arr as $r ) {
1208 if ( ( $i %
2 ) == 0 ) {
1209 if ( $state === 'both' ) {
1215 if ( strlen( $r ) == 2 ) {
1216 if ( $state === 'i' ) {
1217 $output .= '</i>'; $state = '';
1218 } elseif ( $state === 'bi' ) {
1219 $output .= '</i>'; $state = 'b';
1220 } elseif ( $state === 'ib' ) {
1221 $output .= '</b></i><b>'; $state = 'b';
1222 } elseif ( $state === 'both' ) {
1223 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1224 } else { # $state can be 'b' or ''
1225 $output .= '<i>'; $state .= 'i';
1227 } elseif ( strlen( $r ) == 3 ) {
1228 if ( $state === 'b' ) {
1229 $output .= '</b>'; $state = '';
1230 } elseif ( $state === 'bi' ) {
1231 $output .= '</i></b><i>'; $state = 'i';
1232 } elseif ( $state === 'ib' ) {
1233 $output .= '</b>'; $state = 'i';
1234 } elseif ( $state === 'both' ) {
1235 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1236 } else { # $state can be 'i' or ''
1237 $output .= '<b>'; $state .= 'b';
1239 } elseif ( strlen( $r ) == 5 ) {
1240 if ( $state === 'b' ) {
1241 $output .= '</b><i>'; $state = 'i';
1242 } elseif ( $state === 'i' ) {
1243 $output .= '</i><b>'; $state = 'b';
1244 } elseif ( $state === 'bi' ) {
1245 $output .= '</i></b>'; $state = '';
1246 } elseif ( $state === 'ib' ) {
1247 $output .= '</b></i>'; $state = '';
1248 } elseif ( $state === 'both' ) {
1249 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1250 } else { # ($state == '')
1251 $buffer = ''; $state = 'both';
1257 # Now close all remaining tags. Notice that the order is important.
1258 if ( $state === 'b' ||
$state === 'ib' ) {
1261 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1264 if ( $state === 'bi' ) {
1267 # There might be lonely ''''', so make sure we have a buffer
1268 if ( $state === 'both' && $buffer ) {
1269 $output .= '<b><i>'.$buffer.'</i></b>';
1276 * Replace external links (REL)
1278 * Note: this is all very hackish and the order of execution matters a lot.
1279 * Make sure to run maintenance/parserTests.php if you change this code.
1283 function replaceExternalLinks( $text ) {
1285 wfProfileIn( __METHOD__
);
1287 $sk = $this->mOptions
->getSkin();
1289 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1290 $s = array_shift( $bits );
1293 while ( $i<count( $bits ) ) {
1295 $protocol = $bits[$i++
];
1296 $text = $bits[$i++
];
1297 $trail = $bits[$i++
];
1299 # The characters '<' and '>' (which were escaped by
1300 # removeHTMLtags()) should not be included in
1301 # URLs, per RFC 2396.
1303 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1304 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1305 $url = substr( $url, 0, $m2[0][1] );
1308 # If the link text is an image URL, replace it with an <img> tag
1309 # This happened by accident in the original parser, but some people used it extensively
1310 $img = $this->maybeMakeExternalImage( $text );
1311 if ( $img !== false ) {
1317 # Set linktype for CSS - if URL==text, link is essentially free
1318 $linktype = ( $text === $url ) ?
'free' : 'text';
1320 # No link text, e.g. [http://domain.tld/some.link]
1321 if ( $text == '' ) {
1322 # Autonumber if allowed. See bug #5918
1323 if ( strpos( wfUrlProtocols(), substr( $protocol, 0, strpos( $protocol, ':' ) ) ) !== false ) {
1324 $langObj = $this->getFunctionLang();
1325 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1326 $linktype = 'autonumber';
1328 # Otherwise just use the URL
1329 $text = htmlspecialchars( $url );
1333 # Have link text, e.g. [http://domain.tld/some.link text]s
1335 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1338 $text = $wgContLang->markNoConversion( $text );
1340 $url = Sanitizer
::cleanUrl( $url );
1342 # Use the encoded URL
1343 # This means that users can paste URLs directly into the text
1344 # Funny characters like ö aren't valid in URLs anyway
1345 # This was changed in August 2004
1346 $s .= $sk->makeExternalLink( $url, $text, false, $linktype,
1347 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1349 # Register link in the output object.
1350 # Replace unnecessary URL escape codes with the referenced character
1351 # This prevents spammers from hiding links from the filters
1352 $pasteurized = self
::replaceUnusualEscapes( $url );
1353 $this->mOutput
->addExternalLink( $pasteurized );
1356 wfProfileOut( __METHOD__
);
1361 * Get an associative array of additional HTML attributes appropriate for a
1362 * particular external link. This currently may include rel => nofollow
1363 * (depending on configuration, namespace, and the URL's domain) and/or a
1364 * target attribute (depending on configuration).
1366 * @param string $url Optional URL, to extract the domain from for rel =>
1367 * nofollow if appropriate
1368 * @return array Associative array of HTML attributes
1370 function getExternalLinkAttribs( $url = false ) {
1372 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1373 $ns = $this->mTitle
->getNamespace();
1374 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) ) {
1375 $attribs['rel'] = 'nofollow';
1377 global $wgNoFollowDomainExceptions;
1378 if ( $wgNoFollowDomainExceptions ) {
1379 $bits = wfParseUrl( $url );
1380 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1381 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1382 if ( substr( $bits['host'], -strlen( $domain ) ) == $domain ) {
1383 unset( $attribs['rel'] );
1390 if ( $this->mOptions
->getExternalLinkTarget() ) {
1391 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1398 * Replace unusual URL escape codes with their equivalent characters
1402 * @todo This can merge genuinely required bits in the path or query string,
1403 * breaking legit URLs. A proper fix would treat the various parts of
1404 * the URL differently; as a workaround, just use the output for
1405 * statistical records, not for actual linking/output.
1407 static function replaceUnusualEscapes( $url ) {
1408 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1409 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1413 * Callback function used in replaceUnusualEscapes().
1414 * Replaces unusual URL escape codes with their equivalent character
1418 private static function replaceUnusualEscapesCallback( $matches ) {
1419 $char = urldecode( $matches[0] );
1420 $ord = ord( $char );
1421 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1422 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1423 // No, shouldn't be escaped
1426 // Yes, leave it escaped
1432 * make an image if it's allowed, either through the global
1433 * option, through the exception, or through the on-wiki whitelist
1436 function maybeMakeExternalImage( $url ) {
1437 $sk = $this->mOptions
->getSkin();
1438 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1439 $imagesexception = !empty( $imagesfrom );
1441 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1442 if ( $imagesexception && is_array( $imagesfrom ) ) {
1443 $imagematch = false;
1444 foreach ( $imagesfrom as $match ) {
1445 if ( strpos( $url, $match ) === 0 ) {
1450 } elseif ( $imagesexception ) {
1451 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1453 $imagematch = false;
1455 if ( $this->mOptions
->getAllowExternalImages()
1456 ||
( $imagesexception && $imagematch ) ) {
1457 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1459 $text = $sk->makeExternalImage( $url );
1462 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1463 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1464 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1465 foreach ( $whitelist as $entry ) {
1466 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1467 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1470 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1471 # Image matches a whitelist entry
1472 $text = $sk->makeExternalImage( $url );
1481 * Process [[ ]] wikilinks
1482 * @return processed text
1486 function replaceInternalLinks( $s ) {
1487 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1492 * Process [[ ]] wikilinks (RIL)
1493 * @return LinkHolderArray
1497 function replaceInternalLinks2( &$s ) {
1500 wfProfileIn( __METHOD__
);
1502 wfProfileIn( __METHOD__
.'-setup' );
1503 static $tc = FALSE, $e1, $e1_img;
1504 # the % is needed to support urlencoded titles as well
1506 $tc = Title
::legalChars() . '#%';
1507 # Match a link having the form [[namespace:link|alternate]]trail
1508 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1509 # Match cases where there is no "]]", which might still be images
1510 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1513 $sk = $this->mOptions
->getSkin();
1514 $holders = new LinkHolderArray( $this );
1516 # split the entire text string on occurences of [[
1517 $a = StringUtils
::explode( '[[', ' ' . $s );
1518 # get the first element (all text up to first [[), and remove the space we added
1521 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1522 $s = substr( $s, 1 );
1524 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1526 if ( $useLinkPrefixExtension ) {
1527 # Match the end of a line for a word that's not followed by whitespace,
1528 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1529 $e2 = wfMsgForContent( 'linkprefix' );
1532 if ( is_null( $this->mTitle
) ) {
1533 wfProfileOut( __METHOD__
.'-setup' );
1534 wfProfileOut( __METHOD__
);
1535 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1537 $nottalk = !$this->mTitle
->isTalkPage();
1539 if ( $useLinkPrefixExtension ) {
1541 if ( preg_match( $e2, $s, $m ) ) {
1542 $first_prefix = $m[2];
1544 $first_prefix = false;
1550 if ( $wgContLang->hasVariants() ) {
1551 $selflink = $wgContLang->convertLinkToAllVariants( $this->mTitle
->getPrefixedText() );
1553 $selflink = array( $this->mTitle
->getPrefixedText() );
1555 $useSubpages = $this->areSubpagesAllowed();
1556 wfProfileOut( __METHOD__
.'-setup' );
1558 # Loop for each link
1559 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1560 # Check for excessive memory usage
1561 if ( $holders->isBig() ) {
1563 # Do the existence check, replace the link holders and clear the array
1564 $holders->replace( $s );
1568 if ( $useLinkPrefixExtension ) {
1569 wfProfileIn( __METHOD__
.'-prefixhandling' );
1570 if ( preg_match( $e2, $s, $m ) ) {
1577 if ( $first_prefix ) {
1578 $prefix = $first_prefix;
1579 $first_prefix = false;
1581 wfProfileOut( __METHOD__
.'-prefixhandling' );
1584 $might_be_img = false;
1586 wfProfileIn( __METHOD__
."-e1" );
1587 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1589 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1590 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1591 # the real problem is with the $e1 regex
1594 # Still some problems for cases where the ] is meant to be outside punctuation,
1595 # and no image is in sight. See bug 2095.
1597 if ( $text !== '' &&
1598 substr( $m[3], 0, 1 ) === ']' &&
1599 strpos( $text, '[' ) !== false
1602 $text .= ']'; # so that replaceExternalLinks($text) works later
1603 $m[3] = substr( $m[3], 1 );
1605 # fix up urlencoded title texts
1606 if ( strpos( $m[1], '%' ) !== false ) {
1607 # Should anchors '#' also be rejected?
1608 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode( $m[1] ) );
1611 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1612 $might_be_img = true;
1614 if ( strpos( $m[1], '%' ) !== false ) {
1615 $m[1] = urldecode( $m[1] );
1618 } else { # Invalid form; output directly
1619 $s .= $prefix . '[[' . $line ;
1620 wfProfileOut( __METHOD__
."-e1" );
1623 wfProfileOut( __METHOD__
."-e1" );
1624 wfProfileIn( __METHOD__
."-misc" );
1626 # Don't allow internal links to pages containing
1627 # PROTO: where PROTO is a valid URL protocol; these
1628 # should be external links.
1629 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1630 $s .= $prefix . '[[' . $line ;
1631 wfProfileOut( __METHOD__
."-misc" );
1635 # Make subpage if necessary
1636 if ( $useSubpages ) {
1637 $link = $this->maybeDoSubpageLink( $m[1], $text );
1642 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1644 # Strip off leading ':'
1645 $link = substr( $link, 1 );
1648 wfProfileOut( __METHOD__
."-misc" );
1649 wfProfileIn( __METHOD__
."-title" );
1650 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1651 if ( $nt === null ) {
1652 $s .= $prefix . '[[' . $line;
1653 wfProfileOut( __METHOD__
."-title" );
1657 $ns = $nt->getNamespace();
1658 $iw = $nt->getInterWiki();
1659 wfProfileOut( __METHOD__
."-title" );
1661 if ( $might_be_img ) { # if this is actually an invalid link
1662 wfProfileIn( __METHOD__
."-might_be_img" );
1663 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1666 # look at the next 'line' to see if we can close it there
1668 $next_line = $a->current();
1669 if ( $next_line === false ||
$next_line === null ) {
1672 $m = explode( ']]', $next_line, 3 );
1673 if ( count( $m ) == 3 ) {
1674 # the first ]] closes the inner link, the second the image
1676 $text .= "[[{$m[0]}]]{$m[1]}";
1679 } elseif ( count( $m ) == 2 ) {
1680 # if there's exactly one ]] that's fine, we'll keep looking
1681 $text .= "[[{$m[0]}]]{$m[1]}";
1683 # if $next_line is invalid too, we need look no further
1684 $text .= '[[' . $next_line;
1689 # we couldn't find the end of this imageLink, so output it raw
1690 # but don't ignore what might be perfectly normal links in the text we've examined
1691 $holders->merge( $this->replaceInternalLinks2( $text ) );
1692 $s .= "{$prefix}[[$link|$text";
1693 # note: no $trail, because without an end, there *is* no trail
1694 wfProfileOut( __METHOD__
."-might_be_img" );
1697 } else { # it's not an image, so output it raw
1698 $s .= "{$prefix}[[$link|$text";
1699 # note: no $trail, because without an end, there *is* no trail
1700 wfProfileOut( __METHOD__
."-might_be_img" );
1703 wfProfileOut( __METHOD__
."-might_be_img" );
1706 $wasblank = ( $text == '' );
1711 # Link not escaped by : , create the various objects
1715 wfProfileIn( __METHOD__
."-interwiki" );
1716 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1717 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1718 $s = rtrim( $s . $prefix );
1719 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1720 wfProfileOut( __METHOD__
."-interwiki" );
1723 wfProfileOut( __METHOD__
."-interwiki" );
1725 if ( $ns == NS_FILE
) {
1726 wfProfileIn( __METHOD__
."-image" );
1727 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1729 # if no parameters were passed, $text
1730 # becomes something like "File:Foo.png",
1731 # which we don't want to pass on to the
1735 # recursively parse links inside the image caption
1736 # actually, this will parse them in any other parameters, too,
1737 # but it might be hard to fix that, and it doesn't matter ATM
1738 $text = $this->replaceExternalLinks( $text );
1739 $holders->merge( $this->replaceInternalLinks2( $text ) );
1741 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1742 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1744 $s .= $prefix . $trail;
1746 $this->mOutput
->addImage( $nt->getDBkey() );
1747 wfProfileOut( __METHOD__
."-image" );
1752 if ( $ns == NS_CATEGORY
) {
1753 wfProfileIn( __METHOD__
."-category" );
1754 $s = rtrim( $s . "\n" ); # bug 87
1757 $sortkey = $this->getDefaultSort();
1761 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1762 $sortkey = str_replace( "\n", '', $sortkey );
1763 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1764 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1767 * Strip the whitespace Category links produce, see bug 87
1768 * @todo We might want to use trim($tmp, "\n") here.
1770 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'': $prefix . $trail;
1772 wfProfileOut( __METHOD__
."-category" );
1777 # Self-link checking
1778 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1779 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1780 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1785 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1786 # FIXME: Should do batch file existence checks, see comment below
1787 if ( $ns == NS_MEDIA
) {
1788 wfProfileIn( __METHOD__
."-media" );
1789 # Give extensions a chance to select the file revision for us
1790 $skip = $time = false;
1791 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1793 $link = $sk->link( $nt );
1795 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1797 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1798 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1799 $this->mOutput
->addImage( $nt->getDBkey() );
1800 wfProfileOut( __METHOD__
."-media" );
1804 wfProfileIn( __METHOD__
."-always_known" );
1805 # Some titles, such as valid special pages or files in foreign repos, should
1806 # be shown as bluelinks even though they're not included in the page table
1808 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1809 # batch file existence checks for NS_FILE and NS_MEDIA
1810 if ( $iw == '' && $nt->isAlwaysKnown() ) {
1811 $this->mOutput
->addLink( $nt );
1812 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1814 # Links will be added to the output link list after checking
1815 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1817 wfProfileOut( __METHOD__
."-always_known" );
1819 wfProfileOut( __METHOD__
);
1824 * Make a link placeholder. The text returned can be later resolved to a real link with
1825 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1826 * parsing of interwiki links, and secondly to allow all existence checks and
1827 * article length checks (for stub links) to be bundled into a single query.
1831 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1832 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1836 * Render a forced-blue link inline; protect against double expansion of
1837 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1838 * Since this little disaster has to split off the trail text to avoid
1839 * breaking URLs in the following text without breaking trails on the
1840 * wiki links, it's been made into a horrible function.
1843 * @param string $text
1844 * @param string $query
1845 * @param string $trail
1846 * @param string $prefix
1847 * @return string HTML-wikitext mix oh yuck
1849 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1850 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1851 $sk = $this->mOptions
->getSkin();
1852 // FIXME: use link() instead of deprecated makeKnownLinkObj()
1853 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1854 return $this->armorLinks( $link ) . $trail;
1858 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1859 * going to go through further parsing steps before inline URL expansion.
1861 * Not needed quite as much as it used to be since free links are a bit
1862 * more sensible these days. But bracketed links are still an issue.
1864 * @param string more-or-less HTML
1865 * @return string less-or-more HTML with NOPARSE bits
1867 function armorLinks( $text ) {
1868 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1869 "{$this->mUniqPrefix}NOPARSE$1", $text );
1873 * Return true if subpage links should be expanded on this page.
1876 function areSubpagesAllowed() {
1877 # Some namespaces don't allow subpages
1878 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
1882 * Handle link to subpage if necessary
1883 * @param string $target the source of the link
1884 * @param string &$text the link text, modified as necessary
1885 * @return string the full name of the link
1888 function maybeDoSubpageLink( $target, &$text ) {
1889 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
1893 * Used by doBlockLevels()
1896 /* private */ function closeParagraph() {
1898 if ( $this->mLastSection
!= '' ) {
1899 $result = '</' . $this->mLastSection
. ">\n";
1901 $this->mInPre
= false;
1902 $this->mLastSection
= '';
1906 * getCommon() returns the length of the longest common substring
1907 * of both arguments, starting at the beginning of both.
1910 function getCommon( $st1, $st2 ) {
1911 $fl = strlen( $st1 );
1912 $shorter = strlen( $st2 );
1913 if ( $fl < $shorter ) {
1917 for ( $i = 0; $i < $shorter; ++
$i ) {
1918 if ( $st1{$i} != $st2{$i} ) {
1925 * These next three functions open, continue, and close the list
1926 * element appropriate to the prefix character passed into them.
1929 function openList( $char ) {
1930 $result = $this->closeParagraph();
1932 if ( '*' === $char ) {
1933 $result .= '<ul><li>';
1934 } elseif ( '#' === $char ) {
1935 $result .= '<ol><li>';
1936 } elseif ( ':' === $char ) {
1937 $result .= '<dl><dd>';
1938 } elseif ( ';' === $char ) {
1939 $result .= '<dl><dt>';
1940 $this->mDTopen
= true;
1942 $result = '<!-- ERR 1 -->';
1948 /* private */ 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 -->';
1967 /* private */ function closeList( $char ) {
1968 if ( '*' === $char ) {
1969 $text = '</li></ul>';
1970 } elseif ( '#' === $char ) {
1971 $text = '</li></ol>';
1972 } elseif ( ':' === $char ) {
1973 if ( $this->mDTopen
) {
1974 $this->mDTopen
= false;
1975 $text = '</dt></dl>';
1977 $text = '</dd></dl>';
1980 return '<!-- ERR 3 -->';
1987 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
1989 * @param $linestart bool whether or not this is at the start of a line.
1991 * @return string the lists rendered as HTML
1993 function doBlockLevels( $text, $linestart ) {
1994 wfProfileIn( __METHOD__
);
1996 # Parsing through the text line by line. The main thing
1997 # happening here is handling of block-level elements p, pre,
1998 # and making lists from lines starting with * # : etc.
2000 $textLines = StringUtils
::explode( "\n", $text );
2002 $lastPrefix = $output = '';
2003 $this->mDTopen
= $inBlockElem = false;
2005 $paragraphStack = false;
2007 foreach ( $textLines as $oLine ) {
2009 if ( !$linestart ) {
2019 $lastPrefixLength = strlen( $lastPrefix );
2020 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2021 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2022 // If not in a <pre> element, scan for and figure out what prefixes are there.
2023 if ( !$this->mInPre
) {
2024 # Multiple prefixes may abut each other for nested lists.
2025 $prefixLength = strspn( $oLine, '*#:;' );
2026 $prefix = substr( $oLine, 0, $prefixLength );
2029 // ; and : are both from definition-lists, so they're equivalent
2030 // for the purposes of determining whether or not we need to open/close
2032 $prefix2 = str_replace( ';', ':', $prefix );
2033 $t = substr( $oLine, $prefixLength );
2034 $this->mInPre
= (bool)$preOpenMatch;
2036 # Don't interpret any other prefixes in preformatted text
2038 $prefix = $prefix2 = '';
2043 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2044 # Same as the last item, so no need to deal with nesting or opening stuff
2045 $output .= $this->nextItem( substr( $prefix, -1 ) );
2046 $paragraphStack = false;
2048 if ( substr( $prefix, -1 ) === ';') {
2049 # The one nasty exception: definition lists work like this:
2050 # ; title : definition text
2051 # So we check for : in the remainder text to split up the
2052 # title and definition, without b0rking links.
2054 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2056 $output .= $term . $this->nextItem( ':' );
2059 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2060 // We need to open or close prefixes, or both.
2062 # Either open or close a level...
2063 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2064 $paragraphStack = false;
2066 // Close all the prefixes which aren't shared.
2067 while ( $commonPrefixLength < $lastPrefixLength ) {
2068 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2069 --$lastPrefixLength;
2072 // Continue the current prefix if appropriate.
2073 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2074 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2077 // Open prefixes where appropriate.
2078 while ( $prefixLength > $commonPrefixLength ) {
2079 $char = substr( $prefix, $commonPrefixLength, 1 );
2080 $output .= $this->openList( $char );
2082 if ( ';' === $char ) {
2083 # FIXME: This is dupe of code above
2084 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2086 $output .= $term . $this->nextItem( ':' );
2089 ++
$commonPrefixLength;
2091 $lastPrefix = $prefix2;
2094 // If we have no prefixes, go to paragraph mode.
2095 if ( 0 == $prefixLength ) {
2096 wfProfileIn( __METHOD__
."-paragraph" );
2097 # No prefix (not in list)--go to paragraph mode
2098 // XXX: use a stack for nestable elements like span, table and div
2099 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2100 $closematch = preg_match(
2101 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2102 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2103 if ( $openmatch or $closematch ) {
2104 $paragraphStack = false;
2105 #Â TODO bug 5718: paragraph closed
2106 $output .= $this->closeParagraph();
2107 if ( $preOpenMatch and !$preCloseMatch ) {
2108 $this->mInPre
= true;
2110 if ( $closematch ) {
2111 $inBlockElem = false;
2113 $inBlockElem = true;
2115 } elseif ( !$inBlockElem && !$this->mInPre
) {
2116 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2118 if ( $this->mLastSection
!== 'pre' ) {
2119 $paragraphStack = false;
2120 $output .= $this->closeParagraph().'<pre>';
2121 $this->mLastSection
= 'pre';
2123 $t = substr( $t, 1 );
2126 if ( trim( $t ) == '' ) {
2127 if ( $paragraphStack ) {
2128 $output .= $paragraphStack.'<br />';
2129 $paragraphStack = false;
2130 $this->mLastSection
= 'p';
2132 if ( $this->mLastSection
!== 'p' ) {
2133 $output .= $this->closeParagraph();
2134 $this->mLastSection
= '';
2135 $paragraphStack = '<p>';
2137 $paragraphStack = '</p><p>';
2141 if ( $paragraphStack ) {
2142 $output .= $paragraphStack;
2143 $paragraphStack = false;
2144 $this->mLastSection
= 'p';
2145 } elseif ( $this->mLastSection
!== 'p' ) {
2146 $output .= $this->closeParagraph().'<p>';
2147 $this->mLastSection
= 'p';
2152 wfProfileOut( __METHOD__
."-paragraph" );
2154 // somewhere above we forget to get out of pre block (bug 785)
2155 if ( $preCloseMatch && $this->mInPre
) {
2156 $this->mInPre
= false;
2158 if ( $paragraphStack === false ) {
2162 while ( $prefixLength ) {
2163 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2166 if ( $this->mLastSection
!= '' ) {
2167 $output .= '</' . $this->mLastSection
. '>';
2168 $this->mLastSection
= '';
2171 wfProfileOut( __METHOD__
);
2176 * Split up a string on ':', ignoring any occurences inside tags
2177 * to prevent illegal overlapping.
2178 * @param string $str the string to split
2179 * @param string &$before set to everything before the ':'
2180 * @param string &$after set to everything after the ':'
2181 * return string the position of the ':', or false if none found
2183 function findColonNoLinks( $str, &$before, &$after ) {
2184 wfProfileIn( __METHOD__
);
2186 $pos = strpos( $str, ':' );
2187 if ( $pos === false ) {
2189 wfProfileOut( __METHOD__
);
2193 $lt = strpos( $str, '<' );
2194 if ( $lt === false ||
$lt > $pos ) {
2195 // Easy; no tag nesting to worry about
2196 $before = substr( $str, 0, $pos );
2197 $after = substr( $str, $pos+
1 );
2198 wfProfileOut( __METHOD__
);
2202 // Ugly state machine to walk through avoiding tags.
2203 $state = self
::COLON_STATE_TEXT
;
2205 $len = strlen( $str );
2206 for( $i = 0; $i < $len; $i++
) {
2210 // (Using the number is a performance hack for common cases)
2211 case 0: // self::COLON_STATE_TEXT:
2214 // Could be either a <start> tag or an </end> tag
2215 $state = self
::COLON_STATE_TAGSTART
;
2218 if ( $stack == 0 ) {
2220 $before = substr( $str, 0, $i );
2221 $after = substr( $str, $i +
1 );
2222 wfProfileOut( __METHOD__
);
2225 // Embedded in a tag; don't break it.
2228 // Skip ahead looking for something interesting
2229 $colon = strpos( $str, ':', $i );
2230 if ( $colon === false ) {
2231 // Nothing else interesting
2232 wfProfileOut( __METHOD__
);
2235 $lt = strpos( $str, '<', $i );
2236 if ( $stack === 0 ) {
2237 if ( $lt === false ||
$colon < $lt ) {
2239 $before = substr( $str, 0, $colon );
2240 $after = substr( $str, $colon +
1 );
2241 wfProfileOut( __METHOD__
);
2245 if ( $lt === false ) {
2246 // Nothing else interesting to find; abort!
2247 // We're nested, but there's no close tags left. Abort!
2250 // Skip ahead to next tag start
2252 $state = self
::COLON_STATE_TAGSTART
;
2255 case 1: // self::COLON_STATE_TAG:
2260 $state = self
::COLON_STATE_TEXT
;
2263 // Slash may be followed by >?
2264 $state = self
::COLON_STATE_TAGSLASH
;
2270 case 2: // self::COLON_STATE_TAGSTART:
2273 $state = self
::COLON_STATE_CLOSETAG
;
2276 $state = self
::COLON_STATE_COMMENT
;
2279 // Illegal early close? This shouldn't happen D:
2280 $state = self
::COLON_STATE_TEXT
;
2283 $state = self
::COLON_STATE_TAG
;
2286 case 3: // self::COLON_STATE_CLOSETAG:
2291 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2292 wfProfileOut( __METHOD__
);
2295 $state = self
::COLON_STATE_TEXT
;
2298 case self
::COLON_STATE_TAGSLASH
:
2300 // Yes, a self-closed tag <blah/>
2301 $state = self
::COLON_STATE_TEXT
;
2303 // Probably we're jumping the gun, and this is an attribute
2304 $state = self
::COLON_STATE_TAG
;
2307 case 5: // self::COLON_STATE_COMMENT:
2309 $state = self
::COLON_STATE_COMMENTDASH
;
2312 case self
::COLON_STATE_COMMENTDASH
:
2314 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2316 $state = self
::COLON_STATE_COMMENT
;
2319 case self
::COLON_STATE_COMMENTDASHDASH
:
2321 $state = self
::COLON_STATE_TEXT
;
2323 $state = self
::COLON_STATE_COMMENT
;
2327 throw new MWException( "State machine error in " . __METHOD__
);
2331 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2334 wfProfileOut( __METHOD__
);
2339 * Return value of a magic variable (like PAGENAME)
2343 function getVariableValue( $index, $frame=false ) {
2344 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2345 global $wgScriptPath, $wgStylePath;
2348 * Some of these require message or data lookups and can be
2349 * expensive to check many times.
2351 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2352 if ( isset( $this->mVarCache
[$index] ) ) {
2353 return $this->mVarCache
[$index];
2357 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2358 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2361 global $wgLocaltimezone;
2362 if ( isset( $wgLocaltimezone ) ) {
2363 $oldtz = date_default_timezone_get();
2364 date_default_timezone_set( $wgLocaltimezone );
2367 $localTimestamp = date( 'YmdHis', $ts );
2368 $localMonth = date( 'm', $ts );
2369 $localMonth1 = date( 'n', $ts );
2370 $localMonthName = date( 'n', $ts );
2371 $localDay = date( 'j', $ts );
2372 $localDay2 = date( 'd', $ts );
2373 $localDayOfWeek = date( 'w', $ts );
2374 $localWeek = date( 'W', $ts );
2375 $localYear = date( 'Y', $ts );
2376 $localHour = date( 'H', $ts );
2377 if ( isset( $wgLocaltimezone ) ) {
2378 date_default_timezone_set( $oldtz );
2382 case 'currentmonth':
2383 $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2385 case 'currentmonth1':
2386 $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2388 case 'currentmonthname':
2389 $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2391 case 'currentmonthnamegen':
2392 $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2394 case 'currentmonthabbrev':
2395 $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2398 $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2401 $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2404 $value = $wgContLang->formatNum( $localMonth );
2407 $value = $wgContLang->formatNum( $localMonth1 );
2409 case 'localmonthname':
2410 $value = $wgContLang->getMonthName( $localMonthName );
2412 case 'localmonthnamegen':
2413 $value = $wgContLang->getMonthNameGen( $localMonthName );
2415 case 'localmonthabbrev':
2416 $value = $wgContLang->getMonthAbbreviation( $localMonthName );
2419 $value = $wgContLang->formatNum( $localDay );
2422 $value = $wgContLang->formatNum( $localDay2 );
2425 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2428 $value = $this->mTitle
->getPartialURL();
2430 case 'fullpagename':
2431 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2433 case 'fullpagenamee':
2434 $value = $this->mTitle
->getPrefixedURL();
2437 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2439 case 'subpagenamee':
2440 $value = $this->mTitle
->getSubpageUrlForm();
2442 case 'basepagename':
2443 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2445 case 'basepagenamee':
2446 $value = wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2448 case 'talkpagename':
2449 if ( $this->mTitle
->canTalk() ) {
2450 $talkPage = $this->mTitle
->getTalkPage();
2451 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2456 case 'talkpagenamee':
2457 if ( $this->mTitle
->canTalk() ) {
2458 $talkPage = $this->mTitle
->getTalkPage();
2459 $value = $talkPage->getPrefixedUrl();
2464 case 'subjectpagename':
2465 $subjPage = $this->mTitle
->getSubjectPage();
2466 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2468 case 'subjectpagenamee':
2469 $subjPage = $this->mTitle
->getSubjectPage();
2470 $value = $subjPage->getPrefixedUrl();
2473 // Let the edit saving system know we should parse the page
2474 // *after* a revision ID has been assigned.
2475 $this->mOutput
->setFlag( 'vary-revision' );
2476 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2477 $value = $this->mRevisionId
;
2480 // Let the edit saving system know we should parse the page
2481 // *after* a revision ID has been assigned. This is for null edits.
2482 $this->mOutput
->setFlag( 'vary-revision' );
2483 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2484 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2486 case 'revisionday2':
2487 // Let the edit saving system know we should parse the page
2488 // *after* a revision ID has been assigned. This is for null edits.
2489 $this->mOutput
->setFlag( 'vary-revision' );
2490 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2491 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2493 case 'revisionmonth':
2494 // Let the edit saving system know we should parse the page
2495 // *after* a revision ID has been assigned. This is for null edits.
2496 $this->mOutput
->setFlag( 'vary-revision' );
2497 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2498 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2500 case 'revisionyear':
2501 // Let the edit saving system know we should parse the page
2502 // *after* a revision ID has been assigned. This is for null edits.
2503 $this->mOutput
->setFlag( 'vary-revision' );
2504 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2505 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2507 case 'revisiontimestamp':
2508 // Let the edit saving system know we should parse the page
2509 // *after* a revision ID has been assigned. This is for null edits.
2510 $this->mOutput
->setFlag( 'vary-revision' );
2511 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2512 $value = $this->getRevisionTimestamp();
2514 case 'revisionuser':
2515 // Let the edit saving system know we should parse the page
2516 // *after* a revision ID has been assigned. This is for null edits.
2517 $this->mOutput
->setFlag( 'vary-revision' );
2518 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2519 $value = $this->getRevisionUser();
2522 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2525 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2528 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2531 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2533 case 'subjectspace':
2534 $value = $this->mTitle
->getSubjectNsText();
2536 case 'subjectspacee':
2537 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2539 case 'currentdayname':
2540 $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2543 $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2546 $value = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2549 $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2552 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2553 // int to remove the padding
2554 $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2557 $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2559 case 'localdayname':
2560 $value = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2563 $value = $wgContLang->formatNum( $localYear, true );
2566 $value = $wgContLang->time( $localTimestamp, false, false );
2569 $value = $wgContLang->formatNum( $localHour, true );
2572 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2573 // int to remove the padding
2574 $value = $wgContLang->formatNum( (int)$localWeek );
2577 $value = $wgContLang->formatNum( $localDayOfWeek );
2579 case 'numberofarticles':
2580 $value = $wgContLang->formatNum( SiteStats
::articles() );
2582 case 'numberoffiles':
2583 $value = $wgContLang->formatNum( SiteStats
::images() );
2585 case 'numberofusers':
2586 $value = $wgContLang->formatNum( SiteStats
::users() );
2588 case 'numberofactiveusers':
2589 $value = $wgContLang->formatNum( SiteStats
::activeUsers() );
2591 case 'numberofpages':
2592 $value = $wgContLang->formatNum( SiteStats
::pages() );
2594 case 'numberofadmins':
2595 $value = $wgContLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2597 case 'numberofedits':
2598 $value = $wgContLang->formatNum( SiteStats
::edits() );
2600 case 'numberofviews':
2601 $value = $wgContLang->formatNum( SiteStats
::views() );
2603 case 'currenttimestamp':
2604 $value = wfTimestamp( TS_MW
, $ts );
2606 case 'localtimestamp':
2607 $value = $localTimestamp;
2609 case 'currentversion':
2610 $value = SpecialVersion
::getVersion();
2617 return $wgServerName;
2619 return $wgScriptPath;
2621 return $wgStylePath;
2622 case 'directionmark':
2623 return $wgContLang->getDirMark();
2624 case 'contentlanguage':
2625 global $wgContLanguageCode;
2626 return $wgContLanguageCode;
2629 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2637 $this->mVarCache
[$index] = $value;
2643 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2647 function initialiseVariables() {
2648 wfProfileIn( __METHOD__
);
2649 $variableIDs = MagicWord
::getVariableIDs();
2650 $substIDs = MagicWord
::getSubstIDs();
2652 $this->mVariables
= new MagicWordArray( $variableIDs );
2653 $this->mSubstWords
= new MagicWordArray( $substIDs );
2654 wfProfileOut( __METHOD__
);
2658 * Preprocess some wikitext and return the document tree.
2659 * This is the ghost of replace_variables().
2661 * @param string $text The text to parse
2662 * @param integer flags Bitwise combination of:
2663 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2664 * included. Default is to assume a direct page view.
2666 * The generated DOM tree must depend only on the input text and the flags.
2667 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2669 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2670 * change in the DOM tree for a given text, must be passed through the section identifier
2671 * in the section edit link and thus back to extractSections().
2673 * The output of this function is currently only cached in process memory, but a persistent
2674 * cache may be implemented at a later date which takes further advantage of these strict
2675 * dependency requirements.
2679 function preprocessToDom( $text, $flags = 0 ) {
2680 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2685 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2687 public static function splitWhitespace( $s ) {
2688 $ltrimmed = ltrim( $s );
2689 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2690 $trimmed = rtrim( $ltrimmed );
2691 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2693 $w2 = substr( $ltrimmed, -$diff );
2697 return array( $w1, $trimmed, $w2 );
2701 * Replace magic variables, templates, and template arguments
2702 * with the appropriate text. Templates are substituted recursively,
2703 * taking care to avoid infinite loops.
2705 * Note that the substitution depends on value of $mOutputType:
2706 * self::OT_WIKI: only {{subst:}} templates
2707 * self::OT_PREPROCESS: templates but not extension tags
2708 * self::OT_HTML: all templates and extension tags
2710 * @param string $tex The text to transform
2711 * @param PPFrame $frame Object describing the arguments passed to the template.
2712 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2713 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2714 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2717 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2718 # Is there any text? Also, Prevent too big inclusions!
2719 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2722 wfProfileIn( __METHOD__
);
2724 if ( $frame === false ) {
2725 $frame = $this->getPreprocessor()->newFrame();
2726 } elseif ( !( $frame instanceof PPFrame
) ) {
2727 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2728 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2731 $dom = $this->preprocessToDom( $text );
2732 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2733 $text = $frame->expand( $dom, $flags );
2735 wfProfileOut( __METHOD__
);
2739 // Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2740 static function createAssocArgs( $args ) {
2741 $assocArgs = array();
2743 foreach ( $args as $arg ) {
2744 $eqpos = strpos( $arg, '=' );
2745 if ( $eqpos === false ) {
2746 $assocArgs[$index++
] = $arg;
2748 $name = trim( substr( $arg, 0, $eqpos ) );
2749 $value = trim( substr( $arg, $eqpos+
1 ) );
2750 if ( $value === false ) {
2753 if ( $name !== false ) {
2754 $assocArgs[$name] = $value;
2763 * Warn the user when a parser limitation is reached
2764 * Will warn at most once the user per limitation type
2766 * @param string $limitationType, should be one of:
2767 * 'expensive-parserfunction' (corresponding messages:
2768 * 'expensive-parserfunction-warning',
2769 * 'expensive-parserfunction-category')
2770 * 'post-expand-template-argument' (corresponding messages:
2771 * 'post-expand-template-argument-warning',
2772 * 'post-expand-template-argument-category')
2773 * 'post-expand-template-inclusion' (corresponding messages:
2774 * 'post-expand-template-inclusion-warning',
2775 * 'post-expand-template-inclusion-category')
2776 * @params int $current, $max When an explicit limit has been
2777 * exceeded, provide the values (optional)
2779 function limitationWarn( $limitationType, $current=null, $max=null) {
2780 // does no harm if $current and $max are present but are unnecessary for the message
2781 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
2782 $this->mOutput
->addWarning( $warning );
2783 $this->addTrackingCategory( "$limitationType-category" );
2787 * Return the text of a template, after recursively
2788 * replacing any variables or templates within the template.
2790 * @param array $piece The parts of the template
2791 * $piece['title']: the title, i.e. the part before the |
2792 * $piece['parts']: the parameter array
2793 * $piece['lineStart']: whether the brace was at the start of a line
2794 * @param PPFrame The current frame, contains template arguments
2795 * @return string the text of the template
2798 function braceSubstitution( $piece, $frame ) {
2799 global $wgContLang, $wgNonincludableNamespaces;
2800 wfProfileIn( __METHOD__
);
2801 wfProfileIn( __METHOD__
.'-setup' );
2804 $found = false; # $text has been filled
2805 $nowiki = false; # wiki markup in $text should be escaped
2806 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2807 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2808 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2809 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2811 # Title object, where $text came from
2814 # $part1 is the bit before the first |, and must contain only title characters.
2815 # Various prefixes will be stripped from it later.
2816 $titleWithSpaces = $frame->expand( $piece['title'] );
2817 $part1 = trim( $titleWithSpaces );
2820 # Original title text preserved for various purposes
2821 $originalTitle = $part1;
2823 # $args is a list of argument nodes, starting from index 0, not including $part1
2824 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
2825 wfProfileOut( __METHOD__
.'-setup' );
2828 wfProfileIn( __METHOD__
.'-modifiers' );
2831 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
2833 # Possibilities for substMatch: "subst", "safesubst" or FALSE
2834 # Decide whether to expand template or keep wikitext as-is.
2835 if ( $this->ot
['wiki'] ) {
2836 if ( $substMatch === false ) {
2837 $literal = true; # literal when in PST with no prefix
2839 $literal = false; # expand when in PST with subst: or safesubst:
2842 if ( $substMatch == 'subst' ) {
2843 $literal = true; # literal when not in PST with plain subst:
2845 $literal = false; # expand when not in PST with safesubst: or no prefix
2849 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2856 if ( !$found && $args->getLength() == 0 ) {
2857 $id = $this->mVariables
->matchStartToEnd( $part1 );
2858 if ( $id !== false ) {
2859 $text = $this->getVariableValue( $id, $frame );
2860 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
2861 $this->mOutput
->mContainsOldMagic
= true;
2867 # MSG, MSGNW and RAW
2870 $mwMsgnw = MagicWord
::get( 'msgnw' );
2871 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2874 # Remove obsolete MSG:
2875 $mwMsg = MagicWord
::get( 'msg' );
2876 $mwMsg->matchStartAndRemove( $part1 );
2880 $mwRaw = MagicWord
::get( 'raw' );
2881 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2882 $forceRawInterwiki = true;
2885 wfProfileOut( __METHOD__
.'-modifiers' );
2889 wfProfileIn( __METHOD__
. '-pfunc' );
2891 $colonPos = strpos( $part1, ':' );
2892 if ( $colonPos !== false ) {
2893 # Case sensitive functions
2894 $function = substr( $part1, 0, $colonPos );
2895 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2896 $function = $this->mFunctionSynonyms
[1][$function];
2898 # Case insensitive functions
2899 $function = $wgContLang->lc( $function );
2900 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2901 $function = $this->mFunctionSynonyms
[0][$function];
2907 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2908 $initialArgs = array( &$this );
2909 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2910 if ( $flags & SFH_OBJECT_ARGS
) {
2911 # Add a frame parameter, and pass the arguments as an array
2912 $allArgs = $initialArgs;
2913 $allArgs[] = $frame;
2914 for ( $i = 0; $i < $args->getLength(); $i++
) {
2915 $funcArgs[] = $args->item( $i );
2917 $allArgs[] = $funcArgs;
2919 # Convert arguments to plain text
2920 for ( $i = 0; $i < $args->getLength(); $i++
) {
2921 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2923 $allArgs = array_merge( $initialArgs, $funcArgs );
2926 # Workaround for PHP bug 35229 and similar
2927 if ( !is_callable( $callback ) ) {
2928 wfProfileOut( __METHOD__
. '-pfunc' );
2929 wfProfileOut( __METHOD__
);
2930 throw new MWException( "Tag hook for $function is not callable\n" );
2932 $result = call_user_func_array( $callback, $allArgs );
2935 $preprocessFlags = 0;
2937 if ( is_array( $result ) ) {
2938 if ( isset( $result[0] ) ) {
2940 unset( $result[0] );
2943 // Extract flags into the local scope
2944 // This allows callers to set flags such as nowiki, found, etc.
2950 $text = $this->preprocessToDom( $text, $preprocessFlags );
2955 wfProfileOut( __METHOD__
. '-pfunc' );
2958 # Finish mangling title and then check for loops.
2959 # Set $title to a Title object and $titleText to the PDBK
2962 # Split the title into page and subpage
2964 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2965 if ( $subpage !== '' ) {
2966 $ns = $this->mTitle
->getNamespace();
2968 $title = Title
::newFromText( $part1, $ns );
2970 $titleText = $title->getPrefixedText();
2971 # Check for language variants if the template is not found
2972 if ( $wgContLang->hasVariants() && $title->getArticleID() == 0 ) {
2973 $wgContLang->findVariantLink( $part1, $title, true );
2975 # Do recursion depth check
2976 $limit = $this->mOptions
->getMaxTemplateDepth();
2977 if ( $frame->depth
>= $limit ) {
2979 $text = '<span class="error">'
2980 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
2986 # Load from database
2987 if ( !$found && $title ) {
2988 wfProfileIn( __METHOD__
. '-loadtpl' );
2989 if ( !$title->isExternal() ) {
2990 if ( $title->getNamespace() == NS_SPECIAL
2991 && $this->mOptions
->getAllowSpecialInclusion()
2992 && $this->ot
['html'] )
2994 $text = SpecialPage
::capturePath( $title );
2995 if ( is_string( $text ) ) {
2998 $this->disableCache();
3000 } elseif ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3001 $found = false; // access denied
3002 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3004 list( $text, $title ) = $this->getTemplateDom( $title );
3005 if ( $text !== false ) {
3011 # If the title is valid but undisplayable, make a link to it
3012 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3013 $text = "[[:$titleText]]";
3016 } elseif ( $title->isTrans() ) {
3017 // Interwiki transclusion
3018 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3019 $text = $this->interwikiTransclude( $title, 'render' );
3022 $text = $this->interwikiTransclude( $title, 'raw' );
3023 // Preprocess it like a template
3024 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3030 # Do infinite loop check
3031 # This has to be done after redirect resolution to avoid infinite loops via redirects
3032 if ( !$frame->loopCheck( $title ) ) {
3034 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3035 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3037 wfProfileOut( __METHOD__
. '-loadtpl' );
3040 # If we haven't found text to substitute by now, we're done
3041 # Recover the source wikitext and return it
3043 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3044 wfProfileOut( __METHOD__
);
3045 return array( 'object' => $text );
3048 # Expand DOM-style return values in a child frame
3049 if ( $isChildObj ) {
3050 # Clean up argument array
3051 $newFrame = $frame->newChild( $args, $title );
3054 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3055 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3056 # Expansion is eligible for the empty-frame cache
3057 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3058 $text = $this->mTplExpandCache
[$titleText];
3060 $text = $newFrame->expand( $text );
3061 $this->mTplExpandCache
[$titleText] = $text;
3064 # Uncached expansion
3065 $text = $newFrame->expand( $text );
3068 if ( $isLocalObj && $nowiki ) {
3069 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3070 $isLocalObj = false;
3073 # Replace raw HTML by a placeholder
3074 # Add a blank line preceding, to prevent it from mucking up
3075 # immediately preceding headings
3077 $text = "\n\n" . $this->insertStripItem( $text );
3078 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3079 # Escape nowiki-style return values
3080 $text = wfEscapeWikiText( $text );
3081 } elseif ( is_string( $text )
3082 && !$piece['lineStart']
3083 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3085 # Bug 529: if the template begins with a table or block-level
3086 # element, it should be treated as beginning a new line.
3087 # This behaviour is somewhat controversial.
3088 $text = "\n" . $text;
3091 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3092 # Error, oversize inclusion
3093 $text = "[[$originalTitle]]" .
3094 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3095 $this->limitationWarn( 'post-expand-template-inclusion' );
3098 if ( $isLocalObj ) {
3099 $ret = array( 'object' => $text );
3101 $ret = array( 'text' => $text );
3104 wfProfileOut( __METHOD__
);
3109 * Get the semi-parsed DOM representation of a template with a given title,
3110 * and its redirect destination title. Cached.
3112 function getTemplateDom( $title ) {
3113 $cacheTitle = $title;
3114 $titleText = $title->getPrefixedDBkey();
3116 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3117 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3118 $title = Title
::makeTitle( $ns, $dbk );
3119 $titleText = $title->getPrefixedDBkey();
3121 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3122 return array( $this->mTplDomCache
[$titleText], $title );
3125 // Cache miss, go to the database
3126 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3128 if ( $text === false ) {
3129 $this->mTplDomCache
[$titleText] = false;
3130 return array( false, $title );
3133 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3134 $this->mTplDomCache
[ $titleText ] = $dom;
3136 if ( !$title->equals( $cacheTitle ) ) {
3137 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3138 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3141 return array( $dom, $title );
3145 * Fetch the unparsed text of a template and register a reference to it.
3147 function fetchTemplateAndTitle( $title ) {
3148 $templateCb = $this->mOptions
->getTemplateCallback();
3149 $stuff = call_user_func( $templateCb, $title, $this );
3150 $text = $stuff['text'];
3151 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3152 if ( isset( $stuff['deps'] ) ) {
3153 foreach ( $stuff['deps'] as $dep ) {
3154 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3157 return array( $text, $finalTitle );
3160 function fetchTemplate( $title ) {
3161 $rv = $this->fetchTemplateAndTitle( $title );
3166 * Static function to get a template
3167 * Can be overridden via ParserOptions::setTemplateCallback().
3169 static function statelessFetchTemplate( $title, $parser=false ) {
3170 $text = $skip = false;
3171 $finalTitle = $title;
3174 // Loop to fetch the article, with up to 1 redirect
3175 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3176 # Give extensions a chance to select the revision instead
3177 $id = false; // Assume current
3178 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3184 'page_id' => $title->getArticleID(),
3188 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3189 $rev_id = $rev ?
$rev->getId() : 0;
3190 // If there is no current revision, there is no page
3191 if ( $id === false && !$rev ) {
3192 $linkCache = LinkCache
::singleton();
3193 $linkCache->addBadLinkObj( $title );
3198 'page_id' => $title->getArticleID(),
3199 'rev_id' => $rev_id );
3202 $text = $rev->getText();
3203 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3205 $message = $wgContLang->lcfirst( $title->getText() );
3206 $text = wfMsgForContentNoTrans( $message );
3207 if ( wfEmptyMsg( $message, $text ) ) {
3214 if ( $text === false ) {
3218 $finalTitle = $title;
3219 $title = Title
::newFromRedirect( $text );
3223 'finalTitle' => $finalTitle,
3228 * Transclude an interwiki link.
3230 function interwikiTransclude( $title, $action ) {
3231 global $wgEnableScaryTranscluding;
3233 if ( !$wgEnableScaryTranscluding ) {
3234 return wfMsg('scarytranscludedisabled');
3237 $url = $title->getFullUrl( "action=$action" );
3239 if ( strlen( $url ) > 255 ) {
3240 return wfMsg( 'scarytranscludetoolong' );
3242 return $this->fetchScaryTemplateMaybeFromCache( $url );
3245 function fetchScaryTemplateMaybeFromCache( $url ) {
3246 global $wgTranscludeCacheExpiry;
3247 $dbr = wfGetDB( DB_SLAVE
);
3248 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3249 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3250 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3252 return $obj->tc_contents
;
3255 $text = Http
::get( $url );
3257 return wfMsg( 'scarytranscludefailed', $url );
3260 $dbw = wfGetDB( DB_MASTER
);
3261 $dbw->replace( 'transcache', array('tc_url'), array(
3263 'tc_time' => $dbw->timestamp( time() ),
3264 'tc_contents' => $text)
3271 * Triple brace replacement -- used for template arguments
3274 function argSubstitution( $piece, $frame ) {
3275 wfProfileIn( __METHOD__
);
3278 $parts = $piece['parts'];
3279 $nameWithSpaces = $frame->expand( $piece['title'] );
3280 $argName = trim( $nameWithSpaces );
3282 $text = $frame->getArgument( $argName );
3283 if ( $text === false && $parts->getLength() > 0
3287 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3290 # No match in frame, use the supplied default
3291 $object = $parts->item( 0 )->getChildren();
3293 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3294 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3295 $this->limitationWarn( 'post-expand-template-argument' );
3298 if ( $text === false && $object === false ) {
3300 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3302 if ( $error !== false ) {
3305 if ( $object !== false ) {
3306 $ret = array( 'object' => $object );
3308 $ret = array( 'text' => $text );
3311 wfProfileOut( __METHOD__
);
3316 * Return the text to be used for a given extension tag.
3317 * This is the ghost of strip().
3319 * @param array $params Associative array of parameters:
3320 * name PPNode for the tag name
3321 * attr PPNode for unparsed text where tag attributes are thought to be
3322 * attributes Optional associative array of parsed attributes
3323 * inner Contents of extension element
3324 * noClose Original text did not have a close tag
3325 * @param PPFrame $frame
3327 function extensionSubstitution( $params, $frame ) {
3328 global $wgRawHtml, $wgContLang;
3330 $name = $frame->expand( $params['name'] );
3331 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3332 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3333 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3335 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3336 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3337 if ( $isFunctionTag ) {
3338 $markerType = 'none';
3340 $markerType = 'general';
3342 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3343 $name = strtolower( $name );
3344 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3345 if ( isset( $params['attributes'] ) ) {
3346 $attributes = $attributes +
$params['attributes'];
3349 if ( isset( $this->mTagHooks
[$name] ) ) {
3350 # Workaround for PHP bug 35229 and similar
3351 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3352 throw new MWException( "Tag hook for $name is not callable\n" );
3354 $output = call_user_func_array( $this->mTagHooks
[$name],
3355 array( $content, $attributes, $this, $frame ) );
3356 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3357 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3358 if ( !is_callable( $callback ) ) {
3359 throw new MWException( "Tag hook for $name is not callable\n" );
3362 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3364 $output = '<span class="error">Invalid tag extension name: ' .
3365 htmlspecialchars( $name ) . '</span>';
3368 if ( is_array( $output ) ) {
3369 // Extract flags to local scope (to override $markerType)
3371 $output = $flags[0];
3376 if ( is_null( $attrText ) ) {
3379 if ( isset( $params['attributes'] ) ) {
3380 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3381 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3382 htmlspecialchars( $attrValue ) . '"';
3385 if ( $content === null ) {
3386 $output = "<$name$attrText/>";
3388 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3389 $output = "<$name$attrText>$content$close";
3393 if ( $markerType === 'none' ) {
3395 } elseif ( $markerType === 'nowiki' ) {
3396 $this->mStripState
->nowiki
->setPair( $marker, $output );
3397 } elseif ( $markerType === 'general' ) {
3398 $this->mStripState
->general
->setPair( $marker, $output );
3400 throw new MWException( __METHOD__
.': invalid marker type' );
3406 * Increment an include size counter
3408 * @param string $type The type of expansion
3409 * @param integer $size The size of the text
3410 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3412 function incrementIncludeSize( $type, $size ) {
3413 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3416 $this->mIncludeSizes
[$type] +
= $size;
3422 * Increment the expensive function count
3424 * @return boolean False if the limit has been exceeded
3426 function incrementExpensiveFunctionCount() {
3427 global $wgExpensiveParserFunctionLimit;
3428 $this->mExpensiveFunctionCount++
;
3429 if ( $this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit ) {
3436 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3437 * Fills $this->mDoubleUnderscores, returns the modified text
3439 function doDoubleUnderscore( $text ) {
3440 wfProfileIn( __METHOD__
);
3442 // The position of __TOC__ needs to be recorded
3443 $mw = MagicWord
::get( 'toc' );
3444 if ( $mw->match( $text ) ) {
3445 $this->mShowToc
= true;
3446 $this->mForceTocPosition
= true;
3448 // Set a placeholder. At the end we'll fill it in with the TOC.
3449 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3451 // Only keep the first one.
3452 $text = $mw->replace( '', $text );
3455 // Now match and remove the rest of them
3456 $mwa = MagicWord
::getDoubleUnderscoreArray();
3457 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3459 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3460 $this->mOutput
->mNoGallery
= true;
3462 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3463 $this->mShowToc
= false;
3465 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3466 $this->mOutput
->setProperty( 'hiddencat', 'y' );
3467 $this->addTrackingCategory( 'hidden-category-category' );
3469 # (bug 8068) Allow control over whether robots index a page.
3471 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3472 # is not desirable, the last one on the page should win.
3473 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3474 $this->mOutput
->setIndexPolicy( 'noindex' );
3475 $this->addTrackingCategory( 'noindex-category' );
3477 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3478 $this->mOutput
->setIndexPolicy( 'index' );
3479 $this->addTrackingCategory( 'index-category' );
3482 wfProfileOut( __METHOD__
);
3487 * Add a tracking category, getting the title from a system message,
3488 * or print a debug message if the title is invalid.
3489 * @param $msg String message key
3490 * @return Bool whether the addition was successful
3492 protected function addTrackingCategory( $msg ) {
3493 $cat = wfMsgForContent( $msg );
3495 # Allow tracking categories to be disabled by setting them to "-"
3496 if ( $cat === '-' ) {
3500 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3501 if ( $containerCategory ) {
3502 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3505 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3511 * This function accomplishes several tasks:
3512 * 1) Auto-number headings if that option is enabled
3513 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3514 * 3) Add a Table of contents on the top for users who have enabled the option
3515 * 4) Auto-anchor headings
3517 * It loops through all headlines, collects the necessary data, then splits up the
3518 * string and re-inserts the newly formatted headlines.
3520 * @param string $text
3521 * @param string $origText Original, untouched wikitext
3522 * @param boolean $isMain
3525 function formatHeadings( $text, $origText, $isMain=true ) {
3526 global $wgMaxTocLevel, $wgContLang, $wgHtml5, $wgExperimentalHtmlIds;
3528 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3529 $showEditLink = $this->mOptions
->getEditSection();
3531 // Do not call quickUserCan unless necessary
3532 if ( $showEditLink && !$this->mTitle
->quickUserCan( 'edit' ) ) {
3536 # Inhibit editsection links if requested in the page
3537 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ||
$this->mOptions
->getIsPrintable() ) {
3541 # Get all headlines for numbering them and adding funky stuff like [edit]
3542 # links - this is for later, but we need the number of headlines right now
3544 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3546 # if there are fewer than 4 headlines in the article, do not show TOC
3547 # unless it's been explicitly enabled.
3548 $enoughToc = $this->mShowToc
&&
3549 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
3551 # Allow user to stipulate that a page should have a "new section"
3552 # link added via __NEWSECTIONLINK__
3553 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3554 $this->mOutput
->setNewSection( true );
3557 # Allow user to remove the "new section"
3558 # link via __NONEWSECTIONLINK__
3559 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3560 $this->mOutput
->hideNewSection( true );
3563 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3564 # override above conditions and always show TOC above first header
3565 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3566 $this->mShowToc
= true;
3570 # We need this to perform operations on the HTML
3571 $sk = $this->mOptions
->getSkin();
3577 # Ugh .. the TOC should have neat indentation levels which can be
3578 # passed to the skin functions. These are determined here
3582 $sublevelCount = array();
3583 $levelCount = array();
3589 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3590 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3591 $oldType = $this->mOutputType
;
3592 $this->setOutputType( self
::OT_WIKI
);
3593 $frame = $this->getPreprocessor()->newFrame();
3594 $root = $this->preprocessToDom( $origText );
3595 $node = $root->getFirstChild();
3599 foreach ( $matches[3] as $headline ) {
3600 $isTemplate = false;
3602 $sectionIndex = false;
3604 $markerMatches = array();
3605 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
3606 $serial = $markerMatches[1];
3607 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3608 $isTemplate = ( $titleText != $baseTitleText );
3609 $headline = preg_replace( "/^$markerRegex/", "", $headline );
3613 $prevlevel = $level;
3614 $prevtoclevel = $toclevel;
3616 $level = $matches[1][$headlineCount];
3618 if ( $level > $prevlevel ) {
3619 # Increase TOC level
3621 $sublevelCount[$toclevel] = 0;
3622 if ( $toclevel<$wgMaxTocLevel ) {
3623 $prevtoclevel = $toclevel;
3624 $toc .= $sk->tocIndent();
3627 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
3628 # Decrease TOC level, find level to jump to
3630 for ( $i = $toclevel; $i > 0; $i-- ) {
3631 if ( $levelCount[$i] == $level ) {
3632 # Found last matching level
3635 } elseif ( $levelCount[$i] < $level ) {
3636 # Found first matching level below current level
3644 if ( $toclevel<$wgMaxTocLevel ) {
3645 if ( $prevtoclevel < $wgMaxTocLevel ) {
3646 # Unindent only if the previous toc level was shown :p
3647 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3648 $prevtoclevel = $toclevel;
3650 $toc .= $sk->tocLineEnd();
3654 # No change in level, end TOC line
3655 if ( $toclevel<$wgMaxTocLevel ) {
3656 $toc .= $sk->tocLineEnd();
3660 $levelCount[$toclevel] = $level;
3662 # count number of headlines for each level
3663 @$sublevelCount[$toclevel]++
;
3665 for( $i = 1; $i <= $toclevel; $i++
) {
3666 if ( !empty( $sublevelCount[$i] ) ) {
3670 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3675 # The safe header is a version of the header text safe to use for links
3676 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3677 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3679 # Remove link placeholders by the link text.
3680 # <!--LINK number-->
3682 # link text with suffix
3683 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3685 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3686 $tocline = preg_replace(
3687 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3688 array( '', '<$1>' ),
3691 $tocline = trim( $tocline );
3693 # For the anchor, strip out HTML-y stuff period
3694 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3695 $safeHeadline = preg_replace( '/[ _]+/', ' ', $safeHeadline );
3696 $safeHeadline = trim( $safeHeadline );
3698 # Save headline for section edit hint before it's escaped
3699 $headlineHint = $safeHeadline;
3701 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
3702 # For reverse compatibility, provide an id that's
3703 # HTML4-compatible, like we used to.
3705 # It may be worth noting, academically, that it's possible for
3706 # the legacy anchor to conflict with a non-legacy headline
3707 # anchor on the page. In this case likely the "correct" thing
3708 # would be to either drop the legacy anchors or make sure
3709 # they're numbered first. However, this would require people
3710 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3711 # manually, so let's not bother worrying about it.
3712 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
3713 array( 'noninitial', 'legacy' ) );
3714 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3716 if ( $legacyHeadline == $safeHeadline ) {
3717 # No reason to have both (in fact, we can't)
3718 $legacyHeadline = false;
3721 $legacyHeadline = false;
3722 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
3726 # HTML names must be case-insensitively unique (bug 10721). FIXME:
3727 # Does this apply to Unicode characters? Because we aren't
3728 # handling those here.
3729 $arrayKey = strtolower( $safeHeadline );
3730 if ( $legacyHeadline === false ) {
3731 $legacyArrayKey = false;
3733 $legacyArrayKey = strtolower( $legacyHeadline );
3736 # count how many in assoc. array so we can track dupes in anchors
3737 if ( isset( $refers[$arrayKey] ) ) {
3738 $refers[$arrayKey]++
;
3740 $refers[$arrayKey] = 1;
3742 if ( isset( $refers[$legacyArrayKey] ) ) {
3743 $refers[$legacyArrayKey]++
;
3745 $refers[$legacyArrayKey] = 1;
3748 # Don't number the heading if it is the only one (looks silly)
3749 if ( $doNumberHeadings && count( $matches[3] ) > 1) {
3750 # the two are different if the line contains a link
3751 $headline = $numbering . ' ' . $headline;
3754 # Create the anchor for linking from the TOC to the section
3755 $anchor = $safeHeadline;
3756 $legacyAnchor = $legacyHeadline;
3757 if ( $refers[$arrayKey] > 1 ) {
3758 $anchor .= '_' . $refers[$arrayKey];
3760 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3761 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3763 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
3764 $toc .= $sk->tocLine( $anchor, $tocline,
3765 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
3768 # Add the section to the section tree
3769 # Find the DOM node for this header
3770 while ( $node && !$isTemplate ) {
3771 if ( $node->getName() === 'h' ) {
3772 $bits = $node->splitHeading();
3773 if ( $bits['i'] == $sectionIndex )
3776 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
3777 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
3778 $node = $node->getNextSibling();
3781 'toclevel' => $toclevel,
3784 'number' => $numbering,
3785 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
3786 'fromtitle' => $titleText,
3787 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
3788 'anchor' => $anchor,
3791 # give headline the correct <h#> tag
3792 if ( $showEditLink && $sectionIndex !== false ) {
3793 if ( $isTemplate ) {
3794 # Put a T flag in the section identifier, to indicate to extractSections()
3795 # that sections inside <includeonly> should be counted.
3796 $editlink = $sk->doEditSectionLink( Title
::newFromText( $titleText ), "T-$sectionIndex" );
3798 $editlink = $sk->doEditSectionLink( $this->mTitle
, $sectionIndex, $headlineHint );
3803 $head[$headlineCount] = $sk->makeHeadline( $level,
3804 $matches['attrib'][$headlineCount], $anchor, $headline,
3805 $editlink, $legacyAnchor );
3810 $this->setOutputType( $oldType );
3812 # Never ever show TOC if no headers
3813 if ( $numVisible < 1 ) {
3818 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3819 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3821 $toc = $sk->tocList( $toc );
3822 $this->mOutput
->setTOCHTML( $toc );
3826 $this->mOutput
->setSections( $tocraw );
3829 # split up and insert constructed headlines
3831 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3834 foreach ( $blocks as $block ) {
3835 if ( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3836 # This is the [edit] link that appears for the top block of text when
3837 # section editing is enabled
3839 # Disabled because it broke block formatting
3840 # For example, a bullet point in the top line
3841 # $full .= $sk->editSectionLink(0);
3844 if ( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3845 # Top anchor now in skin
3849 if ( !empty( $head[$i] ) ) {
3854 if ( $this->mForceTocPosition
) {
3855 return str_replace( '<!--MWTOC-->', $toc, $full );
3862 * Merge $tree2 into $tree1 by replacing the section with index
3863 * $section in $tree1 and its descendants with the sections in $tree2.
3864 * Note that in the returned section tree, only the 'index' and
3865 * 'byteoffset' fields are guaranteed to be correct.
3866 * @param $tree1 array Section tree from ParserOutput::getSectons()
3867 * @param $tree2 array Section tree
3868 * @param $section int Section index
3869 * @param $title Title Title both section trees come from
3870 * @param $len2 int Length of the original wikitext for $tree2
3871 * @return array Merged section tree
3873 public static function mergeSectionTrees( $tree1, $tree2, $section, $title, $len2 ) {
3876 $targetLevel = false;
3880 $numbering = array( 0 );
3881 $titletext = $title->getPrefixedDBkey();
3882 foreach ( $tree1 as $s ) {
3883 if ( $targetLevel !== false ) {
3884 if ( $s['level'] <= $targetLevel ) {
3885 // We've skipped enough
3886 $targetLevel = false;
3891 if ( $s['index'] != $section ||
3892 $s['fromtitle'] != $titletext ) {
3893 self
::incrementNumbering( $numbering,
3894 $s['toclevel'], $lastLevel );
3896 // Rewrite index, byteoffset and number
3897 if ( $s['fromtitle'] == $titletext ) {
3898 $s['index'] = $nextIndex++
;
3900 $s['byteoffset'] +
= $len2;
3903 $s['number'] = implode( '.', array_map(
3904 array( $wgContLang, 'formatnum' ),
3906 $lastLevel = $s['toclevel'];
3909 // We're at $section
3910 // Insert sections from $tree2 here
3911 foreach ( $tree2 as $s2 ) {
3912 // Rewrite the fields in $s2
3913 // before inserting it
3914 $s2['toclevel'] +
= $s['toclevel'] - 1;
3915 $s2['level'] +
= $s['level'] - 1;
3916 $s2['index'] = $nextIndex++
;
3917 $s2['byteoffset'] +
= $s['byteoffset'];
3919 self
::incrementNumbering( $numbering,
3920 $s2['toclevel'], $lastLevel );
3921 $s2['number'] = implode( '.', array_map(
3922 array( $wgContLang, 'formatnum' ),
3924 $lastLevel = $s2['toclevel'];
3927 // Skip all descendants of $section in $tree1
3928 $targetLevel = $s['level'];
3936 * Increment a section number. Helper function for mergeSectionTrees()
3937 * @param $number array Array representing a section number
3938 * @param $level int Current TOC level (depth)
3939 * @param $lastLevel int Level of previous TOC entry
3941 private static function incrementNumbering( &$number, $level, $lastLevel ) {
3942 if ( $level > $lastLevel ) {
3943 $number[$level - 1] = 1;
3944 } elseif ( $level < $lastLevel ) {
3945 foreach ( $number as $key => $unused )
3946 if ( $key >= $level ) {
3947 unset( $number[$key] );
3949 $number[$level - 1]++
;
3951 $number[$level - 1]++
;
3956 * Transform wiki markup when saving a page by doing \r\n -> \n
3957 * conversion, substitting signatures, {{subst:}} templates, etc.
3959 * @param string $text the text to transform
3960 * @param Title &$title the Title object for the current article
3961 * @param User $user the User object describing the current user
3962 * @param ParserOptions $options parsing options
3963 * @param bool $clearState whether to clear the parser state first
3964 * @return string the altered wiki markup
3967 function preSaveTransform( $text, Title
$title, $user, $options, $clearState = true ) {
3968 $this->mOptions
= $options;
3969 $this->setTitle( $title );
3970 $this->setOutputType( self
::OT_WIKI
);
3972 if ( $clearState ) {
3973 $this->clearState();
3979 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3980 $text = $this->pstPass2( $text, $user );
3981 $text = $this->mStripState
->unstripBoth( $text );
3986 * Pre-save transform helper function
3989 function pstPass2( $text, $user ) {
3990 global $wgContLang, $wgLocaltimezone;
3992 # Note: This is the timestamp saved as hardcoded wikitext to
3993 # the database, we use $wgContLang here in order to give
3994 # everyone the same signature and use the default one rather
3995 # than the one selected in each user's preferences.
3996 # (see also bug 12815)
3997 $ts = $this->mOptions
->getTimestamp();
3998 if ( isset( $wgLocaltimezone ) ) {
3999 $tz = $wgLocaltimezone;
4001 $tz = date_default_timezone_get();
4004 $unixts = wfTimestamp( TS_UNIX
, $ts );
4005 $oldtz = date_default_timezone_get();
4006 date_default_timezone_set( $tz );
4007 $ts = date( 'YmdHis', $unixts );
4008 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4010 # Allow translation of timezones trough wiki. date() can return
4011 # whatever crap the system uses, localised or not, so we cannot
4012 # ship premade translations.
4013 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4014 $value = wfMsgForContent( $key );
4015 if ( !wfEmptyMsg( $key, $value ) ) {
4019 date_default_timezone_set( $oldtz );
4021 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4023 # Variable replacement
4024 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4025 $text = $this->replaceVariables( $text );
4028 $sigText = $this->getUserSig( $user );
4029 $text = strtr( $text, array(
4031 '~~~~' => "$sigText $d",
4035 # Context links: [[|name]] and [[name (context)|]]
4036 global $wgLegalTitleChars;
4037 $tc = "[$wgLegalTitleChars]";
4038 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4040 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4041 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
4042 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4043 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4045 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4046 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4047 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4048 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4050 $t = $this->mTitle
->getText();
4052 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4053 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4054 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4055 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4057 # if there's no context, don't bother duplicating the title
4058 $text = preg_replace( $p2, '[[\\1]]', $text );
4061 # Trim trailing whitespace
4062 $text = rtrim( $text );
4068 * Fetch the user's signature text, if any, and normalize to
4069 * validated, ready-to-insert wikitext.
4070 * If you have pre-fetched the nickname or the fancySig option, you can
4071 * specify them here to save a database query.
4076 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4077 global $wgMaxSigChars;
4079 $username = $user->getName();
4081 // If not given, retrieve from the user object.
4082 if ( $nickname === false )
4083 $nickname = $user->getOption( 'nickname' );
4085 if ( is_null( $fancySig ) ) {
4086 $fancySig = $user->getBoolOption( 'fancysig' );
4089 $nickname = $nickname == null ?
$username : $nickname;
4091 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4092 $nickname = $username;
4093 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4094 } elseif ( $fancySig !== false ) {
4095 # Sig. might contain markup; validate this
4096 if ( $this->validateSig( $nickname ) !== false ) {
4097 # Validated; clean up (if needed) and return it
4098 return $this->cleanSig( $nickname, true );
4100 # Failed to validate; fall back to the default
4101 $nickname = $username;
4102 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4106 // Make sure nickname doesnt get a sig in a sig
4107 $nickname = $this->cleanSigInSig( $nickname );
4109 # If we're still here, make it a link to the user page
4110 $userText = wfEscapeWikiText( $username );
4111 $nickText = wfEscapeWikiText( $nickname );
4112 if ( $user->isAnon() ) {
4113 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4115 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4120 * Check that the user's signature contains no bad XML
4122 * @param string $text
4123 * @return mixed An expanded string, or false if invalid.
4125 function validateSig( $text ) {
4126 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4130 * Clean up signature text
4132 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4133 * 2) Substitute all transclusions
4135 * @param string $text
4136 * @param $parsing Whether we're cleaning (preferences save) or parsing
4137 * @return string Signature text
4139 function cleanSig( $text, $parsing = false ) {
4142 $this->clearState();
4143 $this->setTitle( $wgTitle );
4144 $this->mOptions
= new ParserOptions
;
4145 $this->setOutputType
= self
::OT_PREPROCESS
;
4148 # Option to disable this feature
4149 if ( !$this->mOptions
->getCleanSignatures() ) {
4153 # FIXME: regex doesn't respect extension tags or nowiki
4154 # => Move this logic to braceSubstitution()
4155 $substWord = MagicWord
::get( 'subst' );
4156 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4157 $substText = '{{' . $substWord->getSynonym( 0 );
4159 $text = preg_replace( $substRegex, $substText, $text );
4160 $text = $this->cleanSigInSig( $text );
4161 $dom = $this->preprocessToDom( $text );
4162 $frame = $this->getPreprocessor()->newFrame();
4163 $text = $frame->expand( $dom );
4166 $text = $this->mStripState
->unstripBoth( $text );
4173 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4174 * @param string $text
4175 * @return string Signature text with /~{3,5}/ removed
4177 function cleanSigInSig( $text ) {
4178 $text = preg_replace( '/~{3,5}/', '', $text );
4183 * Set up some variables which are usually set up in parse()
4184 * so that an external function can call some class members with confidence
4187 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
4188 $this->setTitle( $title );
4189 $this->mOptions
= $options;
4190 $this->setOutputType( $outputType );
4191 if ( $clearState ) {
4192 $this->clearState();
4197 * Wrapper for preprocess()
4199 * @param string $text the text to preprocess
4200 * @param ParserOptions $options options
4204 function transformMsg( $text, $options ) {
4206 static $executing = false;
4208 # Guard against infinite recursion
4214 wfProfileIn( __METHOD__
);
4215 $text = $this->preprocess( $text, $wgTitle, $options );
4218 wfProfileOut( __METHOD__
);
4223 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4224 * The callback should have the following form:
4225 * function myParserHook( $text, $params, &$parser ) { ... }
4227 * Transform and return $text. Use $parser for any required context, e.g. use
4228 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4232 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
4233 * @param mixed $callback The callback function (and object) to use for the tag
4235 * @return The old value of the mTagHooks array associated with the hook
4237 function setHook( $tag, $callback ) {
4238 $tag = strtolower( $tag );
4239 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4240 $this->mTagHooks
[$tag] = $callback;
4241 if ( !in_array( $tag, $this->mStripList
) ) {
4242 $this->mStripList
[] = $tag;
4248 function setTransparentTagHook( $tag, $callback ) {
4249 $tag = strtolower( $tag );
4250 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4251 $this->mTransparentTagHooks
[$tag] = $callback;
4257 * Remove all tag hooks
4259 function clearTagHooks() {
4260 $this->mTagHooks
= array();
4261 $this->mStripList
= $this->mDefaultStripList
;
4265 * Create a function, e.g. {{sum:1|2|3}}
4266 * The callback function should have the form:
4267 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4269 * Or with SFH_OBJECT_ARGS:
4270 * function myParserFunction( $parser, $frame, $args ) { ... }
4272 * The callback may either return the text result of the function, or an array with the text
4273 * in element 0, and a number of flags in the other elements. The names of the flags are
4274 * specified in the keys. Valid flags are:
4275 * found The text returned is valid, stop processing the template. This
4277 * nowiki Wiki markup in the return value should be escaped
4278 * isHTML The returned text is HTML, armour it against wikitext transformation
4282 * @param string $id The magic word ID
4283 * @param mixed $callback The callback function (and object) to use
4284 * @param integer $flags a combination of the following flags:
4285 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4287 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4288 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4289 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4290 * the arguments, and to control the way they are expanded.
4292 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4293 * arguments, for instance:
4294 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4296 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4297 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4298 * working if/when this is changed.
4300 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4303 * Please read the documentation in includes/parser/Preprocessor.php for more information
4304 * about the methods available in PPFrame and PPNode.
4306 * @return The old callback function for this name, if any
4308 function setFunctionHook( $id, $callback, $flags = 0 ) {
4311 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4312 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4314 # Add to function cache
4315 $mw = MagicWord
::get( $id );
4317 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4319 $synonyms = $mw->getSynonyms();
4320 $sensitive = intval( $mw->isCaseSensitive() );
4322 foreach ( $synonyms as $syn ) {
4324 if ( !$sensitive ) {
4325 $syn = $wgContLang->lc( $syn );
4328 if ( !( $flags & SFH_NO_HASH
) ) {
4331 # Remove trailing colon
4332 if ( substr( $syn, -1, 1 ) === ':' ) {
4333 $syn = substr( $syn, 0, -1 );
4335 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4341 * Get all registered function hook identifiers
4345 function getFunctionHooks() {
4346 return array_keys( $this->mFunctionHooks
);
4350 * Create a tag function, e.g. <test>some stuff</test>.
4351 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4352 * Unlike parser functions, their content is not preprocessed.
4354 function setFunctionTagHook( $tag, $callback, $flags ) {
4355 $tag = strtolower( $tag );
4356 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4357 $this->mFunctionTagHooks
[$tag] : null;
4358 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4360 if ( !in_array( $tag, $this->mStripList
) ) {
4361 $this->mStripList
[] = $tag;
4368 * FIXME: update documentation. makeLinkObj() is deprecated.
4369 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4370 * Placeholders created in Skin::makeLinkObj()
4371 * Returns an array of link CSS classes, indexed by PDBK.
4373 function replaceLinkHolders( &$text, $options = 0 ) {
4374 return $this->mLinkHolders
->replace( $text );
4378 * Replace <!--LINK--> link placeholders with plain text of links
4379 * (not HTML-formatted).
4380 * @param string $text
4383 function replaceLinkHoldersText( $text ) {
4384 return $this->mLinkHolders
->replaceText( $text );
4388 * Renders an image gallery from a text with one line per image.
4389 * text labels may be given by using |-style alternative text. E.g.
4390 * Image:one.jpg|The number "1"
4391 * Image:tree.jpg|A tree
4392 * given as text will return the HTML of a gallery with two images,
4393 * labeled 'The number "1"' and
4396 function renderImageGallery( $text, $params ) {
4397 $ig = new ImageGallery();
4398 $ig->setContextTitle( $this->mTitle
);
4399 $ig->setShowBytes( false );
4400 $ig->setShowFilename( false );
4401 $ig->setParser( $this );
4402 $ig->setHideBadImages();
4403 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4404 $ig->useSkin( $this->mOptions
->getSkin() );
4405 $ig->mRevisionId
= $this->mRevisionId
;
4407 if ( isset( $params['showfilename'] ) ) {
4408 $ig->setShowFilename( true );
4410 $ig->setShowFilename( false );
4412 if ( isset( $params['caption'] ) ) {
4413 $caption = $params['caption'];
4414 $caption = htmlspecialchars( $caption );
4415 $caption = $this->replaceInternalLinks( $caption );
4416 $ig->setCaptionHtml( $caption );
4418 if ( isset( $params['perrow'] ) ) {
4419 $ig->setPerRow( $params['perrow'] );
4421 if ( isset( $params['widths'] ) ) {
4422 $ig->setWidths( $params['widths'] );
4424 if ( isset( $params['heights'] ) ) {
4425 $ig->setHeights( $params['heights'] );
4428 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4430 $lines = StringUtils
::explode( "\n", $text );
4431 foreach ( $lines as $line ) {
4432 # match lines like these:
4433 # Image:someimage.jpg|This is some image
4435 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4437 if ( count( $matches ) == 0 ) {
4441 if ( strpos( $matches[0], '%' ) !== false ) {
4442 $matches[1] = urldecode( $matches[1] );
4444 $tp = Title
::newFromText( $matches[1]/*, NS_FILE*/ );
4446 if ( is_null( $nt ) ) {
4447 # Bogus title. Ignore these so we don't bomb out later.
4450 if ( isset( $matches[3] ) ) {
4451 $label = $matches[3];
4456 $html = $this->recursiveTagParse( trim( $label ) );
4458 $ig->add( $nt, $html );
4460 # Only add real images (bug #5586)
4461 if ( $nt->getNamespace() == NS_FILE
) {
4462 $this->mOutput
->addImage( $nt->getDBkey() );
4465 return $ig->toHTML();
4468 function getImageParams( $handler ) {
4470 $handlerClass = get_class( $handler );
4474 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4475 // Initialise static lists
4476 static $internalParamNames = array(
4477 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4478 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4479 'bottom', 'text-bottom' ),
4480 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4481 'upright', 'border', 'link', 'alt' ),
4483 static $internalParamMap;
4484 if ( !$internalParamMap ) {
4485 $internalParamMap = array();
4486 foreach ( $internalParamNames as $type => $names ) {
4487 foreach ( $names as $name ) {
4488 $magicName = str_replace( '-', '_', "img_$name" );
4489 $internalParamMap[$magicName] = array( $type, $name );
4494 // Add handler params
4495 $paramMap = $internalParamMap;
4497 $handlerParamMap = $handler->getParamMap();
4498 foreach ( $handlerParamMap as $magic => $paramName ) {
4499 $paramMap[$magic] = array( 'handler', $paramName );
4502 $this->mImageParams
[$handlerClass] = $paramMap;
4503 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4505 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4509 * Parse image options text and use it to make an image
4510 * @param Title $title
4511 * @param string $options
4512 * @param LinkHolderArray $holders
4514 function makeImage( $title, $options, $holders = false ) {
4515 # Check if the options text is of the form "options|alt text"
4517 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4518 # * left no resizing, just left align. label is used for alt= only
4519 # * right same, but right aligned
4520 # * none same, but not aligned
4521 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4522 # * center center the image
4523 # * frame Keep original image size, no magnify-button.
4524 # * framed Same as "frame"
4525 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4526 # * upright reduce width for upright images, rounded to full __0 px
4527 # * border draw a 1px border around the image
4528 # * alt Text for HTML alt attribute (defaults to empty)
4529 # * link Set the target of the image link. Can be external, interwiki, or local
4530 # vertical-align values (no % or length right now):
4540 $parts = StringUtils
::explode( "|", $options );
4541 $sk = $this->mOptions
->getSkin();
4543 # Give extensions a chance to select the file revision for us
4544 $skip = $time = $descQuery = false;
4545 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4548 return $sk->link( $title );
4552 $imagename = $title->getDBkey();
4553 $file = wfFindFile( $title, array( 'time' => $time ) );
4555 $handler = $file ?
$file->getHandler() : false;
4557 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4559 # Process the input parameters
4561 $params = array( 'frame' => array(), 'handler' => array(),
4562 'horizAlign' => array(), 'vertAlign' => array() );
4563 foreach ( $parts as $part ) {
4564 $part = trim( $part );
4565 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4567 if ( isset( $paramMap[$magicName] ) ) {
4568 list( $type, $paramName ) = $paramMap[$magicName];
4570 // Special case; width and height come in one variable together
4571 if ( $type === 'handler' && $paramName === 'width' ) {
4573 # (bug 13500) In both cases (width/height and width only),
4574 # permit trailing "px" for backward compatibility.
4575 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4576 $width = intval( $m[1] );
4577 $height = intval( $m[2] );
4578 if ( $handler->validateParam( 'width', $width ) ) {
4579 $params[$type]['width'] = $width;
4582 if ( $handler->validateParam( 'height', $height ) ) {
4583 $params[$type]['height'] = $height;
4586 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4587 $width = intval( $value );
4588 if ( $handler->validateParam( 'width', $width ) ) {
4589 $params[$type]['width'] = $width;
4592 } // else no validation -- bug 13436
4594 if ( $type === 'handler' ) {
4595 # Validate handler parameter
4596 $validated = $handler->validateParam( $paramName, $value );
4598 # Validate internal parameters
4599 switch( $paramName ) {
4602 // @todo Fixme: possibly check validity here for
4603 // manualthumb? downstream behavior seems odd with
4604 // missing manual thumbs.
4606 $value = $this->stripAltText( $value, $holders );
4609 $chars = self
::EXT_LINK_URL_CLASS
;
4610 $prots = $this->mUrlProtocols
;
4611 if ( $value === '' ) {
4612 $paramName = 'no-link';
4615 } elseif ( preg_match( "/^$prots/", $value ) ) {
4616 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4617 $paramName = 'link-url';
4618 $this->mOutput
->addExternalLink( $value );
4622 $linkTitle = Title
::newFromText( $value );
4624 $paramName = 'link-title';
4625 $value = $linkTitle;
4626 $this->mOutput
->addLink( $linkTitle );
4632 // Most other things appear to be empty or numeric...
4633 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4638 $params[$type][$paramName] = $value;
4642 if ( !$validated ) {
4647 # Process alignment parameters
4648 if ( $params['horizAlign'] ) {
4649 $params['frame']['align'] = key( $params['horizAlign'] );
4651 if ( $params['vertAlign'] ) {
4652 $params['frame']['valign'] = key( $params['vertAlign'] );
4655 $params['frame']['caption'] = $caption;
4657 # Will the image be presented in a frame, with the caption below?
4658 $imageIsFramed = isset( $params['frame']['frame'] ) ||
4659 isset( $params['frame']['framed'] ) ||
4660 isset( $params['frame']['thumbnail'] ) ||
4661 isset( $params['frame']['manualthumb'] );
4663 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4664 # came to also set the caption, ordinary text after the image -- which
4665 # makes no sense, because that just repeats the text multiple times in
4666 # screen readers. It *also* came to set the title attribute.
4668 # Now that we have an alt attribute, we should not set the alt text to
4669 # equal the caption: that's worse than useless, it just repeats the
4670 # text. This is the framed/thumbnail case. If there's no caption, we
4671 # use the unnamed parameter for alt text as well, just for the time be-
4672 # ing, if the unnamed param is set and the alt param is not.
4674 # For the future, we need to figure out if we want to tweak this more,
4675 # e.g., introducing a title= parameter for the title; ignoring the un-
4676 # named parameter entirely for images without a caption; adding an ex-
4677 # plicit caption= parameter and preserving the old magic unnamed para-
4679 if ( $imageIsFramed ) { # Framed image
4680 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
4681 # No caption or alt text, add the filename as the alt text so
4682 # that screen readers at least get some description of the image
4683 $params['frame']['alt'] = $title->getText();
4685 # Do not set $params['frame']['title'] because tooltips don't make sense
4687 } else { # Inline image
4688 if ( !isset( $params['frame']['alt'] ) ) {
4689 # No alt text, use the "caption" for the alt text
4690 if ( $caption !== '') {
4691 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
4693 # No caption, fall back to using the filename for the
4695 $params['frame']['alt'] = $title->getText();
4698 # Use the "caption" for the tooltip text
4699 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4702 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4704 # Linker does the rest
4705 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4707 # Give the handler a chance to modify the parser object
4709 $handler->parserTransformHook( $this, $file );
4715 protected function stripAltText( $caption, $holders ) {
4716 # Strip bad stuff out of the title (tooltip). We can't just use
4717 # replaceLinkHoldersText() here, because if this function is called
4718 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4720 $tooltip = $holders->replaceText( $caption );
4722 $tooltip = $this->replaceLinkHoldersText( $caption );
4725 # make sure there are no placeholders in thumbnail attributes
4726 # that are later expanded to html- so expand them now and
4728 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
4729 $tooltip = Sanitizer
::stripAllTags( $tooltip );
4735 * Set a flag in the output object indicating that the content is dynamic and
4736 * shouldn't be cached.
4738 function disableCache() {
4739 wfDebug( "Parser output marked as uncacheable.\n" );
4740 $this->mOutput
->mCacheTime
= -1;
4744 * Callback from the Sanitizer for expanding items found in HTML attribute
4745 * values, so they can be safely tested and escaped.
4746 * @param string $text
4747 * @param PPFrame $frame
4751 function attributeStripCallback( &$text, $frame = false ) {
4752 $text = $this->replaceVariables( $text, $frame );
4753 $text = $this->mStripState
->unstripBoth( $text );
4762 function Title( $x = null ) { return wfSetVar( $this->mTitle
, $x ); }
4763 function Options( $x = null ) { return wfSetVar( $this->mOptions
, $x ); }
4764 function OutputType( $x = null ) { return wfSetVar( $this->mOutputType
, $x ); }
4770 function getTags() {
4771 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) );
4777 * Break wikitext input into sections, and either pull or replace
4778 * some particular section's text.
4780 * External callers should use the getSection and replaceSection methods.
4782 * @param string $text Page wikitext
4783 * @param string $section A section identifier string of the form:
4784 * <flag1> - <flag2> - ... - <section number>
4786 * Currently the only recognised flag is "T", which means the target section number
4787 * was derived during a template inclusion parse, in other words this is a template
4788 * section edit link. If no flags are given, it was an ordinary section edit link.
4789 * This flag is required to avoid a section numbering mismatch when a section is
4790 * enclosed by <includeonly> (bug 6563).
4792 * The section number 0 pulls the text before the first heading; other numbers will
4793 * pull the given section along with its lower-level subsections. If the section is
4794 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4796 * @param string $mode One of "get" or "replace"
4797 * @param string $newText Replacement text for section data.
4798 * @return string for "get", the extracted section text.
4799 * for "replace", the whole page with the section replaced.
4801 private function extractSections( $text, $section, $mode, $newText='' ) {
4803 $this->clearState();
4804 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4805 $this->mOptions
= new ParserOptions
;
4806 $this->setOutputType( self
::OT_PLAIN
);
4808 $frame = $this->getPreprocessor()->newFrame();
4810 // Process section extraction flags
4812 $sectionParts = explode( '-', $section );
4813 $sectionIndex = array_pop( $sectionParts );
4814 foreach ( $sectionParts as $part ) {
4815 if ( $part === 'T' ) {
4816 $flags |
= self
::PTD_FOR_INCLUSION
;
4819 // Preprocess the text
4820 $root = $this->preprocessToDom( $text, $flags );
4822 // <h> nodes indicate section breaks
4823 // They can only occur at the top level, so we can find them by iterating the root's children
4824 $node = $root->getFirstChild();
4826 // Find the target section
4827 if ( $sectionIndex == 0 ) {
4828 // Section zero doesn't nest, level=big
4829 $targetLevel = 1000;
4832 if ( $node->getName() === 'h' ) {
4833 $bits = $node->splitHeading();
4834 if ( $bits['i'] == $sectionIndex ) {
4835 $targetLevel = $bits['level'];
4839 if ( $mode === 'replace' ) {
4840 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4842 $node = $node->getNextSibling();
4848 if ( $mode === 'get' ) {
4855 // Find the end of the section, including nested sections
4857 if ( $node->getName() === 'h' ) {
4858 $bits = $node->splitHeading();
4859 $curLevel = $bits['level'];
4860 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4864 if ( $mode === 'get' ) {
4865 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4867 $node = $node->getNextSibling();
4870 // Write out the remainder (in replace mode only)
4871 if ( $mode === 'replace' ) {
4872 // Output the replacement text
4873 // Add two newlines on -- trailing whitespace in $newText is conventionally
4874 // stripped by the editor, so we need both newlines to restore the paragraph gap
4875 // Only add trailing whitespace if there is newText
4876 if ( $newText != "" ) {
4877 $outText .= $newText . "\n\n";
4881 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4882 $node = $node->getNextSibling();
4886 if ( is_string( $outText ) ) {
4887 // Re-insert stripped tags
4888 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4895 * This function returns the text of a section, specified by a number ($section).
4896 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4897 * the first section before any such heading (section 0).
4899 * If a section contains subsections, these are also returned.
4901 * @param string $text text to look in
4902 * @param string $section section identifier
4903 * @param string $deftext default to return if section is not found
4904 * @return string text of the requested section
4906 public function getSection( $text, $section, $deftext='' ) {
4907 return $this->extractSections( $text, $section, "get", $deftext );
4910 public function replaceSection( $oldtext, $section, $text ) {
4911 return $this->extractSections( $oldtext, $section, "replace", $text );
4915 * Get the timestamp associated with the current revision, adjusted for
4916 * the default server-local timestamp
4918 function getRevisionTimestamp() {
4919 if ( is_null( $this->mRevisionTimestamp
) ) {
4920 wfProfileIn( __METHOD__
);
4922 $dbr = wfGetDB( DB_SLAVE
);
4923 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4924 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4926 // Normalize timestamp to internal MW format for timezone processing.
4927 // This has the added side-effect of replacing a null value with
4928 // the current time, which gives us more sensible behavior for
4930 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4932 // The cryptic '' timezone parameter tells to use the site-default
4933 // timezone offset instead of the user settings.
4935 // Since this value will be saved into the parser cache, served
4936 // to other users, and potentially even used inside links and such,
4937 // it needs to be consistent for all visitors.
4938 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4940 wfProfileOut( __METHOD__
);
4942 return $this->mRevisionTimestamp
;
4946 * Get the name of the user that edited the last revision
4948 function getRevisionUser() {
4949 // if this template is subst: the revision id will be blank,
4950 // so just use the current user's name
4951 if ( $this->mRevisionId
) {
4952 $revision = Revision
::newFromId( $this->mRevisionId
);
4953 $revuser = $revision->getUserText();
4956 $revuser = $wgUser->getName();
4962 * Mutator for $mDefaultSort
4964 * @param $sort New value
4966 public function setDefaultSort( $sort ) {
4967 $this->mDefaultSort
= $sort;
4971 * Accessor for $mDefaultSort
4972 * Will use the title/prefixed title if none is set
4976 public function getDefaultSort() {
4977 global $wgCategoryPrefixedDefaultSortkey;
4978 if ( $this->mDefaultSort
!== false ) {
4979 return $this->mDefaultSort
;
4980 } elseif ( $this->mTitle
->getNamespace() == NS_CATEGORY ||
4981 !$wgCategoryPrefixedDefaultSortkey )
4983 return $this->mTitle
->getText();
4985 return $this->mTitle
->getPrefixedText();
4990 * Accessor for $mDefaultSort
4991 * Unlike getDefaultSort(), will return false if none is set
4993 * @return string or false
4995 public function getCustomDefaultSort() {
4996 return $this->mDefaultSort
;
5000 * Try to guess the section anchor name based on a wikitext fragment
5001 * presumably extracted from a heading, for example "Header" from
5004 public function guessSectionNameFromWikiText( $text ) {
5005 # Strip out wikitext links(they break the anchor)
5006 $text = $this->stripSectionName( $text );
5007 $headline = Sanitizer
::decodeCharReferences( $text );
5009 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
5010 $headline = trim( $headline );
5011 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
5012 $replacearray = array(
5017 array_keys( $replacearray ),
5018 array_values( $replacearray ),
5023 * Strips a text string of wikitext for use in a section anchor
5025 * Accepts a text string and then removes all wikitext from the
5026 * string and leaves only the resultant text (i.e. the result of
5027 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5028 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5029 * to create valid section anchors by mimicing the output of the
5030 * parser when headings are parsed.
5032 * @param $text string Text string to be stripped of wikitext
5033 * for use in a Section anchor
5034 * @return Filtered text string
5036 public function stripSectionName( $text ) {
5037 # Strip internal link markup
5038 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5039 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5041 # Strip external link markup (FIXME: Not Tolerant to blank link text
5042 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5043 # on how many empty links there are on the page - need to figure that out.
5044 $text = preg_replace( '/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5046 # Parse wikitext quotes (italics & bold)
5047 $text = $this->doQuotes( $text );
5050 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5054 function srvus( $text ) {
5055 return $this->testSrvus( $text, $this->mOutputType
);
5059 * strip/replaceVariables/unstrip for preprocessor regression testing
5061 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
5062 $this->clearState();
5063 if ( !$title instanceof Title
) {
5064 $title = Title
::newFromText( $title );
5066 $this->mTitle
= $title;
5067 $this->mOptions
= $options;
5068 $this->setOutputType( $outputType );
5069 $text = $this->replaceVariables( $text );
5070 $text = $this->mStripState
->unstripBoth( $text );
5071 $text = Sanitizer
::removeHTMLtags( $text );
5075 function testPst( $text, $title, $options ) {
5077 if ( !$title instanceof Title
) {
5078 $title = Title
::newFromText( $title );
5080 return $this->preSaveTransform( $text, $title, $wgUser, $options );
5083 function testPreprocess( $text, $title, $options ) {
5084 if ( !$title instanceof Title
) {
5085 $title = Title
::newFromText( $title );
5087 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5090 function markerSkipCallback( $s, $callback ) {
5093 while ( $i < strlen( $s ) ) {
5094 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5095 if ( $markerStart === false ) {
5096 $out .= call_user_func( $callback, substr( $s, $i ) );
5099 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5100 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5101 if ( $markerEnd === false ) {
5102 $out .= substr( $s, $markerStart );
5105 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5106 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5114 function serialiseHalfParsedText( $text ) {
5116 $data['text'] = $text;
5118 // First, find all strip markers, and store their
5119 // data in an array.
5120 $stripState = new StripState
;
5122 while ( ( $start_pos = strpos( $text, $this->mUniqPrefix
, $pos ) )
5123 && ( $end_pos = strpos( $text, self
::MARKER_SUFFIX
, $pos ) ) )
5125 $end_pos +
= strlen( self
::MARKER_SUFFIX
);
5126 $marker = substr( $text, $start_pos, $end_pos-$start_pos );
5128 if ( !empty( $this->mStripState
->general
->data
[$marker] ) ) {
5129 $replaceArray = $stripState->general
;
5130 $stripText = $this->mStripState
->general
->data
[$marker];
5131 } elseif ( !empty( $this->mStripState
->nowiki
->data
[$marker] ) ) {
5132 $replaceArray = $stripState->nowiki
;
5133 $stripText = $this->mStripState
->nowiki
->data
[$marker];
5135 throw new MWException( "Hanging strip marker: '$marker'." );
5138 $replaceArray->setPair( $marker, $stripText );
5141 $data['stripstate'] = $stripState;
5143 // Now, find all of our links, and store THEIR
5144 // data in an array! :)
5145 $links = array( 'internal' => array(), 'interwiki' => array() );
5149 while ( ( $start_pos = strpos( $text, '<!--LINK ', $pos ) ) ) {
5150 list( $ns, $trail ) = explode( ':', substr( $text, $start_pos +
strlen( '<!--LINK ' ) ), 2 );
5153 if ( empty( $links['internal'][$ns] ) ) {
5154 $links['internal'][$ns] = array();
5157 $key = trim( substr( $trail, 0, strpos( $trail, '-->' ) ) );
5158 $links['internal'][$ns][] = $this->mLinkHolders
->internals
[$ns][$key];
5159 $pos = $start_pos +
strlen( "<!--LINK $ns:$key-->" );
5165 while ( ( $start_pos = strpos( $text, '<!--IWLINK ', $pos ) ) ) {
5166 $data = substr( $text, $start_pos );
5167 $key = trim( substr( $data, 0, strpos( $data, '-->' ) ) );
5168 $links['interwiki'][] = $this->mLinkHolders
->interwiki
[$key];
5169 $pos = $start_pos +
strlen( "<!--IWLINK $key-->" );
5172 $data['linkholder'] = $links;
5177 function unserialiseHalfParsedText( $data, $intPrefix = null /* Unique identifying prefix */ ) {
5178 if ( !$intPrefix ) {
5179 $intPrefix = $this->getRandomString();
5182 // First, extract the strip state.
5183 $stripState = $data['stripstate'];
5184 $this->mStripState
->general
->merge( $stripState->general
);
5185 $this->mStripState
->nowiki
->merge( $stripState->nowiki
);
5187 // Now, extract the text, and renumber links
5188 $text = $data['text'];
5189 $links = $data['linkholder'];
5192 foreach ( $links['internal'] as $ns => $nsLinks ) {
5193 foreach ( $nsLinks as $key => $entry ) {
5194 $newKey = $intPrefix . '-' . $key;
5195 $this->mLinkHolders
->internals
[$ns][$newKey] = $entry;
5197 $text = str_replace( "<!--LINK $ns:$key-->", "<!--LINK $ns:$newKey-->", $text );
5202 foreach ( $links['interwiki'] as $key => $entry ) {
5203 $newKey = "$intPrefix-$key";
5204 $this->mLinkHolders
->interwikis
[$newKey] = $entry;
5206 $text = str_replace( "<!--IWLINK $key-->", "<!--IWLINK $newKey-->", $text );
5209 // Should be good to go.
5215 * @todo document, briefly.
5219 var $general, $nowiki;
5221 function __construct() {
5222 $this->general
= new ReplacementArray
;
5223 $this->nowiki
= new ReplacementArray
;
5226 function unstripGeneral( $text ) {
5227 wfProfileIn( __METHOD__
);
5230 $text = $this->general
->replace( $text );
5231 } while ( $text !== $oldText );
5232 wfProfileOut( __METHOD__
);
5236 function unstripNoWiki( $text ) {
5237 wfProfileIn( __METHOD__
);
5240 $text = $this->nowiki
->replace( $text );
5241 } while ( $text !== $oldText );
5242 wfProfileOut( __METHOD__
);
5246 function unstripBoth( $text ) {
5247 wfProfileIn( __METHOD__
);
5250 $text = $this->general
->replace( $text );
5251 $text = $this->nowiki
->replace( $text );
5252 } while ( $text !== $oldText );
5253 wfProfileOut( __METHOD__
);
5259 * @todo document, briefly.
5262 class OnlyIncludeReplacer
{
5265 function replace( $matches ) {
5266 if ( substr( $matches[1], -1 ) === "\n" ) {
5267 $this->output
.= substr( $matches[1], 0, -1 );
5269 $this->output
.= $matches[1];