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
25 * cleanSig() / cleanSigInSig()
26 * Cleans a signature before saving it to preferences
28 * Extracts sections from an article for section editing
30 * Removes <noinclude> sections, and <includeonly> tags.
33 * objects: $wgLang, $wgContLang
35 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
38 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
39 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
40 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
43 * * only within ParserOptions
50 * Update this version number when the ParserOutput format
51 * changes in an incompatible way, so the parser cache
52 * can automatically discard old data.
54 const VERSION = '1.6.4';
56 # Flags for Parser::setFunctionHook
57 # Also available as global constants from Defines.php
58 const SFH_NO_HASH = 1;
59 const SFH_OBJECT_ARGS = 2;
61 # Constants needed for external link processing
62 # Everything except bracket, space, or control characters
63 const EXT_LINK_URL_CLASS = '[^][<>"\\x00-\\x20\\x7F]';
64 const EXT_IMAGE_REGEX = '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
65 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
67 # State constants for the definition list colon extraction
68 const COLON_STATE_TEXT = 0;
69 const COLON_STATE_TAG = 1;
70 const COLON_STATE_TAGSTART = 2;
71 const COLON_STATE_CLOSETAG = 3;
72 const COLON_STATE_TAGSLASH = 4;
73 const COLON_STATE_COMMENT = 5;
74 const COLON_STATE_COMMENTDASH = 6;
75 const COLON_STATE_COMMENTDASHDASH = 7;
77 # Flags for preprocessToDom
78 const PTD_FOR_INCLUSION = 1;
80 # Allowed values for $this->mOutputType
81 # Parameter to startExternalParse().
82 const OT_HTML = 1; # like parse()
83 const OT_WIKI = 2; # like preSaveTransform()
84 const OT_PREPROCESS = 3; # like preprocess()
86 const OT_PLAIN = 4; # like extractSections() - portions of the original are returned unchanged.
88 # Marker Suffix needs to be accessible staticly.
89 const MARKER_SUFFIX = "-QINU\x7f";
92 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables;
93 var $mSubstWords, $mImageParams, $mImageParamsMagicArray, $mStripList, $mMarkerIndex;
94 var $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols, $mDefaultStripList;
95 var $mVarCache, $mConf, $mFunctionTagHooks;
98 # Cleared with clearState():
99 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
100 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
101 var $mLinkHolders, $mLinkID;
102 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
103 var $mTplExpandCache; # empty-frame expansion cache
104 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
105 var $mExpensiveFunctionCount; # number of expensive parser function calls
108 # These are variables reset at least once per parse regardless of $clearState
109 var $mOptions; # ParserOptions object
110 var $mTitle; # Title context, used for self-link rendering and similar things
111 var $mOutputType; # Output type, one of the OT_xxx constants
112 var $ot; # Shortcut alias, see setOutputType()
113 var $mRevisionId; # ID to display in {{REVISIONID}} tags
114 var $mRevisionTimestamp; # The timestamp of the specified revision ID
115 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp
122 function __construct( $conf = array() ) {
123 $this->mConf = $conf;
124 $this->mTagHooks = array();
125 $this->mTransparentTagHooks = array();
126 $this->mFunctionHooks = array();
127 $this->mFunctionTagHooks = array();
128 $this->mFunctionSynonyms = array( 0 => array(), 1 => array() );
129 $this->mDefaultStripList = $this->mStripList = array();
130 $this->mUrlProtocols = wfUrlProtocols();
131 $this->mExtLinkBracketedRegex = '/\[(\b(' . wfUrlProtocols() . ')'.
132 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/S';
133 $this->mVarCache = array();
134 if ( isset( $conf['preprocessorClass'] ) ) {
135 $this->mPreprocessorClass = $conf['preprocessorClass'];
136 } elseif ( extension_loaded( 'domxml' ) ) {
137 # PECL extension that conflicts with the core DOM extension (bug 13770)
138 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
139 $this->mPreprocessorClass = 'Preprocessor_Hash';
140 } elseif ( extension_loaded( 'dom' ) ) {
141 $this->mPreprocessorClass = 'Preprocessor_DOM';
143 $this->mPreprocessorClass = 'Preprocessor_Hash';
145 $this->mMarkerIndex = 0;
146 $this->mFirstCall = true;
150 * Reduce memory usage to reduce the impact of circular references
152 function __destruct() {
153 if ( isset( $this->mLinkHolders ) ) {
154 $this->mLinkHolders->__destruct();
156 foreach ( $this as $name => $value ) {
157 unset( $this->$name );
162 * Do various kinds of initialisation on the first call of the parser
164 function firstCallInit() {
165 if ( !$this->mFirstCall ) {
168 $this->mFirstCall = false;
170 wfProfileIn( __METHOD__ );
172 CoreParserFunctions::register( $this );
173 CoreTagHooks::register( $this );
174 $this->initialiseVariables();
176 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
177 wfProfileOut( __METHOD__ );
185 function clearState() {
186 wfProfileIn( __METHOD__ );
187 if ( $this->mFirstCall ) {
188 $this->firstCallInit();
190 $this->mOutput = new ParserOutput;
191 $this->mOptions->registerWatcher( array( $this->mOutput, 'recordOption' ) );
192 $this->mAutonumber = 0;
193 $this->mLastSection = '';
194 $this->mDTopen = false;
195 $this->mIncludeCount = array();
196 $this->mStripState = new StripState;
197 $this->mArgStack = false;
198 $this->mInPre = false;
199 $this->mLinkHolders = new LinkHolderArray( $this );
201 $this->mRevisionTimestamp = $this->mRevisionId = null;
202 $this->mVarCache = array();
205 * Prefix for temporary replacement strings for the multipass parser.
206 * \x07 should never appear in input as it's disallowed in XML.
207 * Using it at the front also gives us a little extra robustness
208 * since it shouldn't match when butted up against identifier-like
211 * Must not consist of all title characters, or else it will change
212 * the behaviour of <nowiki> in a link.
214 # $this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
215 # Changed to \x7f to allow XML double-parsing -- TS
216 $this->mUniqPrefix = "\x7fUNIQ" . self::getRandomString();
219 # Clear these on every parse, bug 4549
220 $this->mTplExpandCache = $this->mTplRedirCache = $this->mTplDomCache = array();
222 $this->mShowToc = true;
223 $this->mForceTocPosition = false;
224 $this->mIncludeSizes = array(
228 $this->mPPNodeCount = 0;
229 $this->mDefaultSort = false;
230 $this->mHeadings = array();
231 $this->mDoubleUnderscores = array();
232 $this->mExpensiveFunctionCount = 0;
235 if ( isset( $this->mPreprocessor ) && $this->mPreprocessor->parser !== $this ) {
236 $this->mPreprocessor = null;
239 wfRunHooks( 'ParserClearState', array( &$this ) );
240 wfProfileOut( __METHOD__ );
244 * Convert wikitext to HTML
245 * Do not call this function recursively.
247 * @param $text String: text we want to parse
248 * @param $title A title object
249 * @param $options ParserOptions
250 * @param $linestart boolean
251 * @param $clearState boolean
252 * @param $revid Int: number to pass in {{REVISIONID}}
253 * @return ParserOutput a ParserOutput
255 public function parse( $text, Title $title, ParserOptions $options, $linestart = true, $clearState = true, $revid = null ) {
257 * First pass--just handle <nowiki> sections, pass the rest off
258 * to internalParse() which does all the real work.
261 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang, $wgDisableLangConversion, $wgDisableTitleConversion;
262 $fname = __METHOD__.'-' . wfGetCaller();
263 wfProfileIn( __METHOD__ );
264 wfProfileIn( $fname );
266 $this->mOptions = $options;
271 $this->setTitle( $title ); # Page title has to be set for the pre-processor
273 $oldRevisionId = $this->mRevisionId;
274 $oldRevisionTimestamp = $this->mRevisionTimestamp;
275 if ( $revid !== null ) {
276 $this->mRevisionId = $revid;
277 $this->mRevisionTimestamp = null;
279 $this->setOutputType( self::OT_HTML );
280 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
282 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
283 $text = $this->internalParse( $text );
285 $text = $this->mStripState->unstripGeneral( $text );
287 # Clean up special characters, only run once, next-to-last before doBlockLevels
289 # french spaces, last one Guillemet-left
290 # only if there is something before the space
291 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
292 # french spaces, Guillemet-right
293 '/(\\302\\253) /' => '\\1 ',
294 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
296 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
298 $text = $this->doBlockLevels( $text, $linestart );
300 $this->replaceLinkHolders( $text );
303 * The page doesn't get language converted if
305 * b) Content isn't converted
306 * c) It's a conversion table
308 if ( !( $wgDisableLangConversion
309 || isset( $this->mDoubleUnderscores['nocontentconvert'] )
310 || $this->mTitle->isConversionTable() ) ) {
312 # The position of the convert() call should not be changed. it
313 # assumes that the links are all replaced and the only thing left
314 # is the <nowiki> mark.
316 $text = $wgContLang->convert( $text );
320 * A converted title will be provided in the output object if title and
321 * content conversion are enabled, the article text does not contain
322 * a conversion-suppressing double-underscore tag, and no
323 * {{DISPLAYTITLE:...}} is present. DISPLAYTITLE takes precedence over
324 * automatic link conversion.
326 if ( !( $wgDisableLangConversion
327 || $wgDisableTitleConversion
328 || isset( $this->mDoubleUnderscores['nocontentconvert'] )
329 || isset( $this->mDoubleUnderscores['notitleconvert'] )
330 || $this->mOutput->getDisplayTitle() !== false ) )
332 $convruletitle = $wgContLang->getConvRuleTitle();
333 if ( $convruletitle ) {
334 $this->mOutput->setTitleText( $convruletitle );
336 $titleText = $wgContLang->convertTitle( $title );
337 $this->mOutput->setTitleText( $titleText );
341 $text = $this->mStripState->unstripNoWiki( $text );
343 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
345 //!JF Move to its own function
347 $uniq_prefix = $this->mUniqPrefix;
349 $elements = array_keys( $this->mTransparentTagHooks );
350 $text = $this->extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
352 foreach ( $matches as $marker => $data ) {
353 list( $element, $content, $params, $tag ) = $data;
354 $tagName = strtolower( $element );
355 if ( isset( $this->mTransparentTagHooks[$tagName] ) ) {
356 $output = call_user_func_array( $this->mTransparentTagHooks[$tagName], array( $content, $params, $this ) );
360 $this->mStripState->general->setPair( $marker, $output );
362 $text = $this->mStripState->unstripGeneral( $text );
364 $text = Sanitizer::normalizeCharReferences( $text );
366 if ( ( $wgUseTidy && $this->mOptions->getTidy() ) || $wgAlwaysUseTidy ) {
367 $text = MWTidy::tidy( $text );
369 # attempt to sanitize at least some nesting problems
370 # (bug #2702 and quite a few others)
372 # ''Something [http://www.cool.com cool''] -->
373 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
374 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
375 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
376 # fix up an anchor inside another anchor, only
377 # at least for a single single nested link (bug 3695)
378 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
379 '\\1\\2</a>\\3</a>\\1\\4</a>',
380 # fix div inside inline elements- doBlockLevels won't wrap a line which
381 # contains a div, so fix it up here; replace
382 # div with escaped text
383 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
384 '\\1\\3<div\\5>\\6</div>\\8\\9',
385 # remove empty italic or bold tag pairs, some
386 # introduced by rules above
387 '/<([bi])><\/\\1>/' => '',
390 $text = preg_replace(
391 array_keys( $tidyregs ),
392 array_values( $tidyregs ),
395 global $wgExpensiveParserFunctionLimit;
396 if ( $this->mExpensiveFunctionCount > $wgExpensiveParserFunctionLimit ) {
397 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount, $wgExpensiveParserFunctionLimit );
400 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
402 # Information on include size limits, for the benefit of users who try to skirt them
403 if ( $this->mOptions->getEnableLimitReport() ) {
404 $max = $this->mOptions->getMaxIncludeSize();
405 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
407 "NewPP limit report\n" .
408 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->getMaxPPNodeCount()}\n" .
409 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
410 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
412 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
413 $text .= "\n<!-- \n$limitReport-->\n";
415 $this->mOutput->setText( $text );
417 $this->mRevisionId = $oldRevisionId;
418 $this->mRevisionTimestamp = $oldRevisionTimestamp;
419 wfProfileOut( $fname );
420 wfProfileOut( __METHOD__ );
422 return $this->mOutput;
426 * Recursive parser entry point that can be called from an extension tag
429 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
431 * @param $text String: text extension wants to have parsed
432 * @param $frame PPFrame: The frame to use for expanding any template variables
434 function recursiveTagParse( $text, $frame=false ) {
435 wfProfileIn( __METHOD__ );
436 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
437 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
438 $text = $this->internalParse( $text, false, $frame );
439 wfProfileOut( __METHOD__ );
444 * Expand templates and variables in the text, producing valid, static wikitext.
445 * Also removes comments.
447 function preprocess( $text, Title $title, ParserOptions $options, $revid = null ) {
448 wfProfileIn( __METHOD__ );
449 $this->mOptions = $options;
451 $this->setOutputType( self::OT_PREPROCESS );
452 $this->setTitle( $title );
453 if ( $revid !== null ) {
454 $this->mRevisionId = $revid;
456 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState ) );
457 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState ) );
458 $text = $this->replaceVariables( $text );
459 $text = $this->mStripState->unstripBoth( $text );
460 wfProfileOut( __METHOD__ );
465 * Process the wikitext for the ?preload= feature. (bug 5210)
467 * <noinclude>, <includeonly> etc. are parsed as for template transclusion,
468 * comments, templates, arguments, tags hooks and parser functions are untouched.
470 public function getPreloadText( $text, Title $title, ParserOptions $options ) {
471 # Parser (re)initialisation
472 $this->mOptions = $options;
474 $this->setOutputType( self::OT_PLAIN );
475 $this->setTitle( $title );
477 $flags = PPFrame::NO_ARGS | PPFrame::NO_TEMPLATES;
478 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
479 $text = $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
480 $text = $this->mStripState->unstripBoth( $text );
485 * Get a random string
490 static private function getRandomString() {
491 return dechex( mt_rand( 0, 0x7fffffff ) ) . dechex( mt_rand( 0, 0x7fffffff ) );
495 * Accessor for mUniqPrefix.
499 public function uniqPrefix() {
500 if ( !isset( $this->mUniqPrefix ) ) {
501 # @todo Fixme: this is probably *horribly wrong*
502 # LanguageConverter seems to want $wgParser's uniqPrefix, however
503 # if this is called for a parser cache hit, the parser may not
504 # have ever been initialized in the first place.
505 # Not really sure what the heck is supposed to be going on here.
507 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
509 return $this->mUniqPrefix;
513 * Set the context title
515 function setTitle( $t ) {
516 if ( !$t || $t instanceof FakeTitle ) {
517 $t = Title::newFromText( 'NO TITLE' );
520 if ( strval( $t->getFragment() ) !== '' ) {
521 # Strip the fragment to avoid various odd effects
522 $this->mTitle = clone $t;
523 $this->mTitle->setFragment( '' );
530 * Accessor for the Title object
532 * @return Title object
534 function getTitle() {
535 return $this->mTitle;
539 * Accessor/mutator for the Title object
541 * @param $x New Title object or null to just get the current one
542 * @return Title object
544 function Title( $x = null ) {
545 return wfSetVar( $this->mTitle, $x );
549 * Set the output type
551 * @param $ot Integer: new value
553 function setOutputType( $ot ) {
554 $this->mOutputType = $ot;
557 'html' => $ot == self::OT_HTML,
558 'wiki' => $ot == self::OT_WIKI,
559 'pre' => $ot == self::OT_PREPROCESS,
560 'plain' => $ot == self::OT_PLAIN,
565 * Accessor/mutator for the output type
567 * @param $x New value or null to just get the current one
570 function OutputType( $x = null ) {
571 return wfSetVar( $this->mOutputType, $x );
575 * Get the ParserOutput object
577 * @return ParserOutput object
579 function getOutput() {
580 return $this->mOutput;
584 * Get the ParserOptions object
586 * @return ParserOptions object
588 function getOptions() {
589 return $this->mOptions;
593 * Accessor/mutator for the ParserOptions object
595 * @param $x New value or null to just get the current one
596 * @return Current ParserOptions object
598 function Options( $x = null ) {
599 return wfSetVar( $this->mOptions, $x );
602 function nextLinkID() {
603 return $this->mLinkID++;
606 function getFunctionLang() {
607 global $wgLang, $wgContLang;
609 $target = $this->mOptions->getTargetLanguage();
610 if ( $target !== null ) {
613 return $this->mOptions->getInterfaceMessage() ? $wgLang : $wgContLang;
618 * Get a preprocessor object
620 * @return Preprocessor instance
622 function getPreprocessor() {
623 if ( !isset( $this->mPreprocessor ) ) {
624 $class = $this->mPreprocessorClass;
625 $this->mPreprocessor = new $class( $this );
627 return $this->mPreprocessor;
631 * Replaces all occurrences of HTML-style comments and the given tags
632 * in the text with a random marker and returns the next text. The output
633 * parameter $matches will be an associative array filled with data in
635 * 'UNIQ-xxxxx' => array(
638 * array( 'param' => 'x' ),
639 * '<element param="x">tag content</element>' ) )
641 * @param $elements list of element names. Comments are always extracted.
642 * @param $text Source text string.
643 * @param $matches Out parameter, Array: extracted tags
644 * @param $uniq_prefix
645 * @return String: stripped text
649 public function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
654 $taglist = implode( '|', $elements );
655 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
657 while ( $text != '' ) {
658 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE );
660 if ( count( $p ) < 5 ) {
663 if ( count( $p ) > 5 ) {
677 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++ ) . self::MARKER_SUFFIX;
678 $stripped .= $marker;
680 if ( $close === '/>' ) {
681 # Empty element tag, <tag />
686 if ( $element === '!--' ) {
689 $end = "/(<\\/$element\\s*>)/i";
691 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE );
693 if ( count( $q ) < 3 ) {
694 # No end tag -- let it run out to the end of the text.
703 $matches[$marker] = array( $element,
705 Sanitizer::decodeTagAttributes( $attributes ),
706 "<$element$attributes$close$content$tail" );
712 * Get a list of strippable XML-like elements
714 function getStripList() {
715 return $this->mStripList;
719 * @deprecated use replaceVariables
721 function strip( $text, $state, $stripcomments = false , $dontstrip = array() ) {
726 * Restores pre, math, and other extensions removed by strip()
728 * always call unstripNoWiki() after this one
730 * @deprecated use $this->mStripState->unstrip()
732 function unstrip( $text, $state ) {
733 return $state->unstripGeneral( $text );
737 * Always call this after unstrip() to preserve the order
740 * @deprecated use $this->mStripState->unstrip()
742 function unstripNoWiki( $text, $state ) {
743 return $state->unstripNoWiki( $text );
747 * @deprecated use $this->mStripState->unstripBoth()
749 function unstripForHTML( $text ) {
750 return $this->mStripState->unstripBoth( $text );
754 * Add an item to the strip state
755 * Returns the unique tag which must be inserted into the stripped text
756 * The tag will be replaced with the original text in unstrip()
760 function insertStripItem( $text ) {
761 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self::MARKER_SUFFIX;
762 $this->mMarkerIndex++;
763 $this->mStripState->general->setPair( $rnd, $text );
768 * Interface with html tidy
769 * @deprecated Use MWTidy::tidy()
771 public static function tidy( $text ) {
772 wfDeprecated( __METHOD__ );
773 return MWTidy::tidy( $text );
777 * parse the wiki syntax used to render tables
781 function doTableStuff( $text ) {
782 wfProfileIn( __METHOD__ );
784 $lines = StringUtils::explode( "\n", $text );
786 $td_history = array(); # Is currently a td tag open?
787 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
788 $tr_history = array(); # Is currently a tr tag open?
789 $tr_attributes = array(); # history of tr attributes
790 $has_opened_tr = array(); # Did this table open a <tr> element?
791 $indent_level = 0; # indent level of the table
793 foreach ( $lines as $outLine ) {
794 $line = trim( $outLine );
796 if ( $line === '' ) { # empty line, go to next line
797 $out .= $outLine."\n";
801 $first_character = $line[0];
804 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
805 # First check if we are starting a new table
806 $indent_level = strlen( $matches[1] );
808 $attributes = $this->mStripState->unstripBoth( $matches[2] );
809 $attributes = Sanitizer::fixTagAttributes( $attributes , 'table' );
811 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
812 array_push( $td_history , false );
813 array_push( $last_tag_history , '' );
814 array_push( $tr_history , false );
815 array_push( $tr_attributes , '' );
816 array_push( $has_opened_tr , false );
817 } elseif ( count( $td_history ) == 0 ) {
818 # Don't do any of the following
819 $out .= $outLine."\n";
821 } elseif ( substr( $line , 0 , 2 ) === '|}' ) {
822 # We are ending a table
823 $line = '</table>' . substr( $line , 2 );
824 $last_tag = array_pop( $last_tag_history );
826 if ( !array_pop( $has_opened_tr ) ) {
827 $line = "<tr><td></td></tr>{$line}";
830 if ( array_pop( $tr_history ) ) {
831 $line = "</tr>{$line}";
834 if ( array_pop( $td_history ) ) {
835 $line = "</{$last_tag}>{$line}";
837 array_pop( $tr_attributes );
838 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
839 } elseif ( substr( $line , 0 , 2 ) === '|-' ) {
840 # Now we have a table row
841 $line = preg_replace( '#^\|-+#', '', $line );
843 # Whats after the tag is now only attributes
844 $attributes = $this->mStripState->unstripBoth( $line );
845 $attributes = Sanitizer::fixTagAttributes( $attributes, 'tr' );
846 array_pop( $tr_attributes );
847 array_push( $tr_attributes, $attributes );
850 $last_tag = array_pop( $last_tag_history );
851 array_pop( $has_opened_tr );
852 array_push( $has_opened_tr , true );
854 if ( array_pop( $tr_history ) ) {
858 if ( array_pop( $td_history ) ) {
859 $line = "</{$last_tag}>{$line}";
863 array_push( $tr_history , false );
864 array_push( $td_history , false );
865 array_push( $last_tag_history , '' );
866 } elseif ( $first_character === '|' || $first_character === '!' || substr( $line , 0 , 2 ) === '|+' ) {
867 # This might be cell elements, td, th or captions
868 if ( substr( $line , 0 , 2 ) === '|+' ) {
869 $first_character = '+';
870 $line = substr( $line , 1 );
873 $line = substr( $line , 1 );
875 if ( $first_character === '!' ) {
876 $line = str_replace( '!!' , '||' , $line );
879 # Split up multiple cells on the same line.
880 # FIXME : This can result in improper nesting of tags processed
881 # by earlier parser steps, but should avoid splitting up eg
882 # attribute values containing literal "||".
883 $cells = StringUtils::explodeMarkup( '||' , $line );
887 # Loop through each table cell
888 foreach ( $cells as $cell ) {
890 if ( $first_character !== '+' ) {
891 $tr_after = array_pop( $tr_attributes );
892 if ( !array_pop( $tr_history ) ) {
893 $previous = "<tr{$tr_after}>\n";
895 array_push( $tr_history , true );
896 array_push( $tr_attributes , '' );
897 array_pop( $has_opened_tr );
898 array_push( $has_opened_tr , true );
901 $last_tag = array_pop( $last_tag_history );
903 if ( array_pop( $td_history ) ) {
904 $previous = "</{$last_tag}>\n{$previous}";
907 if ( $first_character === '|' ) {
909 } elseif ( $first_character === '!' ) {
911 } elseif ( $first_character === '+' ) {
912 $last_tag = 'caption';
917 array_push( $last_tag_history , $last_tag );
919 # A cell could contain both parameters and data
920 $cell_data = explode( '|' , $cell , 2 );
922 # Bug 553: Note that a '|' inside an invalid link should not
923 # be mistaken as delimiting cell parameters
924 if ( strpos( $cell_data[0], '[[' ) !== false ) {
925 $cell = "{$previous}<{$last_tag}>{$cell}";
926 } elseif ( count( $cell_data ) == 1 ) {
927 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
929 $attributes = $this->mStripState->unstripBoth( $cell_data[0] );
930 $attributes = Sanitizer::fixTagAttributes( $attributes , $last_tag );
931 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
935 array_push( $td_history , true );
938 $out .= $outLine . "\n";
941 # Closing open td, tr && table
942 while ( count( $td_history ) > 0 ) {
943 if ( array_pop( $td_history ) ) {
946 if ( array_pop( $tr_history ) ) {
949 if ( !array_pop( $has_opened_tr ) ) {
950 $out .= "<tr><td></td></tr>\n" ;
953 $out .= "</table>\n";
956 # Remove trailing line-ending (b/c)
957 if ( substr( $out, -1 ) === "\n" ) {
958 $out = substr( $out, 0, -1 );
961 # special case: don't return empty table
962 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
966 wfProfileOut( __METHOD__ );
972 * Helper function for parse() that transforms wiki markup into
973 * HTML. Only called for $mOutputType == self::OT_HTML.
977 function internalParse( $text, $isMain = true, $frame=false ) {
978 wfProfileIn( __METHOD__ );
982 # Hook to suspend the parser in this state
983 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState ) ) ) {
984 wfProfileOut( __METHOD__ );
988 # if $frame is provided, then use $frame for replacing any variables
990 # use frame depth to infer how include/noinclude tags should be handled
991 # depth=0 means this is the top-level document; otherwise it's an included document
992 if ( !$frame->depth ) {
995 $flag = Parser::PTD_FOR_INCLUSION;
997 $dom = $this->preprocessToDom( $text, $flag );
998 $text = $frame->expand( $dom );
1000 # if $frame is not provided, then use old-style replaceVariables
1001 $text = $this->replaceVariables( $text );
1004 $text = Sanitizer::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks ) );
1005 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState ) );
1007 # Tables need to come after variable replacement for things to work
1008 # properly; putting them before other transformations should keep
1009 # exciting things like link expansions from showing up in surprising
1011 $text = $this->doTableStuff( $text );
1013 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1015 $text = $this->doDoubleUnderscore( $text );
1017 $text = $this->doHeadings( $text );
1018 if ( $this->mOptions->getUseDynamicDates() ) {
1019 $df = DateFormatter::getInstance();
1020 $text = $df->reformat( $this->mOptions->getDateFormat(), $text );
1022 $text = $this->replaceInternalLinks( $text );
1023 $text = $this->doAllQuotes( $text );
1024 $text = $this->replaceExternalLinks( $text );
1026 # replaceInternalLinks may sometimes leave behind
1027 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1028 $text = str_replace( $this->mUniqPrefix.'NOPARSE', '', $text );
1030 $text = $this->doMagicLinks( $text );
1031 $text = $this->formatHeadings( $text, $origText, $isMain );
1033 wfProfileOut( __METHOD__ );
1038 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1039 * magic external links.
1044 function doMagicLinks( $text ) {
1045 wfProfileIn( __METHOD__ );
1046 $prots = $this->mUrlProtocols;
1047 $urlChar = self::EXT_LINK_URL_CLASS;
1048 $text = preg_replace_callback(
1050 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1051 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1052 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1053 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1054 ISBN\s+(\b # m[5]: ISBN, capture number
1055 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1056 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1057 [0-9Xx] # check digit
1059 )!x', array( &$this, 'magicLinkCallback' ), $text );
1060 wfProfileOut( __METHOD__ );
1064 function magicLinkCallback( $m ) {
1065 if ( isset( $m[1] ) && $m[1] !== '' ) {
1068 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1071 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1072 # Free external link
1073 return $this->makeFreeExternalLink( $m[0] );
1074 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1076 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1079 $CssClass = 'mw-magiclink-rfc';
1081 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1083 $urlmsg = 'pubmedurl';
1084 $CssClass = 'mw-magiclink-pmid';
1087 throw new MWException( __METHOD__.': unrecognised match type "' .
1088 substr( $m[0], 0, 20 ) . '"' );
1090 $url = wfMsgForContent( $urlmsg, $id);
1091 $sk = $this->mOptions->getSkin( $this->mTitle );
1092 $la = $sk->getExternalLinkAttributes( "external $CssClass" );
1093 return "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1094 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1097 $num = strtr( $isbn, array(
1102 $titleObj = SpecialPage::getTitleFor( 'Booksources', $num );
1104 $titleObj->escapeLocalUrl() .
1105 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1112 * Make a free external link, given a user-supplied URL
1116 function makeFreeExternalLink( $url ) {
1118 wfProfileIn( __METHOD__ );
1120 $sk = $this->mOptions->getSkin( $this->mTitle );
1123 # The characters '<' and '>' (which were escaped by
1124 # removeHTMLtags()) should not be included in
1125 # URLs, per RFC 2396.
1127 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE ) ) {
1128 $trail = substr( $url, $m2[0][1] ) . $trail;
1129 $url = substr( $url, 0, $m2[0][1] );
1132 # Move trailing punctuation to $trail
1134 # If there is no left bracket, then consider right brackets fair game too
1135 if ( strpos( $url, '(' ) === false ) {
1139 $numSepChars = strspn( strrev( $url ), $sep );
1140 if ( $numSepChars ) {
1141 $trail = substr( $url, -$numSepChars ) . $trail;
1142 $url = substr( $url, 0, -$numSepChars );
1145 $url = Sanitizer::cleanUrl( $url );
1147 # Is this an external image?
1148 $text = $this->maybeMakeExternalImage( $url );
1149 if ( $text === false ) {
1150 # Not an image, make a link
1151 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1152 $this->getExternalLinkAttribs( $url ) );
1153 # Register it in the output object...
1154 # Replace unnecessary URL escape codes with their equivalent characters
1155 $pasteurized = self::replaceUnusualEscapes( $url );
1156 $this->mOutput->addExternalLink( $pasteurized );
1158 wfProfileOut( __METHOD__ );
1159 return $text . $trail;
1164 * Parse headers and return html
1168 function doHeadings( $text ) {
1169 wfProfileIn( __METHOD__ );
1170 for ( $i = 6; $i >= 1; --$i ) {
1171 $h = str_repeat( '=', $i );
1172 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1173 "<h$i>\\1</h$i>", $text );
1175 wfProfileOut( __METHOD__ );
1180 * Replace single quotes with HTML markup
1182 * @return string the altered text
1184 function doAllQuotes( $text ) {
1185 wfProfileIn( __METHOD__ );
1187 $lines = StringUtils::explode( "\n", $text );
1188 foreach ( $lines as $line ) {
1189 $outtext .= $this->doQuotes( $line ) . "\n";
1191 $outtext = substr( $outtext, 0,-1 );
1192 wfProfileOut( __METHOD__ );
1197 * Helper function for doAllQuotes()
1199 public function doQuotes( $text ) {
1200 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1201 if ( count( $arr ) == 1 ) {
1204 # First, do some preliminary work. This may shift some apostrophes from
1205 # being mark-up to being text. It also counts the number of occurrences
1206 # of bold and italics mark-ups.
1209 for ( $i = 0; $i < count( $arr ); $i++ ) {
1210 if ( ( $i % 2 ) == 1 ) {
1211 # If there are ever four apostrophes, assume the first is supposed to
1212 # be text, and the remaining three constitute mark-up for bold text.
1213 if ( strlen( $arr[$i] ) == 4 ) {
1216 } elseif ( strlen( $arr[$i] ) > 5 ) {
1217 # If there are more than 5 apostrophes in a row, assume they're all
1218 # text except for the last 5.
1219 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1222 # Count the number of occurrences of bold and italics mark-ups.
1223 # We are not counting sequences of five apostrophes.
1224 if ( strlen( $arr[$i] ) == 2 ) {
1226 } elseif ( strlen( $arr[$i] ) == 3 ) {
1228 } elseif ( strlen( $arr[$i] ) == 5 ) {
1235 # If there is an odd number of both bold and italics, it is likely
1236 # that one of the bold ones was meant to be an apostrophe followed
1237 # by italics. Which one we cannot know for certain, but it is more
1238 # likely to be one that has a single-letter word before it.
1239 if ( ( $numbold % 2 == 1 ) && ( $numitalics % 2 == 1 ) ) {
1241 $firstsingleletterword = -1;
1242 $firstmultiletterword = -1;
1244 foreach ( $arr as $r ) {
1245 if ( ( $i % 2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1246 $x1 = substr( $arr[$i-1], -1 );
1247 $x2 = substr( $arr[$i-1], -2, 1 );
1248 if ( $x1 === ' ' ) {
1249 if ( $firstspace == -1 ) {
1252 } elseif ( $x2 === ' ') {
1253 if ( $firstsingleletterword == -1 ) {
1254 $firstsingleletterword = $i;
1257 if ( $firstmultiletterword == -1 ) {
1258 $firstmultiletterword = $i;
1265 # If there is a single-letter word, use it!
1266 if ( $firstsingleletterword > -1 ) {
1267 $arr[$firstsingleletterword] = "''";
1268 $arr[$firstsingleletterword-1] .= "'";
1269 } elseif ( $firstmultiletterword > -1 ) {
1270 # If not, but there's a multi-letter word, use that one.
1271 $arr[$firstmultiletterword] = "''";
1272 $arr[$firstmultiletterword-1] .= "'";
1273 } elseif ( $firstspace > -1 ) {
1274 # ... otherwise use the first one that has neither.
1275 # (notice that it is possible for all three to be -1 if, for example,
1276 # there is only one pentuple-apostrophe in the line)
1277 $arr[$firstspace] = "''";
1278 $arr[$firstspace-1] .= "'";
1282 # Now let's actually convert our apostrophic mush to HTML!
1287 foreach ( $arr as $r ) {
1288 if ( ( $i % 2 ) == 0 ) {
1289 if ( $state === 'both' ) {
1295 if ( strlen( $r ) == 2 ) {
1296 if ( $state === 'i' ) {
1297 $output .= '</i>'; $state = '';
1298 } elseif ( $state === 'bi' ) {
1299 $output .= '</i>'; $state = 'b';
1300 } elseif ( $state === 'ib' ) {
1301 $output .= '</b></i><b>'; $state = 'b';
1302 } elseif ( $state === 'both' ) {
1303 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1304 } else { # $state can be 'b' or ''
1305 $output .= '<i>'; $state .= 'i';
1307 } elseif ( strlen( $r ) == 3 ) {
1308 if ( $state === 'b' ) {
1309 $output .= '</b>'; $state = '';
1310 } elseif ( $state === 'bi' ) {
1311 $output .= '</i></b><i>'; $state = 'i';
1312 } elseif ( $state === 'ib' ) {
1313 $output .= '</b>'; $state = 'i';
1314 } elseif ( $state === 'both' ) {
1315 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1316 } else { # $state can be 'i' or ''
1317 $output .= '<b>'; $state .= 'b';
1319 } elseif ( strlen( $r ) == 5 ) {
1320 if ( $state === 'b' ) {
1321 $output .= '</b><i>'; $state = 'i';
1322 } elseif ( $state === 'i' ) {
1323 $output .= '</i><b>'; $state = 'b';
1324 } elseif ( $state === 'bi' ) {
1325 $output .= '</i></b>'; $state = '';
1326 } elseif ( $state === 'ib' ) {
1327 $output .= '</b></i>'; $state = '';
1328 } elseif ( $state === 'both' ) {
1329 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1330 } else { # ($state == '')
1331 $buffer = ''; $state = 'both';
1337 # Now close all remaining tags. Notice that the order is important.
1338 if ( $state === 'b' || $state === 'ib' ) {
1341 if ( $state === 'i' || $state === 'bi' || $state === 'ib' ) {
1344 if ( $state === 'bi' ) {
1347 # There might be lonely ''''', so make sure we have a buffer
1348 if ( $state === 'both' && $buffer ) {
1349 $output .= '<b><i>'.$buffer.'</i></b>';
1356 * Replace external links (REL)
1358 * Note: this is all very hackish and the order of execution matters a lot.
1359 * Make sure to run maintenance/parserTests.php if you change this code.
1363 function replaceExternalLinks( $text ) {
1365 wfProfileIn( __METHOD__ );
1367 $sk = $this->mOptions->getSkin( $this->mTitle );
1369 $bits = preg_split( $this->mExtLinkBracketedRegex, $text, -1, PREG_SPLIT_DELIM_CAPTURE );
1370 $s = array_shift( $bits );
1373 while ( $i<count( $bits ) ) {
1375 $protocol = $bits[$i++];
1376 $text = $bits[$i++];
1377 $trail = $bits[$i++];
1379 # The characters '<' and '>' (which were escaped by
1380 # removeHTMLtags()) should not be included in
1381 # URLs, per RFC 2396.
1383 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE ) ) {
1384 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1385 $url = substr( $url, 0, $m2[0][1] );
1388 # If the link text is an image URL, replace it with an <img> tag
1389 # This happened by accident in the original parser, but some people used it extensively
1390 $img = $this->maybeMakeExternalImage( $text );
1391 if ( $img !== false ) {
1397 # Set linktype for CSS - if URL==text, link is essentially free
1398 $linktype = ( $text === $url ) ? 'free' : 'text';
1400 # No link text, e.g. [http://domain.tld/some.link]
1401 if ( $text == '' ) {
1402 # Autonumber if allowed. See bug #5918
1403 if ( strpos( wfUrlProtocols(), substr( $protocol, 0, strpos( $protocol, ':' ) ) ) !== false ) {
1404 $langObj = $this->getFunctionLang();
1405 $text = '[' . $langObj->formatNum( ++$this->mAutonumber ) . ']';
1406 $linktype = 'autonumber';
1408 # Otherwise just use the URL
1409 $text = htmlspecialchars( $url );
1413 # Have link text, e.g. [http://domain.tld/some.link text]s
1415 list( $dtrail, $trail ) = Linker::splitTrail( $trail );
1418 $text = $wgContLang->markNoConversion( $text );
1420 $url = Sanitizer::cleanUrl( $url );
1422 # Use the encoded URL
1423 # This means that users can paste URLs directly into the text
1424 # Funny characters like ö aren't valid in URLs anyway
1425 # This was changed in August 2004
1426 $s .= $sk->makeExternalLink( $url, $text, false, $linktype,
1427 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1429 # Register link in the output object.
1430 # Replace unnecessary URL escape codes with the referenced character
1431 # This prevents spammers from hiding links from the filters
1432 $pasteurized = self::replaceUnusualEscapes( $url );
1433 $this->mOutput->addExternalLink( $pasteurized );
1436 wfProfileOut( __METHOD__ );
1441 * Get an associative array of additional HTML attributes appropriate for a
1442 * particular external link. This currently may include rel => nofollow
1443 * (depending on configuration, namespace, and the URL's domain) and/or a
1444 * target attribute (depending on configuration).
1446 * @param $url String: optional URL, to extract the domain from for rel =>
1447 * nofollow if appropriate
1448 * @return Array: associative array of HTML attributes
1450 function getExternalLinkAttribs( $url = false ) {
1452 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1453 $ns = $this->mTitle->getNamespace();
1454 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) ) {
1455 $attribs['rel'] = 'nofollow';
1457 global $wgNoFollowDomainExceptions;
1458 if ( $wgNoFollowDomainExceptions ) {
1459 $bits = wfParseUrl( $url );
1460 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1461 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1462 if ( substr( $bits['host'], -strlen( $domain ) ) == $domain ) {
1463 unset( $attribs['rel'] );
1470 if ( $this->mOptions->getExternalLinkTarget() ) {
1471 $attribs['target'] = $this->mOptions->getExternalLinkTarget();
1478 * Replace unusual URL escape codes with their equivalent characters
1480 * @param $url String
1483 * @todo This can merge genuinely required bits in the path or query string,
1484 * breaking legit URLs. A proper fix would treat the various parts of
1485 * the URL differently; as a workaround, just use the output for
1486 * statistical records, not for actual linking/output.
1488 static function replaceUnusualEscapes( $url ) {
1489 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1490 array( __CLASS__, 'replaceUnusualEscapesCallback' ), $url );
1494 * Callback function used in replaceUnusualEscapes().
1495 * Replaces unusual URL escape codes with their equivalent character
1497 private static function replaceUnusualEscapesCallback( $matches ) {
1498 $char = urldecode( $matches[0] );
1499 $ord = ord( $char );
1500 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1501 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1502 # No, shouldn't be escaped
1505 # Yes, leave it escaped
1511 * make an image if it's allowed, either through the global
1512 * option, through the exception, or through the on-wiki whitelist
1515 function maybeMakeExternalImage( $url ) {
1516 $sk = $this->mOptions->getSkin( $this->mTitle );
1517 $imagesfrom = $this->mOptions->getAllowExternalImagesFrom();
1518 $imagesexception = !empty( $imagesfrom );
1520 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1521 if ( $imagesexception && is_array( $imagesfrom ) ) {
1522 $imagematch = false;
1523 foreach ( $imagesfrom as $match ) {
1524 if ( strpos( $url, $match ) === 0 ) {
1529 } elseif ( $imagesexception ) {
1530 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1532 $imagematch = false;
1534 if ( $this->mOptions->getAllowExternalImages()
1535 || ( $imagesexception && $imagematch ) ) {
1536 if ( preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
1538 $text = $sk->makeExternalImage( $url );
1541 if ( !$text && $this->mOptions->getEnableImageWhitelist()
1542 && preg_match( self::EXT_IMAGE_REGEX, $url ) ) {
1543 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1544 foreach ( $whitelist as $entry ) {
1545 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1546 if ( strpos( $entry, '#' ) === 0 || $entry === '' ) {
1549 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1550 # Image matches a whitelist entry
1551 $text = $sk->makeExternalImage( $url );
1560 * Process [[ ]] wikilinks
1561 * @return String: processed text
1565 function replaceInternalLinks( $s ) {
1566 $this->mLinkHolders->merge( $this->replaceInternalLinks2( $s ) );
1571 * Process [[ ]] wikilinks (RIL)
1572 * @return LinkHolderArray
1576 function replaceInternalLinks2( &$s ) {
1579 wfProfileIn( __METHOD__ );
1581 wfProfileIn( __METHOD__.'-setup' );
1582 static $tc = FALSE, $e1, $e1_img;
1583 # the % is needed to support urlencoded titles as well
1585 $tc = Title::legalChars() . '#%';
1586 # Match a link having the form [[namespace:link|alternate]]trail
1587 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1588 # Match cases where there is no "]]", which might still be images
1589 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1592 $sk = $this->mOptions->getSkin( $this->mTitle );
1593 $holders = new LinkHolderArray( $this );
1595 # split the entire text string on occurences of [[
1596 $a = StringUtils::explode( '[[', ' ' . $s );
1597 # get the first element (all text up to first [[), and remove the space we added
1600 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1601 $s = substr( $s, 1 );
1603 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1605 if ( $useLinkPrefixExtension ) {
1606 # Match the end of a line for a word that's not followed by whitespace,
1607 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1608 $e2 = wfMsgForContent( 'linkprefix' );
1611 if ( is_null( $this->mTitle ) ) {
1612 wfProfileOut( __METHOD__.'-setup' );
1613 wfProfileOut( __METHOD__ );
1614 throw new MWException( __METHOD__.": \$this->mTitle is null\n" );
1616 $nottalk = !$this->mTitle->isTalkPage();
1618 if ( $useLinkPrefixExtension ) {
1620 if ( preg_match( $e2, $s, $m ) ) {
1621 $first_prefix = $m[2];
1623 $first_prefix = false;
1629 if ( $wgContLang->hasVariants() ) {
1630 $selflink = $wgContLang->autoConvertToAllVariants( $this->mTitle->getPrefixedText() );
1632 $selflink = array( $this->mTitle->getPrefixedText() );
1634 $useSubpages = $this->areSubpagesAllowed();
1635 wfProfileOut( __METHOD__.'-setup' );
1637 # Loop for each link
1638 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1639 # Check for excessive memory usage
1640 if ( $holders->isBig() ) {
1642 # Do the existence check, replace the link holders and clear the array
1643 $holders->replace( $s );
1647 if ( $useLinkPrefixExtension ) {
1648 wfProfileIn( __METHOD__.'-prefixhandling' );
1649 if ( preg_match( $e2, $s, $m ) ) {
1656 if ( $first_prefix ) {
1657 $prefix = $first_prefix;
1658 $first_prefix = false;
1660 wfProfileOut( __METHOD__.'-prefixhandling' );
1663 $might_be_img = false;
1665 wfProfileIn( __METHOD__."-e1" );
1666 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1668 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1669 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1670 # the real problem is with the $e1 regex
1673 # Still some problems for cases where the ] is meant to be outside punctuation,
1674 # and no image is in sight. See bug 2095.
1676 if ( $text !== '' &&
1677 substr( $m[3], 0, 1 ) === ']' &&
1678 strpos( $text, '[' ) !== false
1681 $text .= ']'; # so that replaceExternalLinks($text) works later
1682 $m[3] = substr( $m[3], 1 );
1684 # fix up urlencoded title texts
1685 if ( strpos( $m[1], '%' ) !== false ) {
1686 # Should anchors '#' also be rejected?
1687 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode( $m[1] ) );
1690 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1691 $might_be_img = true;
1693 if ( strpos( $m[1], '%' ) !== false ) {
1694 $m[1] = urldecode( $m[1] );
1697 } else { # Invalid form; output directly
1698 $s .= $prefix . '[[' . $line ;
1699 wfProfileOut( __METHOD__."-e1" );
1702 wfProfileOut( __METHOD__."-e1" );
1703 wfProfileIn( __METHOD__."-misc" );
1705 # Don't allow internal links to pages containing
1706 # PROTO: where PROTO is a valid URL protocol; these
1707 # should be external links.
1708 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1709 $s .= $prefix . '[[' . $line ;
1710 wfProfileOut( __METHOD__."-misc" );
1714 # Make subpage if necessary
1715 if ( $useSubpages ) {
1716 $link = $this->maybeDoSubpageLink( $m[1], $text );
1721 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1723 # Strip off leading ':'
1724 $link = substr( $link, 1 );
1727 wfProfileOut( __METHOD__."-misc" );
1728 wfProfileIn( __METHOD__."-title" );
1729 $nt = Title::newFromText( $this->mStripState->unstripNoWiki( $link ) );
1730 if ( $nt === null ) {
1731 $s .= $prefix . '[[' . $line;
1732 wfProfileOut( __METHOD__."-title" );
1736 $ns = $nt->getNamespace();
1737 $iw = $nt->getInterWiki();
1738 wfProfileOut( __METHOD__."-title" );
1740 if ( $might_be_img ) { # if this is actually an invalid link
1741 wfProfileIn( __METHOD__."-might_be_img" );
1742 if ( $ns == NS_FILE && $noforce ) { # but might be an image
1745 # look at the next 'line' to see if we can close it there
1747 $next_line = $a->current();
1748 if ( $next_line === false || $next_line === null ) {
1751 $m = explode( ']]', $next_line, 3 );
1752 if ( count( $m ) == 3 ) {
1753 # the first ]] closes the inner link, the second the image
1755 $text .= "[[{$m[0]}]]{$m[1]}";
1758 } elseif ( count( $m ) == 2 ) {
1759 # if there's exactly one ]] that's fine, we'll keep looking
1760 $text .= "[[{$m[0]}]]{$m[1]}";
1762 # if $next_line is invalid too, we need look no further
1763 $text .= '[[' . $next_line;
1768 # we couldn't find the end of this imageLink, so output it raw
1769 # but don't ignore what might be perfectly normal links in the text we've examined
1770 $holders->merge( $this->replaceInternalLinks2( $text ) );
1771 $s .= "{$prefix}[[$link|$text";
1772 # note: no $trail, because without an end, there *is* no trail
1773 wfProfileOut( __METHOD__."-might_be_img" );
1776 } else { # it's not an image, so output it raw
1777 $s .= "{$prefix}[[$link|$text";
1778 # note: no $trail, because without an end, there *is* no trail
1779 wfProfileOut( __METHOD__."-might_be_img" );
1782 wfProfileOut( __METHOD__."-might_be_img" );
1785 $wasblank = ( $text == '' );
1789 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1790 # [[Lista d''e paise d''o munno]] -> <a href="">Lista d''e paise d''o munno</a>
1791 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']] -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1792 $text = $this->doQuotes($text);
1795 # Link not escaped by : , create the various objects
1799 wfProfileIn( __METHOD__."-interwiki" );
1800 if ( $iw && $this->mOptions->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1801 $this->mOutput->addLanguageLink( $nt->getFullText() );
1802 $s = rtrim( $s . $prefix );
1803 $s .= trim( $trail, "\n" ) == '' ? '': $prefix . $trail;
1804 wfProfileOut( __METHOD__."-interwiki" );
1807 wfProfileOut( __METHOD__."-interwiki" );
1809 if ( $ns == NS_FILE ) {
1810 wfProfileIn( __METHOD__."-image" );
1811 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle ) ) {
1813 # if no parameters were passed, $text
1814 # becomes something like "File:Foo.png",
1815 # which we don't want to pass on to the
1819 # recursively parse links inside the image caption
1820 # actually, this will parse them in any other parameters, too,
1821 # but it might be hard to fix that, and it doesn't matter ATM
1822 $text = $this->replaceExternalLinks( $text );
1823 $holders->merge( $this->replaceInternalLinks2( $text ) );
1825 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1826 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1828 $s .= $prefix . $trail;
1830 $this->mOutput->addImage( $nt->getDBkey() );
1831 wfProfileOut( __METHOD__."-image" );
1836 if ( $ns == NS_CATEGORY ) {
1837 wfProfileIn( __METHOD__."-category" );
1838 $s = rtrim( $s . "\n" ); # bug 87
1841 $sortkey = $this->getDefaultSort();
1845 $sortkey = Sanitizer::decodeCharReferences( $sortkey );
1846 $sortkey = str_replace( "\n", '', $sortkey );
1847 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1848 $this->mOutput->addCategory( $nt->getDBkey(), $sortkey );
1851 * Strip the whitespace Category links produce, see bug 87
1852 * @todo We might want to use trim($tmp, "\n") here.
1854 $s .= trim( $prefix . $trail, "\n" ) == '' ? '': $prefix . $trail;
1856 wfProfileOut( __METHOD__."-category" );
1861 # Self-link checking
1862 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL ) {
1863 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1864 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1869 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1870 # FIXME: Should do batch file existence checks, see comment below
1871 if ( $ns == NS_MEDIA ) {
1872 wfProfileIn( __METHOD__."-media" );
1873 # Give extensions a chance to select the file revision for us
1874 $skip = $time = false;
1875 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1877 $link = $sk->link( $nt );
1879 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1881 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1882 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1883 $this->mOutput->addImage( $nt->getDBkey() );
1884 wfProfileOut( __METHOD__."-media" );
1888 wfProfileIn( __METHOD__."-always_known" );
1889 # Some titles, such as valid special pages or files in foreign repos, should
1890 # be shown as bluelinks even though they're not included in the page table
1892 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1893 # batch file existence checks for NS_FILE and NS_MEDIA
1894 if ( $iw == '' && $nt->isAlwaysKnown() ) {
1895 $this->mOutput->addLink( $nt );
1896 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1898 # Links will be added to the output link list after checking
1899 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1901 wfProfileOut( __METHOD__."-always_known" );
1903 wfProfileOut( __METHOD__ );
1908 * Make a link placeholder. The text returned can be later resolved to a real link with
1909 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1910 * parsing of interwiki links, and secondly to allow all existence checks and
1911 * article length checks (for stub links) to be bundled into a single query.
1915 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1916 return $this->mLinkHolders->makeHolder( $nt, $text, $query, $trail, $prefix );
1920 * Render a forced-blue link inline; protect against double expansion of
1921 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1922 * Since this little disaster has to split off the trail text to avoid
1923 * breaking URLs in the following text without breaking trails on the
1924 * wiki links, it's been made into a horrible function.
1927 * @param $text String
1928 * @param $query String
1929 * @param $trail String
1930 * @param $prefix String
1931 * @return String: HTML-wikitext mix oh yuck
1933 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1934 list( $inside, $trail ) = Linker::splitTrail( $trail );
1935 $sk = $this->mOptions->getSkin( $this->mTitle );
1936 # FIXME: use link() instead of deprecated makeKnownLinkObj()
1937 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1938 return $this->armorLinks( $link ) . $trail;
1942 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1943 * going to go through further parsing steps before inline URL expansion.
1945 * Not needed quite as much as it used to be since free links are a bit
1946 * more sensible these days. But bracketed links are still an issue.
1948 * @param $text String: more-or-less HTML
1949 * @return String: less-or-more HTML with NOPARSE bits
1951 function armorLinks( $text ) {
1952 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1953 "{$this->mUniqPrefix}NOPARSE$1", $text );
1957 * Return true if subpage links should be expanded on this page.
1960 function areSubpagesAllowed() {
1961 # Some namespaces don't allow subpages
1962 return MWNamespace::hasSubpages( $this->mTitle->getNamespace() );
1966 * Handle link to subpage if necessary
1968 * @param $target String: the source of the link
1969 * @param &$text String: the link text, modified as necessary
1970 * @return string the full name of the link
1973 function maybeDoSubpageLink( $target, &$text ) {
1974 return Linker::normalizeSubpageLink( $this->mTitle, $target, $text );
1978 * Used by doBlockLevels()
1981 function closeParagraph() {
1983 if ( $this->mLastSection != '' ) {
1984 $result = '</' . $this->mLastSection . ">\n";
1986 $this->mInPre = false;
1987 $this->mLastSection = '';
1992 * getCommon() returns the length of the longest common substring
1993 * of both arguments, starting at the beginning of both.
1996 function getCommon( $st1, $st2 ) {
1997 $fl = strlen( $st1 );
1998 $shorter = strlen( $st2 );
1999 if ( $fl < $shorter ) {
2003 for ( $i = 0; $i < $shorter; ++$i ) {
2004 if ( $st1{$i} != $st2{$i} ) {
2012 * These next three functions open, continue, and close the list
2013 * element appropriate to the prefix character passed into them.
2016 function openList( $char ) {
2017 $result = $this->closeParagraph();
2019 if ( '*' === $char ) {
2020 $result .= '<ul><li>';
2021 } elseif ( '#' === $char ) {
2022 $result .= '<ol><li>';
2023 } elseif ( ':' === $char ) {
2024 $result .= '<dl><dd>';
2025 } elseif ( ';' === $char ) {
2026 $result .= '<dl><dt>';
2027 $this->mDTopen = true;
2029 $result = '<!-- ERR 1 -->';
2037 * @param $char String
2040 function nextItem( $char ) {
2041 if ( '*' === $char || '#' === $char ) {
2043 } elseif ( ':' === $char || ';' === $char ) {
2045 if ( $this->mDTopen ) {
2048 if ( ';' === $char ) {
2049 $this->mDTopen = true;
2050 return $close . '<dt>';
2052 $this->mDTopen = false;
2053 return $close . '<dd>';
2056 return '<!-- ERR 2 -->';
2061 * @param $char String
2064 function closeList( $char ) {
2065 if ( '*' === $char ) {
2066 $text = '</li></ul>';
2067 } elseif ( '#' === $char ) {
2068 $text = '</li></ol>';
2069 } elseif ( ':' === $char ) {
2070 if ( $this->mDTopen ) {
2071 $this->mDTopen = false;
2072 $text = '</dt></dl>';
2074 $text = '</dd></dl>';
2077 return '<!-- ERR 3 -->';
2084 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2086 * @param $text String
2087 * @param $linestart Boolean: whether or not this is at the start of a line.
2089 * @return string the lists rendered as HTML
2091 function doBlockLevels( $text, $linestart ) {
2092 wfProfileIn( __METHOD__ );
2094 # Parsing through the text line by line. The main thing
2095 # happening here is handling of block-level elements p, pre,
2096 # and making lists from lines starting with * # : etc.
2098 $textLines = StringUtils::explode( "\n", $text );
2100 $lastPrefix = $output = '';
2101 $this->mDTopen = $inBlockElem = false;
2103 $paragraphStack = false;
2105 foreach ( $textLines as $oLine ) {
2107 if ( !$linestart ) {
2117 $lastPrefixLength = strlen( $lastPrefix );
2118 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2119 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2120 # If not in a <pre> element, scan for and figure out what prefixes are there.
2121 if ( !$this->mInPre ) {
2122 # Multiple prefixes may abut each other for nested lists.
2123 $prefixLength = strspn( $oLine, '*#:;' );
2124 $prefix = substr( $oLine, 0, $prefixLength );
2127 # ; and : are both from definition-lists, so they're equivalent
2128 # for the purposes of determining whether or not we need to open/close
2130 $prefix2 = str_replace( ';', ':', $prefix );
2131 $t = substr( $oLine, $prefixLength );
2132 $this->mInPre = (bool)$preOpenMatch;
2134 # Don't interpret any other prefixes in preformatted text
2136 $prefix = $prefix2 = '';
2141 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2142 # Same as the last item, so no need to deal with nesting or opening stuff
2143 $output .= $this->nextItem( substr( $prefix, -1 ) );
2144 $paragraphStack = false;
2146 if ( substr( $prefix, -1 ) === ';') {
2147 # The one nasty exception: definition lists work like this:
2148 # ; title : definition text
2149 # So we check for : in the remainder text to split up the
2150 # title and definition, without b0rking links.
2152 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2154 $output .= $term . $this->nextItem( ':' );
2157 } elseif ( $prefixLength || $lastPrefixLength ) {
2158 # We need to open or close prefixes, or both.
2160 # Either open or close a level...
2161 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2162 $paragraphStack = false;
2164 # Close all the prefixes which aren't shared.
2165 while ( $commonPrefixLength < $lastPrefixLength ) {
2166 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2167 --$lastPrefixLength;
2170 # Continue the current prefix if appropriate.
2171 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2172 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2175 # Open prefixes where appropriate.
2176 while ( $prefixLength > $commonPrefixLength ) {
2177 $char = substr( $prefix, $commonPrefixLength, 1 );
2178 $output .= $this->openList( $char );
2180 if ( ';' === $char ) {
2181 # FIXME: This is dupe of code above
2182 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2184 $output .= $term . $this->nextItem( ':' );
2187 ++$commonPrefixLength;
2189 $lastPrefix = $prefix2;
2192 # If we have no prefixes, go to paragraph mode.
2193 if ( 0 == $prefixLength ) {
2194 wfProfileIn( __METHOD__."-paragraph" );
2195 # No prefix (not in list)--go to paragraph mode
2196 # XXX: use a stack for nestable elements like span, table and div
2197 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2198 $closematch = preg_match(
2199 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2200 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2201 if ( $openmatch or $closematch ) {
2202 $paragraphStack = false;
2203 #Â TODO bug 5718: paragraph closed
2204 $output .= $this->closeParagraph();
2205 if ( $preOpenMatch and !$preCloseMatch ) {
2206 $this->mInPre = true;
2208 $inBlockElem = !$closematch;
2209 } elseif ( !$inBlockElem && !$this->mInPre ) {
2210 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection === 'pre' || trim( $t ) != '' ) ) {
2212 if ( $this->mLastSection !== 'pre' ) {
2213 $paragraphStack = false;
2214 $output .= $this->closeParagraph().'<pre>';
2215 $this->mLastSection = 'pre';
2217 $t = substr( $t, 1 );
2220 if ( trim( $t ) === '' ) {
2221 if ( $paragraphStack ) {
2222 $output .= $paragraphStack.'<br />';
2223 $paragraphStack = false;
2224 $this->mLastSection = 'p';
2226 if ( $this->mLastSection !== 'p' ) {
2227 $output .= $this->closeParagraph();
2228 $this->mLastSection = '';
2229 $paragraphStack = '<p>';
2231 $paragraphStack = '</p><p>';
2235 if ( $paragraphStack ) {
2236 $output .= $paragraphStack;
2237 $paragraphStack = false;
2238 $this->mLastSection = 'p';
2239 } elseif ( $this->mLastSection !== 'p' ) {
2240 $output .= $this->closeParagraph().'<p>';
2241 $this->mLastSection = 'p';
2246 wfProfileOut( __METHOD__."-paragraph" );
2248 # somewhere above we forget to get out of pre block (bug 785)
2249 if ( $preCloseMatch && $this->mInPre ) {
2250 $this->mInPre = false;
2252 if ( $paragraphStack === false ) {
2256 while ( $prefixLength ) {
2257 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2260 if ( $this->mLastSection != '' ) {
2261 $output .= '</' . $this->mLastSection . '>';
2262 $this->mLastSection = '';
2265 wfProfileOut( __METHOD__ );
2270 * Split up a string on ':', ignoring any occurences inside tags
2271 * to prevent illegal overlapping.
2273 * @param $str String: the string to split
2274 * @param &$before String: set to everything before the ':'
2275 * @param &$after String: set to everything after the ':'
2276 * return String: the position of the ':', or false if none found
2278 function findColonNoLinks( $str, &$before, &$after ) {
2279 wfProfileIn( __METHOD__ );
2281 $pos = strpos( $str, ':' );
2282 if ( $pos === false ) {
2284 wfProfileOut( __METHOD__ );
2288 $lt = strpos( $str, '<' );
2289 if ( $lt === false || $lt > $pos ) {
2290 # Easy; no tag nesting to worry about
2291 $before = substr( $str, 0, $pos );
2292 $after = substr( $str, $pos+1 );
2293 wfProfileOut( __METHOD__ );
2297 # Ugly state machine to walk through avoiding tags.
2298 $state = self::COLON_STATE_TEXT;
2300 $len = strlen( $str );
2301 for( $i = 0; $i < $len; $i++ ) {
2305 # (Using the number is a performance hack for common cases)
2306 case 0: # self::COLON_STATE_TEXT:
2309 # Could be either a <start> tag or an </end> tag
2310 $state = self::COLON_STATE_TAGSTART;
2313 if ( $stack == 0 ) {
2315 $before = substr( $str, 0, $i );
2316 $after = substr( $str, $i + 1 );
2317 wfProfileOut( __METHOD__ );
2320 # Embedded in a tag; don't break it.
2323 # Skip ahead looking for something interesting
2324 $colon = strpos( $str, ':', $i );
2325 if ( $colon === false ) {
2326 # Nothing else interesting
2327 wfProfileOut( __METHOD__ );
2330 $lt = strpos( $str, '<', $i );
2331 if ( $stack === 0 ) {
2332 if ( $lt === false || $colon < $lt ) {
2334 $before = substr( $str, 0, $colon );
2335 $after = substr( $str, $colon + 1 );
2336 wfProfileOut( __METHOD__ );
2340 if ( $lt === false ) {
2341 # Nothing else interesting to find; abort!
2342 # We're nested, but there's no close tags left. Abort!
2345 # Skip ahead to next tag start
2347 $state = self::COLON_STATE_TAGSTART;
2350 case 1: # self::COLON_STATE_TAG:
2355 $state = self::COLON_STATE_TEXT;
2358 # Slash may be followed by >?
2359 $state = self::COLON_STATE_TAGSLASH;
2365 case 2: # self::COLON_STATE_TAGSTART:
2368 $state = self::COLON_STATE_CLOSETAG;
2371 $state = self::COLON_STATE_COMMENT;
2374 # Illegal early close? This shouldn't happen D:
2375 $state = self::COLON_STATE_TEXT;
2378 $state = self::COLON_STATE_TAG;
2381 case 3: # self::COLON_STATE_CLOSETAG:
2386 wfDebug( __METHOD__.": Invalid input; too many close tags\n" );
2387 wfProfileOut( __METHOD__ );
2390 $state = self::COLON_STATE_TEXT;
2393 case self::COLON_STATE_TAGSLASH:
2395 # Yes, a self-closed tag <blah/>
2396 $state = self::COLON_STATE_TEXT;
2398 # Probably we're jumping the gun, and this is an attribute
2399 $state = self::COLON_STATE_TAG;
2402 case 5: # self::COLON_STATE_COMMENT:
2404 $state = self::COLON_STATE_COMMENTDASH;
2407 case self::COLON_STATE_COMMENTDASH:
2409 $state = self::COLON_STATE_COMMENTDASHDASH;
2411 $state = self::COLON_STATE_COMMENT;
2414 case self::COLON_STATE_COMMENTDASHDASH:
2416 $state = self::COLON_STATE_TEXT;
2418 $state = self::COLON_STATE_COMMENT;
2422 throw new MWException( "State machine error in " . __METHOD__ );
2426 wfDebug( __METHOD__.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2427 wfProfileOut( __METHOD__ );
2430 wfProfileOut( __METHOD__ );
2435 * Return value of a magic variable (like PAGENAME)
2439 function getVariableValue( $index, $frame=false ) {
2440 global $wgContLang, $wgSitename, $wgServer;
2441 global $wgArticlePath, $wgScriptPath, $wgStylePath;
2444 * Some of these require message or data lookups and can be
2445 * expensive to check many times.
2447 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache ) ) ) {
2448 if ( isset( $this->mVarCache[$index] ) ) {
2449 return $this->mVarCache[$index];
2453 $ts = wfTimestamp( TS_UNIX, $this->mOptions->getTimestamp() );
2454 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2457 global $wgLocaltimezone;
2458 if ( isset( $wgLocaltimezone ) ) {
2459 $oldtz = date_default_timezone_get();
2460 date_default_timezone_set( $wgLocaltimezone );
2463 $localTimestamp = date( 'YmdHis', $ts );
2464 $localMonth = date( 'm', $ts );
2465 $localMonth1 = date( 'n', $ts );
2466 $localMonthName = date( 'n', $ts );
2467 $localDay = date( 'j', $ts );
2468 $localDay2 = date( 'd', $ts );
2469 $localDayOfWeek = date( 'w', $ts );
2470 $localWeek = date( 'W', $ts );
2471 $localYear = date( 'Y', $ts );
2472 $localHour = date( 'H', $ts );
2473 if ( isset( $wgLocaltimezone ) ) {
2474 date_default_timezone_set( $oldtz );
2478 case 'currentmonth':
2479 $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2481 case 'currentmonth1':
2482 $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2484 case 'currentmonthname':
2485 $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2487 case 'currentmonthnamegen':
2488 $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2490 case 'currentmonthabbrev':
2491 $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2494 $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2497 $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2500 $value = $wgContLang->formatNum( $localMonth );
2503 $value = $wgContLang->formatNum( $localMonth1 );
2505 case 'localmonthname':
2506 $value = $wgContLang->getMonthName( $localMonthName );
2508 case 'localmonthnamegen':
2509 $value = $wgContLang->getMonthNameGen( $localMonthName );
2511 case 'localmonthabbrev':
2512 $value = $wgContLang->getMonthAbbreviation( $localMonthName );
2515 $value = $wgContLang->formatNum( $localDay );
2518 $value = $wgContLang->formatNum( $localDay2 );
2521 $value = wfEscapeWikiText( $this->mTitle->getText() );
2524 $value = $this->mTitle->getPartialURL();
2526 case 'fullpagename':
2527 $value = wfEscapeWikiText( $this->mTitle->getPrefixedText() );
2529 case 'fullpagenamee':
2530 $value = $this->mTitle->getPrefixedURL();
2533 $value = wfEscapeWikiText( $this->mTitle->getSubpageText() );
2535 case 'subpagenamee':
2536 $value = $this->mTitle->getSubpageUrlForm();
2538 case 'basepagename':
2539 $value = wfEscapeWikiText( $this->mTitle->getBaseText() );
2541 case 'basepagenamee':
2542 $value = wfUrlEncode( str_replace( ' ', '_', $this->mTitle->getBaseText() ) );
2544 case 'talkpagename':
2545 if ( $this->mTitle->canTalk() ) {
2546 $talkPage = $this->mTitle->getTalkPage();
2547 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2552 case 'talkpagenamee':
2553 if ( $this->mTitle->canTalk() ) {
2554 $talkPage = $this->mTitle->getTalkPage();
2555 $value = $talkPage->getPrefixedUrl();
2560 case 'subjectpagename':
2561 $subjPage = $this->mTitle->getSubjectPage();
2562 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2564 case 'subjectpagenamee':
2565 $subjPage = $this->mTitle->getSubjectPage();
2566 $value = $subjPage->getPrefixedUrl();
2569 # Let the edit saving system know we should parse the page
2570 # *after* a revision ID has been assigned.
2571 $this->mOutput->setFlag( 'vary-revision' );
2572 wfDebug( __METHOD__ . ": {{REVISIONID}} used, setting vary-revision...\n" );
2573 $value = $this->mRevisionId;
2576 # Let the edit saving system know we should parse the page
2577 # *after* a revision ID has been assigned. This is for null edits.
2578 $this->mOutput->setFlag( 'vary-revision' );
2579 wfDebug( __METHOD__ . ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2580 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2582 case 'revisionday2':
2583 # Let the edit saving system know we should parse the page
2584 # *after* a revision ID has been assigned. This is for null edits.
2585 $this->mOutput->setFlag( 'vary-revision' );
2586 wfDebug( __METHOD__ . ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2587 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2589 case 'revisionmonth':
2590 # Let the edit saving system know we should parse the page
2591 # *after* a revision ID has been assigned. This is for null edits.
2592 $this->mOutput->setFlag( 'vary-revision' );
2593 wfDebug( __METHOD__ . ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2594 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2596 case 'revisionmonth1':
2597 # Let the edit saving system know we should parse the page
2598 # *after* a revision ID has been assigned. This is for null edits.
2599 $this->mOutput->setFlag( 'vary-revision' );
2600 wfDebug( __METHOD__ . ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2601 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2603 case 'revisionyear':
2604 # Let the edit saving system know we should parse the page
2605 # *after* a revision ID has been assigned. This is for null edits.
2606 $this->mOutput->setFlag( 'vary-revision' );
2607 wfDebug( __METHOD__ . ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2608 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2610 case 'revisiontimestamp':
2611 # Let the edit saving system know we should parse the page
2612 # *after* a revision ID has been assigned. This is for null edits.
2613 $this->mOutput->setFlag( 'vary-revision' );
2614 wfDebug( __METHOD__ . ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2615 $value = $this->getRevisionTimestamp();
2617 case 'revisionuser':
2618 # Let the edit saving system know we should parse the page
2619 # *after* a revision ID has been assigned. This is for null edits.
2620 $this->mOutput->setFlag( 'vary-revision' );
2621 wfDebug( __METHOD__ . ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2622 $value = $this->getRevisionUser();
2625 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2628 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) );
2631 $value = $this->mTitle->canTalk() ? str_replace( '_',' ',$this->mTitle->getTalkNsText() ) : '';
2634 $value = $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : '';
2636 case 'subjectspace':
2637 $value = $this->mTitle->getSubjectNsText();
2639 case 'subjectspacee':
2640 $value = ( wfUrlencode( $this->mTitle->getSubjectNsText() ) );
2642 case 'currentdayname':
2643 $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) + 1 );
2646 $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2649 $value = $wgContLang->time( wfTimestamp( TS_MW, $ts ), false, false );
2652 $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2655 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2656 # int to remove the padding
2657 $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2660 $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2662 case 'localdayname':
2663 $value = $wgContLang->getWeekdayName( $localDayOfWeek + 1 );
2666 $value = $wgContLang->formatNum( $localYear, true );
2669 $value = $wgContLang->time( $localTimestamp, false, false );
2672 $value = $wgContLang->formatNum( $localHour, true );
2675 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2676 # int to remove the padding
2677 $value = $wgContLang->formatNum( (int)$localWeek );
2680 $value = $wgContLang->formatNum( $localDayOfWeek );
2682 case 'numberofarticles':
2683 $value = $wgContLang->formatNum( SiteStats::articles() );
2685 case 'numberoffiles':
2686 $value = $wgContLang->formatNum( SiteStats::images() );
2688 case 'numberofusers':
2689 $value = $wgContLang->formatNum( SiteStats::users() );
2691 case 'numberofactiveusers':
2692 $value = $wgContLang->formatNum( SiteStats::activeUsers() );
2694 case 'numberofpages':
2695 $value = $wgContLang->formatNum( SiteStats::pages() );
2697 case 'numberofadmins':
2698 $value = $wgContLang->formatNum( SiteStats::numberingroup( 'sysop' ) );
2700 case 'numberofedits':
2701 $value = $wgContLang->formatNum( SiteStats::edits() );
2703 case 'numberofviews':
2704 $value = $wgContLang->formatNum( SiteStats::views() );
2706 case 'currenttimestamp':
2707 $value = wfTimestamp( TS_MW, $ts );
2709 case 'localtimestamp':
2710 $value = $localTimestamp;
2712 case 'currentversion':
2713 $value = SpecialVersion::getVersion();
2716 return $wgArticlePath;
2722 wfSuppressWarnings(); # May give an E_WARNING in PHP < 5.3.3
2723 $serverName = parse_url( $wgServer, PHP_URL_HOST );
2724 wfRestoreWarnings();
2725 return $serverName ? $serverName : $wgServer;
2727 return $wgScriptPath;
2729 return $wgStylePath;
2730 case 'directionmark':
2731 return $wgContLang->getDirMark();
2732 case 'contentlanguage':
2733 global $wgLanguageCode;
2734 return $wgLanguageCode;
2737 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache, &$index, &$ret, &$frame ) ) ) {
2745 $this->mVarCache[$index] = $value;
2751 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2755 function initialiseVariables() {
2756 wfProfileIn( __METHOD__ );
2757 $variableIDs = MagicWord::getVariableIDs();
2758 $substIDs = MagicWord::getSubstIDs();
2760 $this->mVariables = new MagicWordArray( $variableIDs );
2761 $this->mSubstWords = new MagicWordArray( $substIDs );
2762 wfProfileOut( __METHOD__ );
2766 * Preprocess some wikitext and return the document tree.
2767 * This is the ghost of replace_variables().
2769 * @param $text String: The text to parse
2770 * @param $flags Integer: bitwise combination of:
2771 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2772 * included. Default is to assume a direct page view.
2774 * The generated DOM tree must depend only on the input text and the flags.
2775 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2777 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2778 * change in the DOM tree for a given text, must be passed through the section identifier
2779 * in the section edit link and thus back to extractSections().
2781 * The output of this function is currently only cached in process memory, but a persistent
2782 * cache may be implemented at a later date which takes further advantage of these strict
2783 * dependency requirements.
2787 function preprocessToDom( $text, $flags = 0 ) {
2788 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2793 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2795 public static function splitWhitespace( $s ) {
2796 $ltrimmed = ltrim( $s );
2797 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2798 $trimmed = rtrim( $ltrimmed );
2799 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2801 $w2 = substr( $ltrimmed, -$diff );
2805 return array( $w1, $trimmed, $w2 );
2809 * Replace magic variables, templates, and template arguments
2810 * with the appropriate text. Templates are substituted recursively,
2811 * taking care to avoid infinite loops.
2813 * Note that the substitution depends on value of $mOutputType:
2814 * self::OT_WIKI: only {{subst:}} templates
2815 * self::OT_PREPROCESS: templates but not extension tags
2816 * self::OT_HTML: all templates and extension tags
2818 * @param $text String: the text to transform
2819 * @param $frame PPFrame Object describing the arguments passed to the template.
2820 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2821 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2822 * @param $argsOnly Boolean: only do argument (triple-brace) expansion, not double-brace expansion
2825 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2826 # Is there any text? Also, Prevent too big inclusions!
2827 if ( strlen( $text ) < 1 || strlen( $text ) > $this->mOptions->getMaxIncludeSize() ) {
2830 wfProfileIn( __METHOD__ );
2832 if ( $frame === false ) {
2833 $frame = $this->getPreprocessor()->newFrame();
2834 } elseif ( !( $frame instanceof PPFrame ) ) {
2835 wfDebug( __METHOD__." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2836 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2839 $dom = $this->preprocessToDom( $text );
2840 $flags = $argsOnly ? PPFrame::NO_TEMPLATES : 0;
2841 $text = $frame->expand( $dom, $flags );
2843 wfProfileOut( __METHOD__ );
2847 # Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2848 static function createAssocArgs( $args ) {
2849 $assocArgs = array();
2851 foreach ( $args as $arg ) {
2852 $eqpos = strpos( $arg, '=' );
2853 if ( $eqpos === false ) {
2854 $assocArgs[$index++] = $arg;
2856 $name = trim( substr( $arg, 0, $eqpos ) );
2857 $value = trim( substr( $arg, $eqpos+1 ) );
2858 if ( $value === false ) {
2861 if ( $name !== false ) {
2862 $assocArgs[$name] = $value;
2871 * Warn the user when a parser limitation is reached
2872 * Will warn at most once the user per limitation type
2874 * @param $limitationType String: should be one of:
2875 * 'expensive-parserfunction' (corresponding messages:
2876 * 'expensive-parserfunction-warning',
2877 * 'expensive-parserfunction-category')
2878 * 'post-expand-template-argument' (corresponding messages:
2879 * 'post-expand-template-argument-warning',
2880 * 'post-expand-template-argument-category')
2881 * 'post-expand-template-inclusion' (corresponding messages:
2882 * 'post-expand-template-inclusion-warning',
2883 * 'post-expand-template-inclusion-category')
2884 * @param $current Current value
2885 * @param $max Maximum allowed, when an explicit limit has been
2886 * exceeded, provide the values (optional)
2888 function limitationWarn( $limitationType, $current=null, $max=null) {
2889 # does no harm if $current and $max are present but are unnecessary for the message
2890 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
2891 $this->mOutput->addWarning( $warning );
2892 $this->addTrackingCategory( "$limitationType-category" );
2896 * Return the text of a template, after recursively
2897 * replacing any variables or templates within the template.
2899 * @param $piece Array: the parts of the template
2900 * $piece['title']: the title, i.e. the part before the |
2901 * $piece['parts']: the parameter array
2902 * $piece['lineStart']: whether the brace was at the start of a line
2903 * @param $frame PPFrame The current frame, contains template arguments
2904 * @return String: the text of the template
2907 function braceSubstitution( $piece, $frame ) {
2908 global $wgContLang, $wgNonincludableNamespaces;
2909 wfProfileIn( __METHOD__ );
2910 wfProfileIn( __METHOD__.'-setup' );
2913 $found = false; # $text has been filled
2914 $nowiki = false; # wiki markup in $text should be escaped
2915 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2916 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2917 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2918 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2920 # Title object, where $text came from
2923 # $part1 is the bit before the first |, and must contain only title characters.
2924 # Various prefixes will be stripped from it later.
2925 $titleWithSpaces = $frame->expand( $piece['title'] );
2926 $part1 = trim( $titleWithSpaces );
2929 # Original title text preserved for various purposes
2930 $originalTitle = $part1;
2932 # $args is a list of argument nodes, starting from index 0, not including $part1
2933 $args = ( null == $piece['parts'] ) ? array() : $piece['parts'];
2934 wfProfileOut( __METHOD__.'-setup' );
2937 wfProfileIn( __METHOD__.'-modifiers' );
2940 $substMatch = $this->mSubstWords->matchStartAndRemove( $part1 );
2942 # Possibilities for substMatch: "subst", "safesubst" or FALSE
2943 # Decide whether to expand template or keep wikitext as-is.
2944 if ( $this->ot['wiki'] ) {
2945 if ( $substMatch === false ) {
2946 $literal = true; # literal when in PST with no prefix
2948 $literal = false; # expand when in PST with subst: or safesubst:
2951 if ( $substMatch == 'subst' ) {
2952 $literal = true; # literal when not in PST with plain subst:
2954 $literal = false; # expand when not in PST with safesubst: or no prefix
2958 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2965 if ( !$found && $args->getLength() == 0 ) {
2966 $id = $this->mVariables->matchStartToEnd( $part1 );
2967 if ( $id !== false ) {
2968 $text = $this->getVariableValue( $id, $frame );
2969 if ( MagicWord::getCacheTTL( $id ) > -1 ) {
2970 $this->mOutput->updateCacheExpiry( MagicWord::getCacheTTL( $id ) );
2976 # MSG, MSGNW and RAW
2979 $mwMsgnw = MagicWord::get( 'msgnw' );
2980 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2983 # Remove obsolete MSG:
2984 $mwMsg = MagicWord::get( 'msg' );
2985 $mwMsg->matchStartAndRemove( $part1 );
2989 $mwRaw = MagicWord::get( 'raw' );
2990 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2991 $forceRawInterwiki = true;
2994 wfProfileOut( __METHOD__.'-modifiers' );
2998 wfProfileIn( __METHOD__ . '-pfunc' );
3000 $colonPos = strpos( $part1, ':' );
3001 if ( $colonPos !== false ) {
3002 # Case sensitive functions
3003 $function = substr( $part1, 0, $colonPos );
3004 if ( isset( $this->mFunctionSynonyms[1][$function] ) ) {
3005 $function = $this->mFunctionSynonyms[1][$function];
3007 # Case insensitive functions
3008 $function = $wgContLang->lc( $function );
3009 if ( isset( $this->mFunctionSynonyms[0][$function] ) ) {
3010 $function = $this->mFunctionSynonyms[0][$function];
3016 list( $callback, $flags ) = $this->mFunctionHooks[$function];
3017 $initialArgs = array( &$this );
3018 $funcArgs = array( trim( substr( $part1, $colonPos + 1 ) ) );
3019 if ( $flags & SFH_OBJECT_ARGS ) {
3020 # Add a frame parameter, and pass the arguments as an array
3021 $allArgs = $initialArgs;
3022 $allArgs[] = $frame;
3023 for ( $i = 0; $i < $args->getLength(); $i++ ) {
3024 $funcArgs[] = $args->item( $i );
3026 $allArgs[] = $funcArgs;
3028 # Convert arguments to plain text
3029 for ( $i = 0; $i < $args->getLength(); $i++ ) {
3030 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3032 $allArgs = array_merge( $initialArgs, $funcArgs );
3035 # Workaround for PHP bug 35229 and similar
3036 if ( !is_callable( $callback ) ) {
3037 wfProfileOut( __METHOD__ . '-pfunc' );
3038 wfProfileOut( __METHOD__ );
3039 throw new MWException( "Tag hook for $function is not callable\n" );
3041 $result = call_user_func_array( $callback, $allArgs );
3044 $preprocessFlags = 0;
3046 if ( is_array( $result ) ) {
3047 if ( isset( $result[0] ) ) {
3049 unset( $result[0] );
3052 # Extract flags into the local scope
3053 # This allows callers to set flags such as nowiki, found, etc.
3059 $text = $this->preprocessToDom( $text, $preprocessFlags );
3064 wfProfileOut( __METHOD__ . '-pfunc' );
3067 # Finish mangling title and then check for loops.
3068 # Set $title to a Title object and $titleText to the PDBK
3071 # Split the title into page and subpage
3073 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3074 if ( $subpage !== '' ) {
3075 $ns = $this->mTitle->getNamespace();
3077 $title = Title::newFromText( $part1, $ns );
3079 $titleText = $title->getPrefixedText();
3080 # Check for language variants if the template is not found
3081 if ( $wgContLang->hasVariants() && $title->getArticleID() == 0 ) {
3082 $wgContLang->findVariantLink( $part1, $title, true );
3084 # Do recursion depth check
3085 $limit = $this->mOptions->getMaxTemplateDepth();
3086 if ( $frame->depth >= $limit ) {
3088 $text = '<span class="error">'
3089 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
3095 # Load from database
3096 if ( !$found && $title ) {
3097 wfProfileIn( __METHOD__ . '-loadtpl' );
3098 if ( !$title->isExternal() ) {
3099 if ( $title->getNamespace() == NS_SPECIAL
3100 && $this->mOptions->getAllowSpecialInclusion()
3101 && $this->ot['html'] )
3103 $text = SpecialPage::capturePath( $title );
3104 if ( is_string( $text ) ) {
3107 $this->disableCache();
3109 } elseif ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3110 $found = false; # access denied
3111 wfDebug( __METHOD__.": template inclusion denied for " . $title->getPrefixedDBkey() );
3113 list( $text, $title ) = $this->getTemplateDom( $title );
3114 if ( $text !== false ) {
3120 # If the title is valid but undisplayable, make a link to it
3121 if ( !$found && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3122 $text = "[[:$titleText]]";
3125 } elseif ( $title->isTrans() ) {
3126 # Interwiki transclusion
3127 if ( $this->ot['html'] && !$forceRawInterwiki ) {
3128 $text = $this->interwikiTransclude( $title, 'render' );
3131 $text = $this->interwikiTransclude( $title, 'raw' );
3132 # Preprocess it like a template
3133 $text = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3139 # Do infinite loop check
3140 # This has to be done after redirect resolution to avoid infinite loops via redirects
3141 if ( !$frame->loopCheck( $title ) ) {
3143 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3144 wfDebug( __METHOD__.": template loop broken at '$titleText'\n" );
3146 wfProfileOut( __METHOD__ . '-loadtpl' );
3149 # If we haven't found text to substitute by now, we're done
3150 # Recover the source wikitext and return it
3152 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3153 wfProfileOut( __METHOD__ );
3154 return array( 'object' => $text );
3157 # Expand DOM-style return values in a child frame
3158 if ( $isChildObj ) {
3159 # Clean up argument array
3160 $newFrame = $frame->newChild( $args, $title );
3163 $text = $newFrame->expand( $text, PPFrame::RECOVER_ORIG );
3164 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3165 # Expansion is eligible for the empty-frame cache
3166 if ( isset( $this->mTplExpandCache[$titleText] ) ) {
3167 $text = $this->mTplExpandCache[$titleText];
3169 $text = $newFrame->expand( $text );
3170 $this->mTplExpandCache[$titleText] = $text;
3173 # Uncached expansion
3174 $text = $newFrame->expand( $text );
3177 if ( $isLocalObj && $nowiki ) {
3178 $text = $frame->expand( $text, PPFrame::RECOVER_ORIG );
3179 $isLocalObj = false;
3182 # Replace raw HTML by a placeholder
3183 # Add a blank line preceding, to prevent it from mucking up
3184 # immediately preceding headings
3186 $text = "\n\n" . $this->insertStripItem( $text );
3187 } elseif ( $nowiki && ( $this->ot['html'] || $this->ot['pre'] ) ) {
3188 # Escape nowiki-style return values
3189 $text = wfEscapeWikiText( $text );
3190 } elseif ( is_string( $text )
3191 && !$piece['lineStart']
3192 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3194 # Bug 529: if the template begins with a table or block-level
3195 # element, it should be treated as beginning a new line.
3196 # This behaviour is somewhat controversial.
3197 $text = "\n" . $text;
3200 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3201 # Error, oversize inclusion
3202 if ( $titleText !== false ) {
3203 # Make a working, properly escaped link if possible (bug 23588)
3204 $text = "[[:$titleText]]";
3206 # This will probably not be a working link, but at least it may
3207 # provide some hint of where the problem is
3208 preg_replace( '/^:/', '', $originalTitle );
3209 $text = "[[:$originalTitle]]";
3211 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3212 $this->limitationWarn( 'post-expand-template-inclusion' );
3215 if ( $isLocalObj ) {
3216 $ret = array( 'object' => $text );
3218 $ret = array( 'text' => $text );
3221 wfProfileOut( __METHOD__ );
3226 * Get the semi-parsed DOM representation of a template with a given title,
3227 * and its redirect destination title. Cached.
3229 function getTemplateDom( $title ) {
3230 $cacheTitle = $title;
3231 $titleText = $title->getPrefixedDBkey();
3233 if ( isset( $this->mTplRedirCache[$titleText] ) ) {
3234 list( $ns, $dbk ) = $this->mTplRedirCache[$titleText];
3235 $title = Title::makeTitle( $ns, $dbk );
3236 $titleText = $title->getPrefixedDBkey();
3238 if ( isset( $this->mTplDomCache[$titleText] ) ) {
3239 return array( $this->mTplDomCache[$titleText], $title );
3242 # Cache miss, go to the database
3243 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3245 if ( $text === false ) {
3246 $this->mTplDomCache[$titleText] = false;
3247 return array( false, $title );
3250 $dom = $this->preprocessToDom( $text, self::PTD_FOR_INCLUSION );
3251 $this->mTplDomCache[ $titleText ] = $dom;
3253 if ( !$title->equals( $cacheTitle ) ) {
3254 $this->mTplRedirCache[$cacheTitle->getPrefixedDBkey()] =
3255 array( $title->getNamespace(), $cdb = $title->getDBkey() );
3258 return array( $dom, $title );
3262 * Fetch the unparsed text of a template and register a reference to it.
3264 function fetchTemplateAndTitle( $title ) {
3265 $templateCb = $this->mOptions->getTemplateCallback(); # Defaults to Parser::statelessFetchTemplate()
3266 $stuff = call_user_func( $templateCb, $title, $this );
3267 $text = $stuff['text'];
3268 $finalTitle = isset( $stuff['finalTitle'] ) ? $stuff['finalTitle'] : $title;
3269 if ( isset( $stuff['deps'] ) ) {
3270 foreach ( $stuff['deps'] as $dep ) {
3271 $this->mOutput->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3274 return array( $text, $finalTitle );
3277 function fetchTemplate( $title ) {
3278 $rv = $this->fetchTemplateAndTitle( $title );
3283 * Static function to get a template
3284 * Can be overridden via ParserOptions::setTemplateCallback().
3286 static function statelessFetchTemplate( $title, $parser=false ) {
3287 $text = $skip = false;
3288 $finalTitle = $title;
3291 # Loop to fetch the article, with up to 1 redirect
3292 for ( $i = 0; $i < 2 && is_object( $title ); $i++ ) {
3293 # Give extensions a chance to select the revision instead
3294 $id = false; # Assume current
3295 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3301 'page_id' => $title->getArticleID(),
3305 $rev = $id ? Revision::newFromId( $id ) : Revision::newFromTitle( $title );
3306 $rev_id = $rev ? $rev->getId() : 0;
3307 # If there is no current revision, there is no page
3308 if ( $id === false && !$rev ) {
3309 $linkCache = LinkCache::singleton();
3310 $linkCache->addBadLinkObj( $title );
3315 'page_id' => $title->getArticleID(),
3316 'rev_id' => $rev_id );
3319 $text = $rev->getText();
3320 } elseif ( $title->getNamespace() == NS_MEDIAWIKI ) {
3322 $message = $wgContLang->lcfirst( $title->getText() );
3323 $text = wfMsgForContentNoTrans( $message );
3324 if ( wfEmptyMsg( $message, $text ) ) {
3331 if ( $text === false ) {
3335 $finalTitle = $title;
3336 $title = Title::newFromRedirect( $text );
3340 'finalTitle' => $finalTitle,
3345 * Transclude an interwiki link.
3347 function interwikiTransclude( $title, $action ) {
3348 global $wgEnableScaryTranscluding;
3350 if ( !$wgEnableScaryTranscluding ) {
3351 return wfMsgForContent('scarytranscludedisabled');
3354 $url = $title->getFullUrl( "action=$action" );
3356 if ( strlen( $url ) > 255 ) {
3357 return wfMsgForContent( 'scarytranscludetoolong' );
3359 return $this->fetchScaryTemplateMaybeFromCache( $url );
3362 function fetchScaryTemplateMaybeFromCache( $url ) {
3363 global $wgTranscludeCacheExpiry;
3364 $dbr = wfGetDB( DB_SLAVE );
3365 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3366 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3367 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3369 return $obj->tc_contents;
3372 $text = Http::get( $url );
3374 return wfMsgForContent( 'scarytranscludefailed', $url );
3377 $dbw = wfGetDB( DB_MASTER );
3378 $dbw->replace( 'transcache', array('tc_url'), array(
3380 'tc_time' => $dbw->timestamp( time() ),
3381 'tc_contents' => $text)
3388 * Triple brace replacement -- used for template arguments
3391 function argSubstitution( $piece, $frame ) {
3392 wfProfileIn( __METHOD__ );
3395 $parts = $piece['parts'];
3396 $nameWithSpaces = $frame->expand( $piece['title'] );
3397 $argName = trim( $nameWithSpaces );
3399 $text = $frame->getArgument( $argName );
3400 if ( $text === false && $parts->getLength() > 0
3404 || ( $this->ot['wiki'] && $frame->isTemplate() )
3407 # No match in frame, use the supplied default
3408 $object = $parts->item( 0 )->getChildren();
3410 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3411 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3412 $this->limitationWarn( 'post-expand-template-argument' );
3415 if ( $text === false && $object === false ) {
3417 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3419 if ( $error !== false ) {
3422 if ( $object !== false ) {
3423 $ret = array( 'object' => $object );
3425 $ret = array( 'text' => $text );
3428 wfProfileOut( __METHOD__ );
3433 * Return the text to be used for a given extension tag.
3434 * This is the ghost of strip().
3436 * @param $params Associative array of parameters:
3437 * name PPNode for the tag name
3438 * attr PPNode for unparsed text where tag attributes are thought to be
3439 * attributes Optional associative array of parsed attributes
3440 * inner Contents of extension element
3441 * noClose Original text did not have a close tag
3442 * @param $frame PPFrame
3444 function extensionSubstitution( $params, $frame ) {
3445 $name = $frame->expand( $params['name'] );
3446 $attrText = !isset( $params['attr'] ) ? null : $frame->expand( $params['attr'] );
3447 $content = !isset( $params['inner'] ) ? null : $frame->expand( $params['inner'] );
3448 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++ ) . self::MARKER_SUFFIX;
3450 $isFunctionTag = isset( $this->mFunctionTagHooks[strtolower($name)] ) &&
3451 ( $this->ot['html'] || $this->ot['pre'] );
3452 if ( $isFunctionTag ) {
3453 $markerType = 'none';
3455 $markerType = 'general';
3457 if ( $this->ot['html'] || $isFunctionTag ) {
3458 $name = strtolower( $name );
3459 $attributes = Sanitizer::decodeTagAttributes( $attrText );
3460 if ( isset( $params['attributes'] ) ) {
3461 $attributes = $attributes + $params['attributes'];
3464 if ( isset( $this->mTagHooks[$name] ) ) {
3465 # Workaround for PHP bug 35229 and similar
3466 if ( !is_callable( $this->mTagHooks[$name] ) ) {
3467 throw new MWException( "Tag hook for $name is not callable\n" );
3469 $output = call_user_func_array( $this->mTagHooks[$name],
3470 array( $content, $attributes, $this, $frame ) );
3471 } elseif ( isset( $this->mFunctionTagHooks[$name] ) ) {
3472 list( $callback, $flags ) = $this->mFunctionTagHooks[$name];
3473 if ( !is_callable( $callback ) ) {
3474 throw new MWException( "Tag hook for $name is not callable\n" );
3477 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3479 $output = '<span class="error">Invalid tag extension name: ' .
3480 htmlspecialchars( $name ) . '</span>';
3483 if ( is_array( $output ) ) {
3484 # Extract flags to local scope (to override $markerType)
3486 $output = $flags[0];
3491 if ( is_null( $attrText ) ) {
3494 if ( isset( $params['attributes'] ) ) {
3495 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3496 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3497 htmlspecialchars( $attrValue ) . '"';
3500 if ( $content === null ) {
3501 $output = "<$name$attrText/>";
3503 $close = is_null( $params['close'] ) ? '' : $frame->expand( $params['close'] );
3504 $output = "<$name$attrText>$content$close";
3508 if ( $markerType === 'none' ) {
3510 } elseif ( $markerType === 'nowiki' ) {
3511 $this->mStripState->nowiki->setPair( $marker, $output );
3512 } elseif ( $markerType === 'general' ) {
3513 $this->mStripState->general->setPair( $marker, $output );
3515 throw new MWException( __METHOD__.': invalid marker type' );
3521 * Increment an include size counter
3523 * @param $type String: the type of expansion
3524 * @param $size Integer: the size of the text
3525 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3527 function incrementIncludeSize( $type, $size ) {
3528 if ( $this->mIncludeSizes[$type] + $size > $this->mOptions->getMaxIncludeSize( $type ) ) {
3531 $this->mIncludeSizes[$type] += $size;
3537 * Increment the expensive function count
3539 * @return Boolean: false if the limit has been exceeded
3541 function incrementExpensiveFunctionCount() {
3542 global $wgExpensiveParserFunctionLimit;
3543 $this->mExpensiveFunctionCount++;
3544 if ( $this->mExpensiveFunctionCount <= $wgExpensiveParserFunctionLimit ) {
3551 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3552 * Fills $this->mDoubleUnderscores, returns the modified text
3554 function doDoubleUnderscore( $text ) {
3555 wfProfileIn( __METHOD__ );
3557 # The position of __TOC__ needs to be recorded
3558 $mw = MagicWord::get( 'toc' );
3559 if ( $mw->match( $text ) ) {
3560 $this->mShowToc = true;
3561 $this->mForceTocPosition = true;
3563 # Set a placeholder. At the end we'll fill it in with the TOC.
3564 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3566 # Only keep the first one.
3567 $text = $mw->replace( '', $text );
3570 # Now match and remove the rest of them
3571 $mwa = MagicWord::getDoubleUnderscoreArray();
3572 $this->mDoubleUnderscores = $mwa->matchAndRemove( $text );
3574 if ( isset( $this->mDoubleUnderscores['nogallery'] ) ) {
3575 $this->mOutput->mNoGallery = true;
3577 if ( isset( $this->mDoubleUnderscores['notoc'] ) && !$this->mForceTocPosition ) {
3578 $this->mShowToc = false;
3580 if ( isset( $this->mDoubleUnderscores['hiddencat'] ) && $this->mTitle->getNamespace() == NS_CATEGORY ) {
3581 $this->addTrackingCategory( 'hidden-category-category' );
3583 # (bug 8068) Allow control over whether robots index a page.
3585 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3586 # is not desirable, the last one on the page should win.
3587 if ( isset( $this->mDoubleUnderscores['noindex'] ) && $this->mTitle->canUseNoindex() ) {
3588 $this->mOutput->setIndexPolicy( 'noindex' );
3589 $this->addTrackingCategory( 'noindex-category' );
3591 if ( isset( $this->mDoubleUnderscores['index'] ) && $this->mTitle->canUseNoindex() ) {
3592 $this->mOutput->setIndexPolicy( 'index' );
3593 $this->addTrackingCategory( 'index-category' );
3596 # Cache all double underscores in the database
3597 foreach ( $this->mDoubleUnderscores as $key => $val ) {
3598 $this->mOutput->setProperty( $key, '' );
3601 wfProfileOut( __METHOD__ );
3606 * Add a tracking category, getting the title from a system message,
3607 * or print a debug message if the title is invalid.
3609 * @param $msg String: message key
3610 * @return Boolean: whether the addition was successful
3612 protected function addTrackingCategory( $msg ) {
3613 $cat = wfMsgForContent( $msg );
3615 # Allow tracking categories to be disabled by setting them to "-"
3616 if ( $cat === '-' ) {
3620 $containerCategory = Title::makeTitleSafe( NS_CATEGORY, $cat );
3621 if ( $containerCategory ) {
3622 $this->mOutput->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3625 wfDebug( __METHOD__.": [[MediaWiki:$msg]] is not a valid title!\n" );
3631 * This function accomplishes several tasks:
3632 * 1) Auto-number headings if that option is enabled
3633 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3634 * 3) Add a Table of contents on the top for users who have enabled the option
3635 * 4) Auto-anchor headings
3637 * It loops through all headlines, collects the necessary data, then splits up the
3638 * string and re-inserts the newly formatted headlines.
3640 * @param $text String
3641 * @param $origText String: original, untouched wikitext
3642 * @param $isMain Boolean
3645 function formatHeadings( $text, $origText, $isMain=true ) {
3646 global $wgMaxTocLevel, $wgContLang, $wgHtml5, $wgExperimentalHtmlIds;
3648 $doNumberHeadings = $this->mOptions->getNumberHeadings();
3650 # Inhibit editsection links if requested in the page
3651 if ( isset( $this->mDoubleUnderscores['noeditsection'] ) ) {
3654 $showEditLink = $this->mOptions->getEditSection();
3657 # Get all headlines for numbering them and adding funky stuff like [edit]
3658 # links - this is for later, but we need the number of headlines right now
3660 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3662 # if there are fewer than 4 headlines in the article, do not show TOC
3663 # unless it's been explicitly enabled.
3664 $enoughToc = $this->mShowToc &&
3665 ( ( $numMatches >= 4 ) || $this->mForceTocPosition );
3667 # Allow user to stipulate that a page should have a "new section"
3668 # link added via __NEWSECTIONLINK__
3669 if ( isset( $this->mDoubleUnderscores['newsectionlink'] ) ) {
3670 $this->mOutput->setNewSection( true );
3673 # Allow user to remove the "new section"
3674 # link via __NONEWSECTIONLINK__
3675 if ( isset( $this->mDoubleUnderscores['nonewsectionlink'] ) ) {
3676 $this->mOutput->hideNewSection( true );
3679 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3680 # override above conditions and always show TOC above first header
3681 if ( isset( $this->mDoubleUnderscores['forcetoc'] ) ) {
3682 $this->mShowToc = true;
3686 # We need this to perform operations on the HTML
3687 $sk = $this->mOptions->getSkin( $this->mTitle );
3693 # Ugh .. the TOC should have neat indentation levels which can be
3694 # passed to the skin functions. These are determined here
3698 $sublevelCount = array();
3699 $levelCount = array();
3704 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self::MARKER_SUFFIX;
3705 $baseTitleText = $this->mTitle->getPrefixedDBkey();
3706 $oldType = $this->mOutputType;
3707 $this->setOutputType( self::OT_WIKI );
3708 $frame = $this->getPreprocessor()->newFrame();
3709 $root = $this->preprocessToDom( $origText );
3710 $node = $root->getFirstChild();
3715 foreach ( $matches[3] as $headline ) {
3716 $isTemplate = false;
3718 $sectionIndex = false;
3720 $markerMatches = array();
3721 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
3722 $serial = $markerMatches[1];
3723 list( $titleText, $sectionIndex ) = $this->mHeadings[$serial];
3724 $isTemplate = ( $titleText != $baseTitleText );
3725 $headline = preg_replace( "/^$markerRegex/", "", $headline );
3729 $prevlevel = $level;
3731 $level = $matches[1][$headlineCount];
3733 if ( $level > $prevlevel ) {
3734 # Increase TOC level
3736 $sublevelCount[$toclevel] = 0;
3737 if ( $toclevel<$wgMaxTocLevel ) {
3738 $prevtoclevel = $toclevel;
3739 $toc .= $sk->tocIndent();
3742 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
3743 # Decrease TOC level, find level to jump to
3745 for ( $i = $toclevel; $i > 0; $i-- ) {
3746 if ( $levelCount[$i] == $level ) {
3747 # Found last matching level
3750 } elseif ( $levelCount[$i] < $level ) {
3751 # Found first matching level below current level
3759 if ( $toclevel<$wgMaxTocLevel ) {
3760 if ( $prevtoclevel < $wgMaxTocLevel ) {
3761 # Unindent only if the previous toc level was shown :p
3762 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3763 $prevtoclevel = $toclevel;
3765 $toc .= $sk->tocLineEnd();
3769 # No change in level, end TOC line
3770 if ( $toclevel<$wgMaxTocLevel ) {
3771 $toc .= $sk->tocLineEnd();
3775 $levelCount[$toclevel] = $level;
3777 # count number of headlines for each level
3778 @$sublevelCount[$toclevel]++;
3780 for( $i = 1; $i <= $toclevel; $i++ ) {
3781 if ( !empty( $sublevelCount[$i] ) ) {
3785 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3790 # The safe header is a version of the header text safe to use for links
3791 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3792 $safeHeadline = $this->mStripState->unstripBoth( $headline );
3794 # Remove link placeholders by the link text.
3795 # <!--LINK number-->
3797 # link text with suffix
3798 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3800 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3801 $tocline = preg_replace(
3802 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3803 array( '', '<$1>' ),
3806 $tocline = trim( $tocline );
3808 # For the anchor, strip out HTML-y stuff period
3809 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3810 $safeHeadline = Sanitizer::normalizeSectionNameWhitespace( $safeHeadline );
3812 # Save headline for section edit hint before it's escaped
3813 $headlineHint = $safeHeadline;
3815 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
3816 # For reverse compatibility, provide an id that's
3817 # HTML4-compatible, like we used to.
3819 # It may be worth noting, academically, that it's possible for
3820 # the legacy anchor to conflict with a non-legacy headline
3821 # anchor on the page. In this case likely the "correct" thing
3822 # would be to either drop the legacy anchors or make sure
3823 # they're numbered first. However, this would require people
3824 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3825 # manually, so let's not bother worrying about it.
3826 $legacyHeadline = Sanitizer::escapeId( $safeHeadline,
3827 array( 'noninitial', 'legacy' ) );
3828 $safeHeadline = Sanitizer::escapeId( $safeHeadline );
3830 if ( $legacyHeadline == $safeHeadline ) {
3831 # No reason to have both (in fact, we can't)
3832 $legacyHeadline = false;
3835 $legacyHeadline = false;
3836 $safeHeadline = Sanitizer::escapeId( $safeHeadline,
3840 # HTML names must be case-insensitively unique (bug 10721).
3841 # This does not apply to Unicode characters per
3842 # http://dev.w3.org/html5/spec/infrastructure.html#case-sensitivity-and-string-comparison
3843 # FIXME: We may be changing them depending on the current locale.
3844 $arrayKey = strtolower( $safeHeadline );
3845 if ( $legacyHeadline === false ) {
3846 $legacyArrayKey = false;
3848 $legacyArrayKey = strtolower( $legacyHeadline );
3851 # count how many in assoc. array so we can track dupes in anchors
3852 if ( isset( $refers[$arrayKey] ) ) {
3853 $refers[$arrayKey]++;
3855 $refers[$arrayKey] = 1;
3857 if ( isset( $refers[$legacyArrayKey] ) ) {
3858 $refers[$legacyArrayKey]++;
3860 $refers[$legacyArrayKey] = 1;
3863 # Don't number the heading if it is the only one (looks silly)
3864 if ( $doNumberHeadings && count( $matches[3] ) > 1) {
3865 # the two are different if the line contains a link
3866 $headline = $numbering . ' ' . $headline;
3869 # Create the anchor for linking from the TOC to the section
3870 $anchor = $safeHeadline;
3871 $legacyAnchor = $legacyHeadline;
3872 if ( $refers[$arrayKey] > 1 ) {
3873 $anchor .= '_' . $refers[$arrayKey];
3875 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3876 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3878 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) || $toclevel < $wgMaxTocLevel ) ) {
3879 $toc .= $sk->tocLine( $anchor, $tocline,
3880 $numbering, $toclevel, ( $isTemplate ? false : $sectionIndex ) );
3883 # Add the section to the section tree
3884 # Find the DOM node for this header
3885 while ( $node && !$isTemplate ) {
3886 if ( $node->getName() === 'h' ) {
3887 $bits = $node->splitHeading();
3888 if ( $bits['i'] == $sectionIndex ) {
3892 $byteOffset += mb_strlen( $this->mStripState->unstripBoth(
3893 $frame->expand( $node, PPFrame::RECOVER_ORIG ) ) );
3894 $node = $node->getNextSibling();
3897 'toclevel' => $toclevel,
3900 'number' => $numbering,
3901 'index' => ( $isTemplate ? 'T-' : '' ) . $sectionIndex,
3902 'fromtitle' => $titleText,
3903 'byteoffset' => ( $isTemplate ? null : $byteOffset ),
3904 'anchor' => $anchor,
3907 # give headline the correct <h#> tag
3908 if ( $showEditLink && $sectionIndex !== false ) {
3909 if ( $isTemplate ) {
3910 # Put a T flag in the section identifier, to indicate to extractSections()
3911 # that sections inside <includeonly> should be counted.
3912 $editlink = $sk->doEditSectionLink( Title::newFromText( $titleText ), "T-$sectionIndex", null, $this->mOptions->getUserLang() );
3914 $editlink = $sk->doEditSectionLink( $this->mTitle, $sectionIndex, $headlineHint, $this->mOptions->getUserLang() );
3919 $head[$headlineCount] = $sk->makeHeadline( $level,
3920 $matches['attrib'][$headlineCount], $anchor, $headline,
3921 $editlink, $legacyAnchor );
3926 $this->setOutputType( $oldType );
3928 # Never ever show TOC if no headers
3929 if ( $numVisible < 1 ) {
3934 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3935 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3937 $toc = $sk->tocList( $toc, $this->mOptions->getUserLang() );
3938 $this->mOutput->setTOCHTML( $toc );
3942 $this->mOutput->setSections( $tocraw );
3945 # split up and insert constructed headlines
3947 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3950 foreach ( $blocks as $block ) {
3951 if ( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3952 # This is the [edit] link that appears for the top block of text when
3953 # section editing is enabled
3955 # Disabled because it broke block formatting
3956 # For example, a bullet point in the top line
3957 # $full .= $sk->editSectionLink(0);
3960 if ( $enoughToc && !$i && $isMain && !$this->mForceTocPosition ) {
3961 # Top anchor now in skin
3965 if ( !empty( $head[$i] ) ) {
3970 if ( $this->mForceTocPosition ) {
3971 return str_replace( '<!--MWTOC-->', $toc, $full );
3978 * Transform wiki markup when saving a page by doing \r\n -> \n
3979 * conversion, substitting signatures, {{subst:}} templates, etc.
3981 * @param $text String: the text to transform
3982 * @param $title Title: the Title object for the current article
3983 * @param $user User: the User object describing the current user
3984 * @param $options ParserOptions: parsing options
3985 * @param $clearState Boolean: whether to clear the parser state first
3986 * @return String: the altered wiki markup
3988 public function preSaveTransform( $text, Title $title, $user, $options, $clearState = true ) {
3989 $this->mOptions = $options;
3990 $this->setTitle( $title );
3991 $this->setOutputType( self::OT_WIKI );
3993 if ( $clearState ) {
3994 $this->clearState();
4000 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4001 $text = $this->pstPass2( $text, $user );
4002 $text = $this->mStripState->unstripBoth( $text );
4007 * Pre-save transform helper function
4010 function pstPass2( $text, $user ) {
4011 global $wgContLang, $wgLocaltimezone;
4013 # Note: This is the timestamp saved as hardcoded wikitext to
4014 # the database, we use $wgContLang here in order to give
4015 # everyone the same signature and use the default one rather
4016 # than the one selected in each user's preferences.
4017 # (see also bug 12815)
4018 $ts = $this->mOptions->getTimestamp();
4019 if ( isset( $wgLocaltimezone ) ) {
4020 $tz = $wgLocaltimezone;
4022 $tz = date_default_timezone_get();
4025 $unixts = wfTimestamp( TS_UNIX, $ts );
4026 $oldtz = date_default_timezone_get();
4027 date_default_timezone_set( $tz );
4028 $ts = date( 'YmdHis', $unixts );
4029 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4031 # Allow translation of timezones through wiki. date() can return
4032 # whatever crap the system uses, localised or not, so we cannot
4033 # ship premade translations.
4034 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4035 $value = wfMsgForContent( $key );
4036 if ( !wfEmptyMsg( $key, $value ) ) {
4040 date_default_timezone_set( $oldtz );
4042 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4044 # Variable replacement
4045 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4046 $text = $this->replaceVariables( $text );
4048 # This works almost by chance, as the replaceVariables are done before the getUserSig(),
4049 # which may corrupt this parser instance via its wfMsgExt( parsemag ) call-
4052 $sigText = $this->getUserSig( $user );
4053 $text = strtr( $text, array(
4055 '~~~~' => "$sigText $d",
4059 # Context links: [[|name]] and [[name (context)|]]
4060 global $wgLegalTitleChars;
4061 $tc = "[$wgLegalTitleChars]";
4062 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4064 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4065 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
4066 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4067 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4069 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4070 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4071 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4072 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4074 $t = $this->mTitle->getText();
4076 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4077 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4078 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4079 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4081 # if there's no context, don't bother duplicating the title
4082 $text = preg_replace( $p2, '[[\\1]]', $text );
4085 # Trim trailing whitespace
4086 $text = rtrim( $text );
4092 * Fetch the user's signature text, if any, and normalize to
4093 * validated, ready-to-insert wikitext.
4094 * If you have pre-fetched the nickname or the fancySig option, you can
4095 * specify them here to save a database query.
4098 * @param $nickname String: nickname to use or false to use user's default nickname
4099 * @param $fancySig Boolean: whether the nicknname is the complete signature
4100 * or null to use default value
4103 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4104 global $wgMaxSigChars;
4106 $username = $user->getName();
4108 # If not given, retrieve from the user object.
4109 if ( $nickname === false )
4110 $nickname = $user->getOption( 'nickname' );
4112 if ( is_null( $fancySig ) ) {
4113 $fancySig = $user->getBoolOption( 'fancysig' );
4116 $nickname = $nickname == null ? $username : $nickname;
4118 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4119 $nickname = $username;
4120 wfDebug( __METHOD__ . ": $username has overlong signature.\n" );
4121 } elseif ( $fancySig !== false ) {
4122 # Sig. might contain markup; validate this
4123 if ( $this->validateSig( $nickname ) !== false ) {
4124 # Validated; clean up (if needed) and return it
4125 return $this->cleanSig( $nickname, true );
4127 # Failed to validate; fall back to the default
4128 $nickname = $username;
4129 wfDebug( __METHOD__.": $username has bad XML tags in signature.\n" );
4133 # Make sure nickname doesnt get a sig in a sig
4134 $nickname = $this->cleanSigInSig( $nickname );
4136 # If we're still here, make it a link to the user page
4137 $userText = wfEscapeWikiText( $username );
4138 $nickText = wfEscapeWikiText( $nickname );
4139 if ( $user->isAnon() ) {
4140 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4142 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4147 * Check that the user's signature contains no bad XML
4149 * @param $text String
4150 * @return mixed An expanded string, or false if invalid.
4152 function validateSig( $text ) {
4153 return( Xml::isWellFormedXmlFragment( $text ) ? $text : false );
4157 * Clean up signature text
4159 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4160 * 2) Substitute all transclusions
4162 * @param $text String
4163 * @param $parsing Whether we're cleaning (preferences save) or parsing
4164 * @return String: signature text
4166 function cleanSig( $text, $parsing = false ) {
4169 $this->mOptions = new ParserOptions;
4170 $this->clearState();
4171 $this->setTitle( $wgTitle );
4172 $this->setOutputType = self::OT_PREPROCESS;
4175 # Option to disable this feature
4176 if ( !$this->mOptions->getCleanSignatures() ) {
4180 # FIXME: regex doesn't respect extension tags or nowiki
4181 # => Move this logic to braceSubstitution()
4182 $substWord = MagicWord::get( 'subst' );
4183 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4184 $substText = '{{' . $substWord->getSynonym( 0 );
4186 $text = preg_replace( $substRegex, $substText, $text );
4187 $text = $this->cleanSigInSig( $text );
4188 $dom = $this->preprocessToDom( $text );
4189 $frame = $this->getPreprocessor()->newFrame();
4190 $text = $frame->expand( $dom );
4193 $text = $this->mStripState->unstripBoth( $text );
4200 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4202 * @param $text String
4203 * @return String: signature text with /~{3,5}/ removed
4205 function cleanSigInSig( $text ) {
4206 $text = preg_replace( '/~{3,5}/', '', $text );
4211 * Set up some variables which are usually set up in parse()
4212 * so that an external function can call some class members with confidence
4214 public function startExternalParse( Title $title = null, ParserOptions $options, $outputType, $clearState = true ) {
4215 $this->setTitle( $title );
4216 $this->mOptions = $options;
4217 $this->setOutputType( $outputType );
4218 if ( $clearState ) {
4219 $this->clearState();
4224 * Wrapper for preprocess()
4226 * @param $text String: the text to preprocess
4227 * @param $options ParserOptions: options
4230 public function transformMsg( $text, $options ) {
4232 static $executing = false;
4234 # Guard against infinite recursion
4240 wfProfileIn( __METHOD__ );
4243 # It's not uncommon having a null $wgTitle in scripts. See r80898
4244 # Create a ghost title in such case
4245 $title = Title::newFromText( 'Dwimmerlaik' );
4247 $text = $this->preprocess( $text, $title, $options );
4250 wfProfileOut( __METHOD__ );
4255 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4256 * The callback should have the following form:
4257 * function myParserHook( $text, $params, $parser ) { ... }
4259 * Transform and return $text. Use $parser for any required context, e.g. use
4260 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4262 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4263 * @param $callback Mixed: the callback function (and object) to use for the tag
4264 * @return The old value of the mTagHooks array associated with the hook
4266 public function setHook( $tag, $callback ) {
4267 $tag = strtolower( $tag );
4268 $oldVal = isset( $this->mTagHooks[$tag] ) ? $this->mTagHooks[$tag] : null;
4269 $this->mTagHooks[$tag] = $callback;
4270 if ( !in_array( $tag, $this->mStripList ) ) {
4271 $this->mStripList[] = $tag;
4277 function setTransparentTagHook( $tag, $callback ) {
4278 $tag = strtolower( $tag );
4279 $oldVal = isset( $this->mTransparentTagHooks[$tag] ) ? $this->mTransparentTagHooks[$tag] : null;
4280 $this->mTransparentTagHooks[$tag] = $callback;
4286 * Remove all tag hooks
4288 function clearTagHooks() {
4289 $this->mTagHooks = array();
4290 $this->mStripList = $this->mDefaultStripList;
4294 * Create a function, e.g. {{sum:1|2|3}}
4295 * The callback function should have the form:
4296 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4298 * Or with SFH_OBJECT_ARGS:
4299 * function myParserFunction( $parser, $frame, $args ) { ... }
4301 * The callback may either return the text result of the function, or an array with the text
4302 * in element 0, and a number of flags in the other elements. The names of the flags are
4303 * specified in the keys. Valid flags are:
4304 * found The text returned is valid, stop processing the template. This
4306 * nowiki Wiki markup in the return value should be escaped
4307 * isHTML The returned text is HTML, armour it against wikitext transformation
4309 * @param $id String: The magic word ID
4310 * @param $callback Mixed: the callback function (and object) to use
4311 * @param $flags Integer: a combination of the following flags:
4312 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4314 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4315 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4316 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4317 * the arguments, and to control the way they are expanded.
4319 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4320 * arguments, for instance:
4321 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4323 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4324 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4325 * working if/when this is changed.
4327 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4330 * Please read the documentation in includes/parser/Preprocessor.php for more information
4331 * about the methods available in PPFrame and PPNode.
4333 * @return The old callback function for this name, if any
4335 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4338 $oldVal = isset( $this->mFunctionHooks[$id] ) ? $this->mFunctionHooks[$id][0] : null;
4339 $this->mFunctionHooks[$id] = array( $callback, $flags );
4341 # Add to function cache
4342 $mw = MagicWord::get( $id );
4344 throw new MWException( __METHOD__.'() expecting a magic word identifier.' );
4346 $synonyms = $mw->getSynonyms();
4347 $sensitive = intval( $mw->isCaseSensitive() );
4349 foreach ( $synonyms as $syn ) {
4351 if ( !$sensitive ) {
4352 $syn = $wgContLang->lc( $syn );
4355 if ( !( $flags & SFH_NO_HASH ) ) {
4358 # Remove trailing colon
4359 if ( substr( $syn, -1, 1 ) === ':' ) {
4360 $syn = substr( $syn, 0, -1 );
4362 $this->mFunctionSynonyms[$sensitive][$syn] = $id;
4368 * Get all registered function hook identifiers
4372 function getFunctionHooks() {
4373 return array_keys( $this->mFunctionHooks );
4377 * Create a tag function, e.g. <test>some stuff</test>.
4378 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4379 * Unlike parser functions, their content is not preprocessed.
4381 function setFunctionTagHook( $tag, $callback, $flags ) {
4382 $tag = strtolower( $tag );
4383 $old = isset( $this->mFunctionTagHooks[$tag] ) ?
4384 $this->mFunctionTagHooks[$tag] : null;
4385 $this->mFunctionTagHooks[$tag] = array( $callback, $flags );
4387 if ( !in_array( $tag, $this->mStripList ) ) {
4388 $this->mStripList[] = $tag;
4395 * FIXME: update documentation. makeLinkObj() is deprecated.
4396 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4397 * Placeholders created in Skin::makeLinkObj()
4398 * Returns an array of link CSS classes, indexed by PDBK.
4400 function replaceLinkHolders( &$text, $options = 0 ) {
4401 return $this->mLinkHolders->replace( $text );
4405 * Replace <!--LINK--> link placeholders with plain text of links
4406 * (not HTML-formatted).
4408 * @param $text String
4411 function replaceLinkHoldersText( $text ) {
4412 return $this->mLinkHolders->replaceText( $text );
4416 * Renders an image gallery from a text with one line per image.
4417 * text labels may be given by using |-style alternative text. E.g.
4418 * Image:one.jpg|The number "1"
4419 * Image:tree.jpg|A tree
4420 * given as text will return the HTML of a gallery with two images,
4421 * labeled 'The number "1"' and
4424 function renderImageGallery( $text, $params ) {
4425 $ig = new ImageGallery();
4426 $ig->setContextTitle( $this->mTitle );
4427 $ig->setShowBytes( false );
4428 $ig->setShowFilename( false );
4429 $ig->setParser( $this );
4430 $ig->setHideBadImages();
4431 $ig->setAttributes( Sanitizer::validateTagAttributes( $params, 'table' ) );
4432 $ig->useSkin( $this->mOptions->getSkin( $this->mTitle ) );
4433 $ig->mRevisionId = $this->mRevisionId;
4435 if ( isset( $params['showfilename'] ) ) {
4436 $ig->setShowFilename( true );
4438 $ig->setShowFilename( false );
4440 if ( isset( $params['caption'] ) ) {
4441 $caption = $params['caption'];
4442 $caption = htmlspecialchars( $caption );
4443 $caption = $this->replaceInternalLinks( $caption );
4444 $ig->setCaptionHtml( $caption );
4446 if ( isset( $params['perrow'] ) ) {
4447 $ig->setPerRow( $params['perrow'] );
4449 if ( isset( $params['widths'] ) ) {
4450 $ig->setWidths( $params['widths'] );
4452 if ( isset( $params['heights'] ) ) {
4453 $ig->setHeights( $params['heights'] );
4456 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4458 $lines = StringUtils::explode( "\n", $text );
4459 foreach ( $lines as $line ) {
4460 # match lines like these:
4461 # Image:someimage.jpg|This is some image
4463 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4465 if ( count( $matches ) == 0 ) {
4469 if ( strpos( $matches[0], '%' ) !== false ) {
4470 $matches[1] = urldecode( $matches[1] );
4472 $tp = Title::newFromText( $matches[1] );
4474 if ( is_null( $nt ) ) {
4475 # Bogus title. Ignore these so we don't bomb out later.
4478 if ( isset( $matches[3] ) ) {
4479 $label = $matches[3];
4484 $html = $this->recursiveTagParse( trim( $label ) );
4486 $ig->add( $nt, $html );
4488 # Only add real images (bug #5586)
4489 if ( $nt->getNamespace() == NS_FILE ) {
4490 $this->mOutput->addImage( $nt->getDBkey() );
4493 return $ig->toHTML();
4496 function getImageParams( $handler ) {
4498 $handlerClass = get_class( $handler );
4502 if ( !isset( $this->mImageParams[$handlerClass] ) ) {
4503 # Initialise static lists
4504 static $internalParamNames = array(
4505 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4506 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4507 'bottom', 'text-bottom' ),
4508 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4509 'upright', 'border', 'link', 'alt' ),
4511 static $internalParamMap;
4512 if ( !$internalParamMap ) {
4513 $internalParamMap = array();
4514 foreach ( $internalParamNames as $type => $names ) {
4515 foreach ( $names as $name ) {
4516 $magicName = str_replace( '-', '_', "img_$name" );
4517 $internalParamMap[$magicName] = array( $type, $name );
4522 # Add handler params
4523 $paramMap = $internalParamMap;
4525 $handlerParamMap = $handler->getParamMap();
4526 foreach ( $handlerParamMap as $magic => $paramName ) {
4527 $paramMap[$magic] = array( 'handler', $paramName );
4530 $this->mImageParams[$handlerClass] = $paramMap;
4531 $this->mImageParamsMagicArray[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4533 return array( $this->mImageParams[$handlerClass], $this->mImageParamsMagicArray[$handlerClass] );
4537 * Parse image options text and use it to make an image
4539 * @param $title Title
4540 * @param $options String
4541 * @param $holders LinkHolderArray
4543 function makeImage( $title, $options, $holders = false ) {
4544 # Check if the options text is of the form "options|alt text"
4546 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4547 # * left no resizing, just left align. label is used for alt= only
4548 # * right same, but right aligned
4549 # * none same, but not aligned
4550 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4551 # * center center the image
4552 # * frame Keep original image size, no magnify-button.
4553 # * framed Same as "frame"
4554 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4555 # * upright reduce width for upright images, rounded to full __0 px
4556 # * border draw a 1px border around the image
4557 # * alt Text for HTML alt attribute (defaults to empty)
4558 # * link Set the target of the image link. Can be external, interwiki, or local
4559 # vertical-align values (no % or length right now):
4569 $parts = StringUtils::explode( "|", $options );
4570 $sk = $this->mOptions->getSkin( $this->mTitle );
4572 # Give extensions a chance to select the file revision for us
4573 $skip = $time = $descQuery = false;
4574 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4577 return $sk->link( $title );
4581 $file = wfFindFile( $title, array( 'time' => $time ) );
4583 $handler = $file ? $file->getHandler() : false;
4585 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4587 # Process the input parameters
4589 $params = array( 'frame' => array(), 'handler' => array(),
4590 'horizAlign' => array(), 'vertAlign' => array() );
4591 foreach ( $parts as $part ) {
4592 $part = trim( $part );
4593 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4595 if ( isset( $paramMap[$magicName] ) ) {
4596 list( $type, $paramName ) = $paramMap[$magicName];
4598 # Special case; width and height come in one variable together
4599 if ( $type === 'handler' && $paramName === 'width' ) {
4601 # (bug 13500) In both cases (width/height and width only),
4602 # permit trailing "px" for backward compatibility.
4603 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4604 $width = intval( $m[1] );
4605 $height = intval( $m[2] );
4606 if ( $handler->validateParam( 'width', $width ) ) {
4607 $params[$type]['width'] = $width;
4610 if ( $handler->validateParam( 'height', $height ) ) {
4611 $params[$type]['height'] = $height;
4614 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4615 $width = intval( $value );
4616 if ( $handler->validateParam( 'width', $width ) ) {
4617 $params[$type]['width'] = $width;
4620 } # else no validation -- bug 13436
4622 if ( $type === 'handler' ) {
4623 # Validate handler parameter
4624 $validated = $handler->validateParam( $paramName, $value );
4626 # Validate internal parameters
4627 switch( $paramName ) {
4630 # @todo Fixme: possibly check validity here for
4631 # manualthumb? downstream behavior seems odd with
4632 # missing manual thumbs.
4634 $value = $this->stripAltText( $value, $holders );
4637 $chars = self::EXT_LINK_URL_CLASS;
4638 $prots = $this->mUrlProtocols;
4639 if ( $value === '' ) {
4640 $paramName = 'no-link';
4643 } elseif ( preg_match( "/^$prots/", $value ) ) {
4644 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4645 $paramName = 'link-url';
4646 $this->mOutput->addExternalLink( $value );
4647 if ( $this->mOptions->getExternalLinkTarget() ) {
4648 $params[$type]['link-target'] = $this->mOptions->getExternalLinkTarget();
4653 $linkTitle = Title::newFromText( $value );
4655 $paramName = 'link-title';
4656 $value = $linkTitle;
4657 $this->mOutput->addLink( $linkTitle );
4663 # Most other things appear to be empty or numeric...
4664 $validated = ( $value === false || is_numeric( trim( $value ) ) );
4669 $params[$type][$paramName] = $value;
4673 if ( !$validated ) {
4678 # Process alignment parameters
4679 if ( $params['horizAlign'] ) {
4680 $params['frame']['align'] = key( $params['horizAlign'] );
4682 if ( $params['vertAlign'] ) {
4683 $params['frame']['valign'] = key( $params['vertAlign'] );
4686 $params['frame']['caption'] = $caption;
4688 # Will the image be presented in a frame, with the caption below?
4689 $imageIsFramed = isset( $params['frame']['frame'] ) ||
4690 isset( $params['frame']['framed'] ) ||
4691 isset( $params['frame']['thumbnail'] ) ||
4692 isset( $params['frame']['manualthumb'] );
4694 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4695 # came to also set the caption, ordinary text after the image -- which
4696 # makes no sense, because that just repeats the text multiple times in
4697 # screen readers. It *also* came to set the title attribute.
4699 # Now that we have an alt attribute, we should not set the alt text to
4700 # equal the caption: that's worse than useless, it just repeats the
4701 # text. This is the framed/thumbnail case. If there's no caption, we
4702 # use the unnamed parameter for alt text as well, just for the time be-
4703 # ing, if the unnamed param is set and the alt param is not.
4705 # For the future, we need to figure out if we want to tweak this more,
4706 # e.g., introducing a title= parameter for the title; ignoring the un-
4707 # named parameter entirely for images without a caption; adding an ex-
4708 # plicit caption= parameter and preserving the old magic unnamed para-
4710 if ( $imageIsFramed ) { # Framed image
4711 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
4712 # No caption or alt text, add the filename as the alt text so
4713 # that screen readers at least get some description of the image
4714 $params['frame']['alt'] = $title->getText();
4716 # Do not set $params['frame']['title'] because tooltips don't make sense
4718 } else { # Inline image
4719 if ( !isset( $params['frame']['alt'] ) ) {
4720 # No alt text, use the "caption" for the alt text
4721 if ( $caption !== '') {
4722 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
4724 # No caption, fall back to using the filename for the
4726 $params['frame']['alt'] = $title->getText();
4729 # Use the "caption" for the tooltip text
4730 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4733 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4735 # Linker does the rest
4736 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery, $this->mOptions->getThumbSize() );
4738 # Give the handler a chance to modify the parser object
4740 $handler->parserTransformHook( $this, $file );
4746 protected function stripAltText( $caption, $holders ) {
4747 # Strip bad stuff out of the title (tooltip). We can't just use
4748 # replaceLinkHoldersText() here, because if this function is called
4749 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4751 $tooltip = $holders->replaceText( $caption );
4753 $tooltip = $this->replaceLinkHoldersText( $caption );
4756 # make sure there are no placeholders in thumbnail attributes
4757 # that are later expanded to html- so expand them now and
4759 $tooltip = $this->mStripState->unstripBoth( $tooltip );
4760 $tooltip = Sanitizer::stripAllTags( $tooltip );
4766 * Set a flag in the output object indicating that the content is dynamic and
4767 * shouldn't be cached.
4769 function disableCache() {
4770 wfDebug( "Parser output marked as uncacheable.\n" );
4771 $this->mOutput->setCacheTime( -1 ); // old style, for compatibility
4772 $this->mOutput->updateCacheExpiry( 0 ); // new style, for consistency
4776 * Callback from the Sanitizer for expanding items found in HTML attribute
4777 * values, so they can be safely tested and escaped.
4779 * @param $text String
4780 * @param $frame PPFrame
4784 function attributeStripCallback( &$text, $frame = false ) {
4785 $text = $this->replaceVariables( $text, $frame );
4786 $text = $this->mStripState->unstripBoth( $text );
4793 function getTags() {
4794 return array_merge( array_keys( $this->mTransparentTagHooks ), array_keys( $this->mTagHooks ) );
4798 * Break wikitext input into sections, and either pull or replace
4799 * some particular section's text.
4801 * External callers should use the getSection and replaceSection methods.
4803 * @param $text String: Page wikitext
4804 * @param $section String: a section identifier string of the form:
4805 * <flag1> - <flag2> - ... - <section number>
4807 * Currently the only recognised flag is "T", which means the target section number
4808 * was derived during a template inclusion parse, in other words this is a template
4809 * section edit link. If no flags are given, it was an ordinary section edit link.
4810 * This flag is required to avoid a section numbering mismatch when a section is
4811 * enclosed by <includeonly> (bug 6563).
4813 * The section number 0 pulls the text before the first heading; other numbers will
4814 * pull the given section along with its lower-level subsections. If the section is
4815 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4817 * @param $mode String: one of "get" or "replace"
4818 * @param $newText String: replacement text for section data.
4819 * @return String: for "get", the extracted section text.
4820 * for "replace", the whole page with the section replaced.
4822 private function extractSections( $text, $section, $mode, $newText='' ) {
4824 $this->mOptions = new ParserOptions;
4825 $this->clearState();
4826 $this->setTitle( $wgTitle ); # not generally used but removes an ugly failure mode
4827 $this->setOutputType( self::OT_PLAIN );
4829 $frame = $this->getPreprocessor()->newFrame();
4831 # Process section extraction flags
4833 $sectionParts = explode( '-', $section );
4834 $sectionIndex = array_pop( $sectionParts );
4835 foreach ( $sectionParts as $part ) {
4836 if ( $part === 'T' ) {
4837 $flags |= self::PTD_FOR_INCLUSION;
4840 # Preprocess the text
4841 $root = $this->preprocessToDom( $text, $flags );
4843 # <h> nodes indicate section breaks
4844 # They can only occur at the top level, so we can find them by iterating the root's children
4845 $node = $root->getFirstChild();
4847 # Find the target section
4848 if ( $sectionIndex == 0 ) {
4849 # Section zero doesn't nest, level=big
4850 $targetLevel = 1000;
4853 if ( $node->getName() === 'h' ) {
4854 $bits = $node->splitHeading();
4855 if ( $bits['i'] == $sectionIndex ) {
4856 $targetLevel = $bits['level'];
4860 if ( $mode === 'replace' ) {
4861 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
4863 $node = $node->getNextSibling();
4869 if ( $mode === 'get' ) {
4876 # Find the end of the section, including nested sections
4878 if ( $node->getName() === 'h' ) {
4879 $bits = $node->splitHeading();
4880 $curLevel = $bits['level'];
4881 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4885 if ( $mode === 'get' ) {
4886 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
4888 $node = $node->getNextSibling();
4891 # Write out the remainder (in replace mode only)
4892 if ( $mode === 'replace' ) {
4893 # Output the replacement text
4894 # Add two newlines on -- trailing whitespace in $newText is conventionally
4895 # stripped by the editor, so we need both newlines to restore the paragraph gap
4896 # Only add trailing whitespace if there is newText
4897 if ( $newText != "" ) {
4898 $outText .= $newText . "\n\n";
4902 $outText .= $frame->expand( $node, PPFrame::RECOVER_ORIG );
4903 $node = $node->getNextSibling();
4907 if ( is_string( $outText ) ) {
4908 # Re-insert stripped tags
4909 $outText = rtrim( $this->mStripState->unstripBoth( $outText ) );
4916 * This function returns the text of a section, specified by a number ($section).
4917 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4918 * the first section before any such heading (section 0).
4920 * If a section contains subsections, these are also returned.
4922 * @param $text String: text to look in
4923 * @param $section String: section identifier
4924 * @param $deftext String: default to return if section is not found
4925 * @return string text of the requested section
4927 public function getSection( $text, $section, $deftext='' ) {
4928 return $this->extractSections( $text, $section, "get", $deftext );
4932 * This function returns $oldtext after the content of the section
4933 * specified by $section has been replaced with $text.
4935 * @param $text String: former text of the article
4936 * @param $section Numeric: section identifier
4937 * @param $text String: replacing text
4938 * #return String: modified text
4940 public function replaceSection( $oldtext, $section, $text ) {
4941 return $this->extractSections( $oldtext, $section, "replace", $text );
4945 * Get the ID of the revision we are parsing
4947 * @return Mixed: integer or null
4949 function getRevisionId() {
4950 return $this->mRevisionId;
4954 * Get the timestamp associated with the current revision, adjusted for
4955 * the default server-local timestamp
4957 function getRevisionTimestamp() {
4958 if ( is_null( $this->mRevisionTimestamp ) ) {
4959 wfProfileIn( __METHOD__ );
4961 $dbr = wfGetDB( DB_SLAVE );
4962 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4963 array( 'rev_id' => $this->mRevisionId ), __METHOD__ );
4965 # Normalize timestamp to internal MW format for timezone processing.
4966 # This has the added side-effect of replacing a null value with
4967 # the current time, which gives us more sensible behavior for
4969 $timestamp = wfTimestamp( TS_MW, $timestamp );
4971 # The cryptic '' timezone parameter tells to use the site-default
4972 # timezone offset instead of the user settings.
4974 # Since this value will be saved into the parser cache, served
4975 # to other users, and potentially even used inside links and such,
4976 # it needs to be consistent for all visitors.
4977 $this->mRevisionTimestamp = $wgContLang->userAdjust( $timestamp, '' );
4979 wfProfileOut( __METHOD__ );
4981 return $this->mRevisionTimestamp;
4985 * Get the name of the user that edited the last revision
4987 * @return String: user name
4989 function getRevisionUser() {
4990 # if this template is subst: the revision id will be blank,
4991 # so just use the current user's name
4992 if ( $this->mRevisionId ) {
4993 $revision = Revision::newFromId( $this->mRevisionId );
4994 $revuser = $revision->getUserText();
4997 $revuser = $wgUser->getName();
5003 * Mutator for $mDefaultSort
5005 * @param $sort New value
5007 public function setDefaultSort( $sort ) {
5008 $this->mDefaultSort = $sort;
5009 $this->mOutput->setProperty( 'defaultsort', $sort );
5013 * Accessor for $mDefaultSort
5014 * Will use the empty string if none is set.
5016 * This value is treated as a prefix, so the
5017 * empty string is equivalent to sorting by
5022 public function getDefaultSort() {
5023 if ( $this->mDefaultSort !== false ) {
5024 return $this->mDefaultSort;
5031 * Accessor for $mDefaultSort
5032 * Unlike getDefaultSort(), will return false if none is set
5034 * @return string or false
5036 public function getCustomDefaultSort() {
5037 return $this->mDefaultSort;
5041 * Try to guess the section anchor name based on a wikitext fragment
5042 * presumably extracted from a heading, for example "Header" from
5045 public function guessSectionNameFromWikiText( $text ) {
5046 # Strip out wikitext links(they break the anchor)
5047 $text = $this->stripSectionName( $text );
5048 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
5049 return '#' . Sanitizer::escapeId( $text, 'noninitial' );
5053 * Same as guessSectionNameFromWikiText(), but produces legacy anchors
5054 * instead. For use in redirects, since IE6 interprets Redirect: headers
5055 * as something other than UTF-8 (apparently?), resulting in breakage.
5057 * @param $text String: The section name
5058 * @return string An anchor
5060 public function guessLegacySectionNameFromWikiText( $text ) {
5061 # Strip out wikitext links(they break the anchor)
5062 $text = $this->stripSectionName( $text );
5063 $text = Sanitizer::normalizeSectionNameWhitespace( $text );
5064 return '#' . Sanitizer::escapeId( $text, array( 'noninitial', 'legacy' ) );
5068 * Strips a text string of wikitext for use in a section anchor
5070 * Accepts a text string and then removes all wikitext from the
5071 * string and leaves only the resultant text (i.e. the result of
5072 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5073 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5074 * to create valid section anchors by mimicing the output of the
5075 * parser when headings are parsed.
5077 * @param $text String: text string to be stripped of wikitext
5078 * for use in a Section anchor
5079 * @return Filtered text string
5081 public function stripSectionName( $text ) {
5082 # Strip internal link markup
5083 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5084 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5086 # Strip external link markup (FIXME: Not Tolerant to blank link text
5087 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5088 # on how many empty links there are on the page - need to figure that out.
5089 $text = preg_replace( '/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5091 # Parse wikitext quotes (italics & bold)
5092 $text = $this->doQuotes( $text );
5095 $text = StringUtils::delimiterReplace( '<', '>', '', $text );
5100 * strip/replaceVariables/unstrip for preprocessor regression testing
5102 function testSrvus( $text, $title, ParserOptions $options, $outputType = self::OT_HTML ) {
5103 $this->mOptions = $options;
5104 $this->clearState();
5105 if ( !$title instanceof Title ) {
5106 $title = Title::newFromText( $title );
5108 $this->mTitle = $title;
5109 $this->setOutputType( $outputType );
5110 $text = $this->replaceVariables( $text );
5111 $text = $this->mStripState->unstripBoth( $text );
5112 $text = Sanitizer::removeHTMLtags( $text );
5116 function testPst( $text, $title, $options ) {
5118 if ( !$title instanceof Title ) {
5119 $title = Title::newFromText( $title );
5121 return $this->preSaveTransform( $text, $title, $wgUser, $options );
5124 function testPreprocess( $text, $title, $options ) {
5125 if ( !$title instanceof Title ) {
5126 $title = Title::newFromText( $title );
5128 return $this->testSrvus( $text, $title, $options, self::OT_PREPROCESS );
5131 function markerSkipCallback( $s, $callback ) {
5134 while ( $i < strlen( $s ) ) {
5135 $markerStart = strpos( $s, $this->mUniqPrefix, $i );
5136 if ( $markerStart === false ) {
5137 $out .= call_user_func( $callback, substr( $s, $i ) );
5140 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5141 $markerEnd = strpos( $s, self::MARKER_SUFFIX, $markerStart );
5142 if ( $markerEnd === false ) {
5143 $out .= substr( $s, $markerStart );
5146 $markerEnd += strlen( self::MARKER_SUFFIX );
5147 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5155 function serialiseHalfParsedText( $text ) {
5157 $data['text'] = $text;
5159 # First, find all strip markers, and store their
5161 $stripState = new StripState;
5163 while ( ( $start_pos = strpos( $text, $this->mUniqPrefix, $pos ) )
5164 && ( $end_pos = strpos( $text, self::MARKER_SUFFIX, $pos ) ) )
5166 $end_pos += strlen( self::MARKER_SUFFIX );
5167 $marker = substr( $text, $start_pos, $end_pos-$start_pos );
5169 if ( !empty( $this->mStripState->general->data[$marker] ) ) {
5170 $replaceArray = $stripState->general;
5171 $stripText = $this->mStripState->general->data[$marker];
5172 } elseif ( !empty( $this->mStripState->nowiki->data[$marker] ) ) {
5173 $replaceArray = $stripState->nowiki;
5174 $stripText = $this->mStripState->nowiki->data[$marker];
5176 throw new MWException( "Hanging strip marker: '$marker'." );
5179 $replaceArray->setPair( $marker, $stripText );
5182 $data['stripstate'] = $stripState;
5184 # Now, find all of our links, and store THEIR
5185 # data in an array! :)
5186 $links = array( 'internal' => array(), 'interwiki' => array() );
5190 while ( ( $start_pos = strpos( $text, '<!--LINK ', $pos ) ) ) {
5191 list( $ns, $trail ) = explode( ':', substr( $text, $start_pos + strlen( '<!--LINK ' ) ), 2 );
5194 if ( empty( $links['internal'][$ns] ) ) {
5195 $links['internal'][$ns] = array();
5198 $key = trim( substr( $trail, 0, strpos( $trail, '-->' ) ) );
5199 $links['internal'][$ns][] = $this->mLinkHolders->internals[$ns][$key];
5200 $pos = $start_pos + strlen( "<!--LINK $ns:$key-->" );
5206 while ( ( $start_pos = strpos( $text, '<!--IWLINK ', $pos ) ) ) {
5207 $data = substr( $text, $start_pos );
5208 $key = trim( substr( $data, 0, strpos( $data, '-->' ) ) );
5209 $links['interwiki'][] = $this->mLinkHolders->interwiki[$key];
5210 $pos = $start_pos + strlen( "<!--IWLINK $key-->" );
5213 $data['linkholder'] = $links;
5220 * @param $data Array
5221 * @param $intPrefix String unique identifying prefix
5224 function unserialiseHalfParsedText( $data, $intPrefix = null ) {
5225 if ( !$intPrefix ) {
5226 $intPrefix = self::getRandomString();
5229 # First, extract the strip state.
5230 $stripState = $data['stripstate'];
5231 $this->mStripState->general->merge( $stripState->general );
5232 $this->mStripState->nowiki->merge( $stripState->nowiki );
5234 # Now, extract the text, and renumber links
5235 $text = $data['text'];
5236 $links = $data['linkholder'];
5239 foreach ( $links['internal'] as $ns => $nsLinks ) {
5240 foreach ( $nsLinks as $key => $entry ) {
5241 $newKey = $intPrefix . '-' . $key;
5242 $this->mLinkHolders->internals[$ns][$newKey] = $entry;
5244 $text = str_replace( "<!--LINK $ns:$key-->", "<!--LINK $ns:$newKey-->", $text );
5249 foreach ( $links['interwiki'] as $key => $entry ) {
5250 $newKey = "$intPrefix-$key";
5251 $this->mLinkHolders->interwikis[$newKey] = $entry;
5253 $text = str_replace( "<!--IWLINK $key-->", "<!--IWLINK $newKey-->", $text );
5256 # Should be good to go.
5262 * @todo document, briefly.
5266 var $general, $nowiki;
5268 function __construct() {
5269 $this->general = new ReplacementArray;
5270 $this->nowiki = new ReplacementArray;
5273 function unstripGeneral( $text ) {
5274 wfProfileIn( __METHOD__ );
5277 $text = $this->general->replace( $text );
5278 } while ( $text !== $oldText );
5279 wfProfileOut( __METHOD__ );
5283 function unstripNoWiki( $text ) {
5284 wfProfileIn( __METHOD__ );
5287 $text = $this->nowiki->replace( $text );
5288 } while ( $text !== $oldText );
5289 wfProfileOut( __METHOD__ );
5293 function unstripBoth( $text ) {
5294 wfProfileIn( __METHOD__ );
5297 $text = $this->general->replace( $text );
5298 $text = $this->nowiki->replace( $text );
5299 } while ( $text !== $oldText );
5300 wfProfileOut( __METHOD__ );
5306 * @todo document, briefly.
5309 class OnlyIncludeReplacer {
5312 function replace( $matches ) {
5313 if ( substr( $matches[1], -1 ) === "\n" ) {
5314 $this->output .= substr( $matches[1], 0, -1 );
5316 $this->output .= $matches[1];