3 * @defgroup Parser Parser
7 * File for Parser and related classes
12 * PHP Parser - Processes wiki markup (which uses a more user-friendly
13 * syntax, such as "[[link]]" for making links), and provides a one-way
14 * transformation of that wiki markup it into XHTML output / markup
15 * (which in turn the browser understands, and can display).
18 * There are five main entry points into the Parser class:
20 * produces HTML output
22 * produces altered wiki markup.
24 * removes HTML comments and expands templates
26 * Cleans a signature before saving it to preferences
28 * Extracts sections from an article for section editing
31 * objects: $wgLang, $wgContLang
33 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
36 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
37 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
38 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
41 * * only within ParserOptions
49 * Update this version number when the ParserOutput format
50 * changes in an incompatible way, so the parser cache
51 * can automatically discard old data.
53 const VERSION
= '1.6.4';
55 # Flags for Parser::setFunctionHook
56 # Also available as global constants from Defines.php
57 const SFH_NO_HASH
= 1;
58 const SFH_OBJECT_ARGS
= 2;
60 # Constants needed for external link processing
61 # Everything except bracket, space, or control characters
62 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F]';
63 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
64 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
66 // State constants for the definition list colon extraction
67 const COLON_STATE_TEXT
= 0;
68 const COLON_STATE_TAG
= 1;
69 const COLON_STATE_TAGSTART
= 2;
70 const COLON_STATE_CLOSETAG
= 3;
71 const COLON_STATE_TAGSLASH
= 4;
72 const COLON_STATE_COMMENT
= 5;
73 const COLON_STATE_COMMENTDASH
= 6;
74 const COLON_STATE_COMMENTDASHDASH
= 7;
76 // Flags for preprocessToDom
77 const PTD_FOR_INCLUSION
= 1;
79 // Allowed values for $this->mOutputType
80 // Parameter to startExternalParse().
83 const OT_PREPROCESS
= 3;
86 // Marker Suffix needs to be accessible staticly.
87 const MARKER_SUFFIX
= "-QINU\x7f";
93 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables,
94 $mImageParams, $mImageParamsMagicArray, $mStripList, $mMarkerIndex, $mPreprocessor,
95 $mExtLinkBracketedRegex, $mUrlProtocols, $mDefaultStripList, $mVarCache, $mConf,
96 $mFunctionTagHooks, $mDoTitleConvert, $mDoContentConvert;
99 # Cleared with clearState():
100 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
101 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
102 var $mLinkHolders, $mLinkID;
103 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
104 var $mTplExpandCache; // empty-frame expansion cache
105 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
106 var $mExpensiveFunctionCount; // number of expensive parser function calls
109 # These are variables reset at least once per parse regardless of $clearState
110 var $mOptions, // ParserOptions object
111 $mTitle, // Title context, used for self-link rendering and similar things
112 $mOutputType, // Output type, one of the OT_xxx constants
113 $ot, // Shortcut alias, see setOutputType()
114 $mRevisionId, // ID to display in {{REVISIONID}} tags
115 $mRevisionTimestamp, // The timestamp of the specified revision ID
116 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
125 function __construct( $conf = array() ) {
126 $this->mConf
= $conf;
127 $this->mTagHooks
= array();
128 $this->mTransparentTagHooks
= array();
129 $this->mFunctionHooks
= array();
130 $this->mFunctionTagHooks
= array();
131 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
132 $this->mDefaultStripList
= $this->mStripList
= array( 'nowiki', 'gallery', 'a' );
133 $this->mUrlProtocols
= wfUrlProtocols();
134 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
135 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
136 $this->mVarCache
= array();
137 if ( isset( $conf['preprocessorClass'] ) ) {
138 $this->mPreprocessorClass
= $conf['preprocessorClass'];
139 } elseif ( extension_loaded( 'domxml' ) ) {
140 // PECL extension that conflicts with the core DOM extension (bug 13770)
141 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
142 $this->mPreprocessorClass
= 'Preprocessor_Hash';
143 } elseif ( extension_loaded( 'dom' ) ) {
144 $this->mPreprocessorClass
= 'Preprocessor_DOM';
146 $this->mPreprocessorClass
= 'Preprocessor_Hash';
148 $this->mMarkerIndex
= 0;
149 $this->mFirstCall
= true;
150 $this->mDoTitleConvert
= true;
151 $this->mDoContentConvert
= true;
155 * Reduce memory usage to reduce the impact of circular references
157 function __destruct() {
158 if ( isset( $this->mLinkHolders
) ) {
159 $this->mLinkHolders
->__destruct();
161 foreach ( $this as $name => $value ) {
162 unset( $this->$name );
167 * Do various kinds of initialisation on the first call of the parser
169 function firstCallInit() {
170 if ( !$this->mFirstCall
) {
173 $this->mFirstCall
= false;
175 wfProfileIn( __METHOD__
);
177 $this->setHook( 'pre', array( $this, 'renderPreTag' ) );
178 CoreParserFunctions
::register( $this );
179 $this->initialiseVariables();
181 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
182 wfProfileOut( __METHOD__
);
190 function clearState() {
191 wfProfileIn( __METHOD__
);
192 if ( $this->mFirstCall
) {
193 $this->firstCallInit();
195 $this->mOutput
= new ParserOutput
;
196 $this->mAutonumber
= 0;
197 $this->mLastSection
= '';
198 $this->mDTopen
= false;
199 $this->mIncludeCount
= array();
200 $this->mStripState
= new StripState
;
201 $this->mArgStack
= false;
202 $this->mInPre
= false;
203 $this->mLinkHolders
= new LinkHolderArray( $this );
205 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
206 $this->mVarCache
= array();
209 * Prefix for temporary replacement strings for the multipass parser.
210 * \x07 should never appear in input as it's disallowed in XML.
211 * Using it at the front also gives us a little extra robustness
212 * since it shouldn't match when butted up against identifier-like
215 * Must not consist of all title characters, or else it will change
216 * the behaviour of <nowiki> in a link.
218 #$this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
219 # Changed to \x7f to allow XML double-parsing -- TS
220 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
223 # Clear these on every parse, bug 4549
224 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
226 $this->mShowToc
= true;
227 $this->mForceTocPosition
= false;
228 $this->mIncludeSizes
= array(
232 $this->mPPNodeCount
= 0;
233 $this->mDefaultSort
= false;
234 $this->mHeadings
= array();
235 $this->mDoubleUnderscores
= array();
236 $this->mExpensiveFunctionCount
= 0;
239 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
240 $this->mPreprocessor
= null;
243 wfRunHooks( 'ParserClearState', array( &$this ) );
244 wfProfileOut( __METHOD__
);
247 function setOutputType( $ot ) {
248 $this->mOutputType
= $ot;
251 'html' => $ot == self
::OT_HTML
,
252 'wiki' => $ot == self
::OT_WIKI
,
253 'pre' => $ot == self
::OT_PREPROCESS
,
258 * Set the context title
260 function setTitle( $t ) {
261 // If don't have a Title object, then convert what we have to
262 // a string and then to Title. If you pass in an object, make
263 // sure it has a __toString() method or you'll get a
264 // "Catchable fatal error"
265 if ( $t && !($t instanceOf FakeTitle
)
266 && !($t instanceOf Title
) ) {
267 $t = Title
::newFromText( "$t" );
270 if ( !($t instanceOf Title
) ) {
271 $t = Title
::newFromText( 'NO TITLE' );
274 if ( strval( $t->getFragment() ) !== '' ) {
275 # Strip the fragment to avoid various odd effects
276 $this->mTitle
= clone $t;
277 $this->mTitle
->setFragment( '' );
284 * Accessor for mUniqPrefix.
288 function uniqPrefix() {
289 if( !isset( $this->mUniqPrefix
) ) {
290 // @todo Fixme: this is probably *horribly wrong*
291 // LanguageConverter seems to want $wgParser's uniqPrefix, however
292 // if this is called for a parser cache hit, the parser may not
293 // have ever been initialized in the first place.
294 // Not really sure what the heck is supposed to be going on here.
296 //throw new MWException( "Accessing uninitialized mUniqPrefix" );
298 return $this->mUniqPrefix
;
302 * Convert wikitext to HTML
303 * Do not call this function recursively.
305 * @param $text String: text we want to parse
306 * @param $title A title object
307 * @param $options ParserOptions
308 * @param $linestart boolean
309 * @param $clearState boolean
310 * @param $revid Int: number to pass in {{REVISIONID}}
311 * @return ParserOutput a ParserOutput
313 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
315 * First pass--just handle <nowiki> sections, pass the rest off
316 * to internalParse() which does all the real work.
319 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
320 $fname = __METHOD__
.'-' . wfGetCaller();
321 wfProfileIn( __METHOD__
);
322 wfProfileIn( $fname );
328 $this->mOptions
= $options;
329 $this->setTitle( $title ); // Page title has to be set for the pre-processor
331 $oldRevisionId = $this->mRevisionId
;
332 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
333 if( $revid !== null ) {
334 $this->mRevisionId
= $revid;
335 $this->mRevisionTimestamp
= null;
337 $this->setOutputType( self
::OT_HTML
);
338 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
340 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
341 $text = $this->internalParse( $text );
343 $text = $this->mStripState
->unstripGeneral( $text );
345 # Clean up special characters, only run once, next-to-last before doBlockLevels
347 # french spaces, last one Guillemet-left
348 # only if there is something before the space
349 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
350 # french spaces, Guillemet-right
351 '/(\\302\\253) /' => '\\1 ',
352 '/ (!\s*important)/' => ' \\1', #Beware of CSS magic word !important, bug #11874.
354 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
356 $text = $this->doBlockLevels( $text, $linestart );
358 $this->replaceLinkHolders( $text );
360 // The position of the convert() call should not be changed. it
361 // assumes that the links are all replaced and the only thing left
362 // is the <nowiki> mark.
363 if ( $this->mDoContentConvert
&& !$this->mTitle
->isConversionTable()) {
364 $text = $wgContLang->convert( $text );
367 // A title may have been set in a conversion rule.
368 // Note that if a user tries to set a title in a conversion
369 // rule but content conversion was not done, then the parser
370 // won't pick it up. This is probably expected behavior.
371 if ( $wgContLang->getConvRuleTitle() ) {
372 $this->setTitle( $wgContLang->getConvRuleTitle() );
373 } elseif ( $this->mDoTitleConvert
&& !$this->mTitle
->isConversionTable() ) {
374 $this->setTitle( $wgContLang->convert( $title ) );
377 $text = $this->mStripState
->unstripNoWiki( $text );
379 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
381 //!JF Move to its own function
383 $uniq_prefix = $this->mUniqPrefix
;
385 $elements = array_keys( $this->mTransparentTagHooks
);
386 $text = self
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
388 foreach( $matches as $marker => $data ) {
389 list( $element, $content, $params, $tag ) = $data;
390 $tagName = strtolower( $element );
391 if( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
392 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName],
393 array( $content, $params, $this ) );
397 $this->mStripState
->general
->setPair( $marker, $output );
399 $text = $this->mStripState
->unstripGeneral( $text );
401 $text = Sanitizer
::normalizeCharReferences( $text );
403 if ( ( $wgUseTidy && $this->mOptions
->mTidy
) ||
$wgAlwaysUseTidy ) {
404 $text = MWTidy
::tidy( $text );
406 # attempt to sanitize at least some nesting problems
407 # (bug #2702 and quite a few others)
409 # ''Something [http://www.cool.com cool''] -->
410 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
411 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
412 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
413 # fix up an anchor inside another anchor, only
414 # at least for a single single nested link (bug 3695)
415 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
416 '\\1\\2</a>\\3</a>\\1\\4</a>',
417 # fix div inside inline elements- doBlockLevels won't wrap a line which
418 # contains a div, so fix it up here; replace
419 # div with escaped text
420 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
421 '\\1\\3<div\\5>\\6</div>\\8\\9',
422 # remove empty italic or bold tag pairs, some
423 # introduced by rules above
424 '/<([bi])><\/\\1>/' => '',
427 $text = preg_replace(
428 array_keys( $tidyregs ),
429 array_values( $tidyregs ),
432 global $wgExpensiveParserFunctionLimit;
433 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
434 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
437 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
439 # Information on include size limits, for the benefit of users who try to skirt them
440 if ( $this->mOptions
->getEnableLimitReport() ) {
441 global $wgExpensiveParserFunctionLimit;
442 $max = $this->mOptions
->getMaxIncludeSize();
443 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
445 "NewPP limit report\n" .
446 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
447 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
448 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
450 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
451 $text .= "\n<!-- \n$limitReport-->\n";
453 $this->mOutput
->setText( $text );
454 $this->mRevisionId
= $oldRevisionId;
455 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
456 wfProfileOut( $fname );
457 wfProfileOut( __METHOD__
);
459 return $this->mOutput
;
463 * Recursive parser entry point that can be called from an extension tag
466 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
468 * @param $text String: text extension wants to have parsed
469 * @param PPFrame $frame: The frame to use for expanding any template variables
471 function recursiveTagParse( $text, $frame=false ) {
472 wfProfileIn( __METHOD__
);
473 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
474 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
475 $text = $this->internalParse( $text, false, $frame );
476 wfProfileOut( __METHOD__
);
481 * Expand templates and variables in the text, producing valid, static wikitext.
482 * Also removes comments.
484 function preprocess( $text, $title, $options, $revid = null ) {
485 wfProfileIn( __METHOD__
);
487 $this->setOutputType( self
::OT_PREPROCESS
);
488 $this->mOptions
= $options;
489 $this->setTitle( $title );
490 if( $revid !== null ) {
491 $this->mRevisionId
= $revid;
493 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
494 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
495 $text = $this->replaceVariables( $text );
496 $text = $this->mStripState
->unstripBoth( $text );
497 wfProfileOut( __METHOD__
);
502 * Get a random string
507 function getRandomString() {
508 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
511 function &getTitle() { return $this->mTitle
; }
512 function getOptions() { return $this->mOptions
; }
513 function getRevisionId() { return $this->mRevisionId
; }
514 function getOutput() { return $this->mOutput
; }
515 function nextLinkID() { return $this->mLinkID++
; }
517 function getFunctionLang() {
518 global $wgLang, $wgContLang;
520 $target = $this->mOptions
->getTargetLanguage();
521 if ( $target !== null ) {
524 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
529 * Get a preprocessor object
531 function getPreprocessor() {
532 if ( !isset( $this->mPreprocessor
) ) {
533 $class = $this->mPreprocessorClass
;
534 $this->mPreprocessor
= new $class( $this );
536 return $this->mPreprocessor
;
540 * Replaces all occurrences of HTML-style comments and the given tags
541 * in the text with a random marker and returns the next text. The output
542 * parameter $matches will be an associative array filled with data in
544 * 'UNIQ-xxxxx' => array(
547 * array( 'param' => 'x' ),
548 * '<element param="x">tag content</element>' ) )
550 * @param $elements list of element names. Comments are always extracted.
551 * @param $text Source text string.
552 * @param $uniq_prefix
557 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
562 $taglist = implode( '|', $elements );
563 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
565 while ( $text != '' ) {
566 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
568 if( count( $p ) < 5 ) {
571 if( count( $p ) > 5 ) {
585 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . self
::MARKER_SUFFIX
;
586 $stripped .= $marker;
588 if ( $close === '/>' ) {
589 // Empty element tag, <tag />
594 if( $element === '!--' ) {
597 $end = "/(<\\/$element\\s*>)/i";
599 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
601 if( count( $q ) < 3 ) {
602 # No end tag -- let it run out to the end of the text.
611 $matches[$marker] = array( $element,
613 Sanitizer
::decodeTagAttributes( $attributes ),
614 "<$element$attributes$close$content$tail" );
620 * Get a list of strippable XML-like elements
622 function getStripList() {
624 $elements = $this->mStripList
;
626 $elements[] = 'html';
628 if( $this->mOptions
->getUseTeX() ) {
629 $elements[] = 'math';
635 * @deprecated use replaceVariables
637 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
642 * Restores pre, math, and other extensions removed by strip()
644 * always call unstripNoWiki() after this one
646 * @deprecated use $this->mStripState->unstrip()
648 function unstrip( $text, $state ) {
649 return $state->unstripGeneral( $text );
653 * Always call this after unstrip() to preserve the order
656 * @deprecated use $this->mStripState->unstrip()
658 function unstripNoWiki( $text, $state ) {
659 return $state->unstripNoWiki( $text );
663 * @deprecated use $this->mStripState->unstripBoth()
665 function unstripForHTML( $text ) {
666 return $this->mStripState
->unstripBoth( $text );
670 * Add an item to the strip state
671 * Returns the unique tag which must be inserted into the stripped text
672 * The tag will be replaced with the original text in unstrip()
676 function insertStripItem( $text ) {
677 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
678 $this->mMarkerIndex++
;
679 $this->mStripState
->general
->setPair( $rnd, $text );
684 * Interface with html tidy
685 * @deprecated Use MWTidy::tidy()
687 public static function tidy( $text ) {
688 wfDeprecated( __METHOD__
);
689 return MWTidy
::tidy( $text );
693 * parse the wiki syntax used to render tables
697 function doTableStuff ( $text ) {
698 wfProfileIn( __METHOD__
);
700 $lines = StringUtils
::explode( "\n", $text );
702 $td_history = array (); // Is currently a td tag open?
703 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
704 $tr_history = array (); // Is currently a tr tag open?
705 $tr_attributes = array (); // history of tr attributes
706 $has_opened_tr = array(); // Did this table open a <tr> element?
707 $indent_level = 0; // indent level of the table
709 foreach ( $lines as $outLine ) {
710 $line = trim( $outLine );
712 if( $line == '' ) { // empty line, go to next line
713 $out .= $outLine."\n";
716 $first_character = $line[0];
719 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
720 // First check if we are starting a new table
721 $indent_level = strlen( $matches[1] );
723 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
724 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
726 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
727 array_push ( $td_history , false );
728 array_push ( $last_tag_history , '' );
729 array_push ( $tr_history , false );
730 array_push ( $tr_attributes , '' );
731 array_push ( $has_opened_tr , false );
732 } else if ( count ( $td_history ) == 0 ) {
733 // Don't do any of the following
734 $out .= $outLine."\n";
736 } else if ( substr ( $line , 0 , 2 ) === '|}' ) {
737 // We are ending a table
738 $line = '</table>' . substr ( $line , 2 );
739 $last_tag = array_pop ( $last_tag_history );
741 if ( !array_pop ( $has_opened_tr ) ) {
742 $line = "<tr><td></td></tr>{$line}";
745 if ( array_pop ( $tr_history ) ) {
746 $line = "</tr>{$line}";
749 if ( array_pop ( $td_history ) ) {
750 $line = "</{$last_tag}>{$line}";
752 array_pop ( $tr_attributes );
753 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
754 } else if ( substr ( $line , 0 , 2 ) === '|-' ) {
755 // Now we have a table row
756 $line = preg_replace( '#^\|-+#', '', $line );
758 // Whats after the tag is now only attributes
759 $attributes = $this->mStripState
->unstripBoth( $line );
760 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
761 array_pop ( $tr_attributes );
762 array_push ( $tr_attributes , $attributes );
765 $last_tag = array_pop ( $last_tag_history );
766 array_pop ( $has_opened_tr );
767 array_push ( $has_opened_tr , true );
769 if ( array_pop ( $tr_history ) ) {
773 if ( array_pop ( $td_history ) ) {
774 $line = "</{$last_tag}>{$line}";
778 array_push ( $tr_history , false );
779 array_push ( $td_history , false );
780 array_push ( $last_tag_history , '' );
782 else if ( $first_character === '|' ||
$first_character === '!' ||
substr ( $line , 0 , 2 ) === '|+' ) {
783 // This might be cell elements, td, th or captions
784 if ( substr ( $line , 0 , 2 ) === '|+' ) {
785 $first_character = '+';
786 $line = substr ( $line , 1 );
789 $line = substr ( $line , 1 );
791 if ( $first_character === '!' ) {
792 $line = str_replace ( '!!' , '||' , $line );
795 // Split up multiple cells on the same line.
796 // FIXME : This can result in improper nesting of tags processed
797 // by earlier parser steps, but should avoid splitting up eg
798 // attribute values containing literal "||".
799 $cells = StringUtils
::explodeMarkup( '||' , $line );
803 // Loop through each table cell
804 foreach ( $cells as $cell )
807 if ( $first_character !== '+' )
809 $tr_after = array_pop ( $tr_attributes );
810 if ( !array_pop ( $tr_history ) ) {
811 $previous = "<tr{$tr_after}>\n";
813 array_push ( $tr_history , true );
814 array_push ( $tr_attributes , '' );
815 array_pop ( $has_opened_tr );
816 array_push ( $has_opened_tr , true );
819 $last_tag = array_pop ( $last_tag_history );
821 if ( array_pop ( $td_history ) ) {
822 $previous = "</{$last_tag}>{$previous}";
825 if ( $first_character === '|' ) {
827 } else if ( $first_character === '!' ) {
829 } else if ( $first_character === '+' ) {
830 $last_tag = 'caption';
835 array_push ( $last_tag_history , $last_tag );
837 // A cell could contain both parameters and data
838 $cell_data = explode ( '|' , $cell , 2 );
840 // Bug 553: Note that a '|' inside an invalid link should not
841 // be mistaken as delimiting cell parameters
842 if ( strpos( $cell_data[0], '[[' ) !== false ) {
843 $cell = "{$previous}<{$last_tag}>{$cell}";
844 } else if ( count ( $cell_data ) == 1 )
845 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
847 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
848 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
849 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
853 array_push ( $td_history , true );
856 $out .= $outLine . "\n";
859 // Closing open td, tr && table
860 while ( count ( $td_history ) > 0 )
862 if ( array_pop ( $td_history ) ) {
865 if ( array_pop ( $tr_history ) ) {
868 if ( !array_pop ( $has_opened_tr ) ) {
869 $out .= "<tr><td></td></tr>\n" ;
872 $out .= "</table>\n";
875 // Remove trailing line-ending (b/c)
876 if ( substr( $out, -1 ) === "\n" ) {
877 $out = substr( $out, 0, -1 );
880 // special case: don't return empty table
881 if( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
885 wfProfileOut( __METHOD__
);
891 * Helper function for parse() that transforms wiki markup into
892 * HTML. Only called for $mOutputType == self::OT_HTML.
896 function internalParse( $text, $isMain = true, $frame=false ) {
897 wfProfileIn( __METHOD__
);
901 # Hook to suspend the parser in this state
902 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
903 wfProfileOut( __METHOD__
);
907 // if $frame is provided, then use $frame for replacing any variables
909 // use frame depth to infer how include/noinclude tags should be handled
910 // depth=0 means this is the top-level document; otherwise it's an included document
914 $flag = Parser
::PTD_FOR_INCLUSION
;
915 $dom = $this->preprocessToDom( $text, $flag );
916 $text = $frame->expand( $dom );
918 // if $frame is not provided, then use old-style replaceVariables
920 $text = $this->replaceVariables( $text );
923 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
924 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
926 // Tables need to come after variable replacement for things to work
927 // properly; putting them before other transformations should keep
928 // exciting things like link expansions from showing up in surprising
930 $text = $this->doTableStuff( $text );
932 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
934 $text = $this->doDoubleUnderscore( $text );
936 $text = $this->doHeadings( $text );
937 if( $this->mOptions
->getUseDynamicDates() ) {
938 $df = DateFormatter
::getInstance();
939 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
941 $text = $this->doAllQuotes( $text );
942 $text = $this->replaceInternalLinks( $text );
943 $text = $this->replaceExternalLinks( $text );
945 # replaceInternalLinks may sometimes leave behind
946 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
947 $text = str_replace($this->mUniqPrefix
.'NOPARSE', '', $text);
949 $text = $this->doMagicLinks( $text );
950 $text = $this->formatHeadings( $text, $origText, $isMain );
952 wfProfileOut( __METHOD__
);
957 * Replace special strings like "ISBN xxx" and "RFC xxx" with
958 * magic external links.
963 function doMagicLinks( $text ) {
964 wfProfileIn( __METHOD__
);
965 $prots = $this->mUrlProtocols
;
966 $urlChar = self
::EXT_LINK_URL_CLASS
;
967 $text = preg_replace_callback(
969 (<a.*?</a>) | # m[1]: Skip link text
970 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
971 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
972 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
973 ISBN\s+(\b # m[5]: ISBN, capture number
974 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
975 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
976 [0-9Xx] # check digit
978 )!x', array( &$this, 'magicLinkCallback' ), $text );
979 wfProfileOut( __METHOD__
);
983 function magicLinkCallback( $m ) {
984 if ( isset( $m[1] ) && $m[1] !== '' ) {
987 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
990 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
992 return $this->makeFreeExternalLink( $m[0] );
993 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
996 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
999 $CssClass = 'mw-magiclink-rfc';
1001 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1003 $urlmsg = 'pubmedurl';
1004 $CssClass = 'mw-magiclink-pmid';
1007 throw new MWException( __METHOD__
.': unrecognised match type "' .
1008 substr($m[0], 0, 20 ) . '"' );
1010 $url = wfMsg( $urlmsg, $id);
1011 $sk = $this->mOptions
->getSkin();
1012 $la = $sk->getExternalLinkAttributes( "external $CssClass" );
1013 return "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1014 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1017 $num = strtr( $isbn, array(
1022 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1024 $titleObj->escapeLocalUrl() .
1025 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1032 * Make a free external link, given a user-supplied URL
1036 function makeFreeExternalLink( $url ) {
1038 wfProfileIn( __METHOD__
);
1040 $sk = $this->mOptions
->getSkin();
1043 # The characters '<' and '>' (which were escaped by
1044 # removeHTMLtags()) should not be included in
1045 # URLs, per RFC 2396.
1047 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1048 $trail = substr($url, $m2[0][1]) . $trail;
1049 $url = substr($url, 0, $m2[0][1]);
1052 # Move trailing punctuation to $trail
1054 # If there is no left bracket, then consider right brackets fair game too
1055 if ( strpos( $url, '(' ) === false ) {
1059 $numSepChars = strspn( strrev( $url ), $sep );
1060 if ( $numSepChars ) {
1061 $trail = substr( $url, -$numSepChars ) . $trail;
1062 $url = substr( $url, 0, -$numSepChars );
1065 $url = Sanitizer
::cleanUrl( $url );
1067 # Is this an external image?
1068 $text = $this->maybeMakeExternalImage( $url );
1069 if ( $text === false ) {
1070 # Not an image, make a link
1071 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1072 $this->getExternalLinkAttribs( $url ) );
1073 # Register it in the output object...
1074 # Replace unnecessary URL escape codes with their equivalent characters
1075 $pasteurized = self
::replaceUnusualEscapes( $url );
1076 $this->mOutput
->addExternalLink( $pasteurized );
1078 wfProfileOut( __METHOD__
);
1079 return $text . $trail;
1084 * Parse headers and return html
1088 function doHeadings( $text ) {
1089 wfProfileIn( __METHOD__
);
1090 for ( $i = 6; $i >= 1; --$i ) {
1091 $h = str_repeat( '=', $i );
1092 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1093 "<h$i>\\1</h$i>", $text );
1095 wfProfileOut( __METHOD__
);
1100 * Replace single quotes with HTML markup
1102 * @return string the altered text
1104 function doAllQuotes( $text ) {
1105 wfProfileIn( __METHOD__
);
1107 $lines = StringUtils
::explode( "\n", $text );
1108 foreach ( $lines as $line ) {
1109 $outtext .= $this->doQuotes( $line ) . "\n";
1111 $outtext = substr($outtext, 0,-1);
1112 wfProfileOut( __METHOD__
);
1117 * Helper function for doAllQuotes()
1119 public function doQuotes( $text ) {
1120 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1121 if ( count( $arr ) == 1 )
1125 # First, do some preliminary work. This may shift some apostrophes from
1126 # being mark-up to being text. It also counts the number of occurrences
1127 # of bold and italics mark-ups.
1131 foreach ( $arr as $r )
1133 if ( ( $i %
2 ) == 1 )
1135 # If there are ever four apostrophes, assume the first is supposed to
1136 # be text, and the remaining three constitute mark-up for bold text.
1137 if ( strlen( $arr[$i] ) == 4 )
1142 # If there are more than 5 apostrophes in a row, assume they're all
1143 # text except for the last 5.
1144 else if ( strlen( $arr[$i] ) > 5 )
1146 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1149 # Count the number of occurrences of bold and italics mark-ups.
1150 # We are not counting sequences of five apostrophes.
1151 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1152 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1153 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1158 # If there is an odd number of both bold and italics, it is likely
1159 # that one of the bold ones was meant to be an apostrophe followed
1160 # by italics. Which one we cannot know for certain, but it is more
1161 # likely to be one that has a single-letter word before it.
1162 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1165 $firstsingleletterword = -1;
1166 $firstmultiletterword = -1;
1168 foreach ( $arr as $r )
1170 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1172 $x1 = substr ($arr[$i-1], -1);
1173 $x2 = substr ($arr[$i-1], -2, 1);
1175 if ($firstspace == -1) $firstspace = $i;
1176 } else if ($x2 === ' ') {
1177 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1179 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1185 # If there is a single-letter word, use it!
1186 if ($firstsingleletterword > -1)
1188 $arr [ $firstsingleletterword ] = "''";
1189 $arr [ $firstsingleletterword-1 ] .= "'";
1191 # If not, but there's a multi-letter word, use that one.
1192 else if ($firstmultiletterword > -1)
1194 $arr [ $firstmultiletterword ] = "''";
1195 $arr [ $firstmultiletterword-1 ] .= "'";
1197 # ... otherwise use the first one that has neither.
1198 # (notice that it is possible for all three to be -1 if, for example,
1199 # there is only one pentuple-apostrophe in the line)
1200 else if ($firstspace > -1)
1202 $arr [ $firstspace ] = "''";
1203 $arr [ $firstspace-1 ] .= "'";
1207 # Now let's actually convert our apostrophic mush to HTML!
1212 foreach ($arr as $r)
1216 if ($state === 'both')
1223 if (strlen ($r) == 2)
1226 { $output .= '</i>'; $state = ''; }
1227 else if ($state === 'bi')
1228 { $output .= '</i>'; $state = 'b'; }
1229 else if ($state === 'ib')
1230 { $output .= '</b></i><b>'; $state = 'b'; }
1231 else if ($state === 'both')
1232 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1233 else # $state can be 'b' or ''
1234 { $output .= '<i>'; $state .= 'i'; }
1236 else if (strlen ($r) == 3)
1239 { $output .= '</b>'; $state = ''; }
1240 else if ($state === 'bi')
1241 { $output .= '</i></b><i>'; $state = 'i'; }
1242 else if ($state === 'ib')
1243 { $output .= '</b>'; $state = 'i'; }
1244 else if ($state === 'both')
1245 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1246 else # $state can be 'i' or ''
1247 { $output .= '<b>'; $state .= 'b'; }
1249 else if (strlen ($r) == 5)
1252 { $output .= '</b><i>'; $state = 'i'; }
1253 else if ($state === 'i')
1254 { $output .= '</i><b>'; $state = 'b'; }
1255 else if ($state === 'bi')
1256 { $output .= '</i></b>'; $state = ''; }
1257 else if ($state === 'ib')
1258 { $output .= '</b></i>'; $state = ''; }
1259 else if ($state === 'both')
1260 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1261 else # ($state == '')
1262 { $buffer = ''; $state = 'both'; }
1267 # Now close all remaining tags. Notice that the order is important.
1268 if ($state === 'b' ||
$state === 'ib')
1270 if ($state === 'i' ||
$state === 'bi' ||
$state === 'ib')
1272 if ($state === 'bi')
1274 # There might be lonely ''''', so make sure we have a buffer
1275 if ($state === 'both' && $buffer)
1276 $output .= '<b><i>'.$buffer.'</i></b>';
1282 * Replace external links (REL)
1284 * Note: this is all very hackish and the order of execution matters a lot.
1285 * Make sure to run maintenance/parserTests.php if you change this code.
1289 function replaceExternalLinks( $text ) {
1291 wfProfileIn( __METHOD__
);
1293 $sk = $this->mOptions
->getSkin();
1295 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1296 $s = array_shift( $bits );
1299 while ( $i<count( $bits ) ) {
1301 $protocol = $bits[$i++
];
1302 $text = $bits[$i++
];
1303 $trail = $bits[$i++
];
1305 # The characters '<' and '>' (which were escaped by
1306 # removeHTMLtags()) should not be included in
1307 # URLs, per RFC 2396.
1309 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1310 $text = substr($url, $m2[0][1]) . ' ' . $text;
1311 $url = substr($url, 0, $m2[0][1]);
1314 # If the link text is an image URL, replace it with an <img> tag
1315 # This happened by accident in the original parser, but some people used it extensively
1316 $img = $this->maybeMakeExternalImage( $text );
1317 if ( $img !== false ) {
1323 # Set linktype for CSS - if URL==text, link is essentially free
1324 $linktype = ($text === $url) ?
'free' : 'text';
1326 # No link text, e.g. [http://domain.tld/some.link]
1327 if ( $text == '' ) {
1328 # Autonumber if allowed. See bug #5918
1329 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1330 $langObj = $this->getFunctionLang();
1331 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1332 $linktype = 'autonumber';
1334 # Otherwise just use the URL
1335 $text = htmlspecialchars( $url );
1339 # Have link text, e.g. [http://domain.tld/some.link text]s
1341 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1344 $text = $wgContLang->markNoConversion($text);
1346 $url = Sanitizer
::cleanUrl( $url );
1348 # Use the encoded URL
1349 # This means that users can paste URLs directly into the text
1350 # Funny characters like ö aren't valid in URLs anyway
1351 # This was changed in August 2004
1352 $s .= $sk->makeExternalLink( $url, $text, false, $linktype,
1353 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1355 # Register link in the output object.
1356 # Replace unnecessary URL escape codes with the referenced character
1357 # This prevents spammers from hiding links from the filters
1358 $pasteurized = self
::replaceUnusualEscapes( $url );
1359 $this->mOutput
->addExternalLink( $pasteurized );
1362 wfProfileOut( __METHOD__
);
1367 * Get an associative array of additional HTML attributes appropriate for a
1368 * particular external link. This currently may include rel => nofollow
1369 * (depending on configuration, namespace, and the URL's domain) and/or a
1370 * target attribute (depending on configuration).
1372 * @param string $url Optional URL, to extract the domain from for rel =>
1373 * nofollow if appropriate
1374 * @return array Associative array of HTML attributes
1376 function getExternalLinkAttribs( $url = false ) {
1378 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1379 $ns = $this->mTitle
->getNamespace();
1380 if( $wgNoFollowLinks && !in_array($ns, $wgNoFollowNsExceptions) ) {
1381 $attribs['rel'] = 'nofollow';
1383 global $wgNoFollowDomainExceptions;
1384 if ( $wgNoFollowDomainExceptions ) {
1385 $bits = wfParseUrl( $url );
1386 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1387 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1388 if( substr( $bits['host'], -strlen( $domain ) )
1390 unset( $attribs['rel'] );
1397 if ( $this->mOptions
->getExternalLinkTarget() ) {
1398 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1405 * Replace unusual URL escape codes with their equivalent characters
1409 * @todo This can merge genuinely required bits in the path or query string,
1410 * breaking legit URLs. A proper fix would treat the various parts of
1411 * the URL differently; as a workaround, just use the output for
1412 * statistical records, not for actual linking/output.
1414 static function replaceUnusualEscapes( $url ) {
1415 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1416 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1420 * Callback function used in replaceUnusualEscapes().
1421 * Replaces unusual URL escape codes with their equivalent character
1425 private static function replaceUnusualEscapesCallback( $matches ) {
1426 $char = urldecode( $matches[0] );
1427 $ord = ord( $char );
1428 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1429 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1430 // No, shouldn't be escaped
1433 // Yes, leave it escaped
1439 * make an image if it's allowed, either through the global
1440 * option, through the exception, or through the on-wiki whitelist
1443 function maybeMakeExternalImage( $url ) {
1444 $sk = $this->mOptions
->getSkin();
1445 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1446 $imagesexception = !empty($imagesfrom);
1448 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1449 if( $imagesexception && is_array( $imagesfrom ) ) {
1450 $imagematch = false;
1451 foreach( $imagesfrom as $match ) {
1452 if( strpos( $url, $match ) === 0 ) {
1457 } elseif( $imagesexception ) {
1458 $imagematch = (strpos( $url, $imagesfrom ) === 0);
1460 $imagematch = false;
1462 if ( $this->mOptions
->getAllowExternalImages()
1463 ||
( $imagesexception && $imagematch ) ) {
1464 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1466 $text = $sk->makeExternalImage( $url );
1469 if( !$text && $this->mOptions
->getEnableImageWhitelist()
1470 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1471 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1472 foreach( $whitelist as $entry ) {
1473 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1474 if( strpos( $entry, '#' ) === 0 ||
$entry === '' )
1476 if( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1477 # Image matches a whitelist entry
1478 $text = $sk->makeExternalImage( $url );
1487 * Process [[ ]] wikilinks
1488 * @return processed text
1492 function replaceInternalLinks( $s ) {
1493 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1498 * Process [[ ]] wikilinks (RIL)
1499 * @return LinkHolderArray
1503 function replaceInternalLinks2( &$s ) {
1506 wfProfileIn( __METHOD__
);
1508 wfProfileIn( __METHOD__
.'-setup' );
1509 static $tc = FALSE, $e1, $e1_img;
1510 # the % is needed to support urlencoded titles as well
1512 $tc = Title
::legalChars() . '#%';
1513 # Match a link having the form [[namespace:link|alternate]]trail
1514 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1515 # Match cases where there is no "]]", which might still be images
1516 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1519 $sk = $this->mOptions
->getSkin();
1520 $holders = new LinkHolderArray( $this );
1522 #split the entire text string on occurences of [[
1523 $a = StringUtils
::explode( '[[', ' ' . $s );
1524 #get the first element (all text up to first [[), and remove the space we added
1527 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1528 $s = substr( $s, 1 );
1530 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1532 if ( $useLinkPrefixExtension ) {
1533 # Match the end of a line for a word that's not followed by whitespace,
1534 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1535 $e2 = wfMsgForContent( 'linkprefix' );
1538 if( is_null( $this->mTitle
) ) {
1539 wfProfileOut( __METHOD__
.'-setup' );
1540 wfProfileOut( __METHOD__
);
1541 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1543 $nottalk = !$this->mTitle
->isTalkPage();
1545 if ( $useLinkPrefixExtension ) {
1547 if ( preg_match( $e2, $s, $m ) ) {
1548 $first_prefix = $m[2];
1550 $first_prefix = false;
1556 if($wgContLang->hasVariants()) {
1557 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1559 $selflink = array($this->mTitle
->getPrefixedText());
1561 $useSubpages = $this->areSubpagesAllowed();
1562 wfProfileOut( __METHOD__
.'-setup' );
1564 # Loop for each link
1565 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1566 # Check for excessive memory usage
1567 if ( $holders->isBig() ) {
1569 # Do the existence check, replace the link holders and clear the array
1570 $holders->replace( $s );
1574 if ( $useLinkPrefixExtension ) {
1575 wfProfileIn( __METHOD__
.'-prefixhandling' );
1576 if ( preg_match( $e2, $s, $m ) ) {
1584 $prefix = $first_prefix;
1585 $first_prefix = false;
1587 wfProfileOut( __METHOD__
.'-prefixhandling' );
1590 $might_be_img = false;
1592 wfProfileIn( __METHOD__
."-e1" );
1593 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1595 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1596 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1597 # the real problem is with the $e1 regex
1600 # Still some problems for cases where the ] is meant to be outside punctuation,
1601 # and no image is in sight. See bug 2095.
1604 substr( $m[3], 0, 1 ) === ']' &&
1605 strpos($text, '[') !== false
1608 $text .= ']'; # so that replaceExternalLinks($text) works later
1609 $m[3] = substr( $m[3], 1 );
1611 # fix up urlencoded title texts
1612 if( strpos( $m[1], '%' ) !== false ) {
1613 # Should anchors '#' also be rejected?
1614 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1617 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1618 $might_be_img = true;
1620 if ( strpos( $m[1], '%' ) !== false ) {
1621 $m[1] = urldecode($m[1]);
1624 } else { # Invalid form; output directly
1625 $s .= $prefix . '[[' . $line ;
1626 wfProfileOut( __METHOD__
."-e1" );
1629 wfProfileOut( __METHOD__
."-e1" );
1630 wfProfileIn( __METHOD__
."-misc" );
1632 # Don't allow internal links to pages containing
1633 # PROTO: where PROTO is a valid URL protocol; these
1634 # should be external links.
1635 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1636 $s .= $prefix . '[[' . $line ;
1637 wfProfileOut( __METHOD__
."-misc" );
1641 # Make subpage if necessary
1642 if ( $useSubpages ) {
1643 $link = $this->maybeDoSubpageLink( $m[1], $text );
1648 $noforce = (substr( $m[1], 0, 1 ) !== ':');
1650 # Strip off leading ':'
1651 $link = substr( $link, 1 );
1654 wfProfileOut( __METHOD__
."-misc" );
1655 wfProfileIn( __METHOD__
."-title" );
1656 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1657 if ( $nt === null ) {
1658 $s .= $prefix . '[[' . $line;
1659 wfProfileOut( __METHOD__
."-title" );
1663 $ns = $nt->getNamespace();
1664 $iw = $nt->getInterWiki();
1665 wfProfileOut( __METHOD__
."-title" );
1667 if ( $might_be_img ) { # if this is actually an invalid link
1668 wfProfileIn( __METHOD__
."-might_be_img" );
1669 if ( $ns == NS_FILE
&& $noforce ) { #but might be an image
1672 #look at the next 'line' to see if we can close it there
1674 $next_line = $a->current();
1675 if ( $next_line === false ||
$next_line === null ) {
1678 $m = explode( ']]', $next_line, 3 );
1679 if ( count( $m ) == 3 ) {
1680 # the first ]] closes the inner link, the second the image
1682 $text .= "[[{$m[0]}]]{$m[1]}";
1685 } elseif ( count( $m ) == 2 ) {
1686 #if there's exactly one ]] that's fine, we'll keep looking
1687 $text .= "[[{$m[0]}]]{$m[1]}";
1689 #if $next_line is invalid too, we need look no further
1690 $text .= '[[' . $next_line;
1695 # we couldn't find the end of this imageLink, so output it raw
1696 #but don't ignore what might be perfectly normal links in the text we've examined
1697 $holders->merge( $this->replaceInternalLinks2( $text ) );
1698 $s .= "{$prefix}[[$link|$text";
1699 # note: no $trail, because without an end, there *is* no trail
1700 wfProfileOut( __METHOD__
."-might_be_img" );
1703 } else { #it's not an image, so output it raw
1704 $s .= "{$prefix}[[$link|$text";
1705 # note: no $trail, because without an end, there *is* no trail
1706 wfProfileOut( __METHOD__
."-might_be_img" );
1709 wfProfileOut( __METHOD__
."-might_be_img" );
1712 $wasblank = ( $text == '' );
1713 if ( $wasblank ) $text = $link;
1715 # Link not escaped by : , create the various objects
1719 wfProfileIn( __METHOD__
."-interwiki" );
1720 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1721 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1722 $s = rtrim($s . $prefix);
1723 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1724 wfProfileOut( __METHOD__
."-interwiki" );
1727 wfProfileOut( __METHOD__
."-interwiki" );
1729 if ( $ns == NS_FILE
) {
1730 wfProfileIn( __METHOD__
."-image" );
1731 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1733 # if no parameters were passed, $text
1734 # becomes something like "File:Foo.png",
1735 # which we don't want to pass on to the
1739 # recursively parse links inside the image caption
1740 # actually, this will parse them in any other parameters, too,
1741 # but it might be hard to fix that, and it doesn't matter ATM
1742 $text = $this->replaceExternalLinks($text);
1743 $holders->merge( $this->replaceInternalLinks2( $text ) );
1745 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1746 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1748 $this->mOutput
->addImage( $nt->getDBkey() );
1749 wfProfileOut( __METHOD__
."-image" );
1754 if ( $ns == NS_CATEGORY
) {
1755 wfProfileIn( __METHOD__
."-category" );
1756 $s = rtrim($s . "\n"); # bug 87
1759 $sortkey = $this->getDefaultSort();
1763 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1764 $sortkey = str_replace( "\n", '', $sortkey );
1765 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1766 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1769 * Strip the whitespace Category links produce, see bug 87
1770 * @todo We might want to use trim($tmp, "\n") here.
1772 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1774 wfProfileOut( __METHOD__
."-category" );
1779 # Self-link checking
1780 if( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1781 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1782 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1787 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1788 # FIXME: Should do batch file existence checks, see comment below
1789 if( $ns == NS_MEDIA
) {
1790 wfProfileIn( __METHOD__
."-media" );
1791 # Give extensions a chance to select the file revision for us
1792 $skip = $time = false;
1793 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1795 $link = $sk->link( $nt );
1797 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1799 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1800 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1801 $this->mOutput
->addImage( $nt->getDBkey() );
1802 wfProfileOut( __METHOD__
."-media" );
1806 wfProfileIn( __METHOD__
."-always_known" );
1807 # Some titles, such as valid special pages or files in foreign repos, should
1808 # be shown as bluelinks even though they're not included in the page table
1810 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1811 # batch file existence checks for NS_FILE and NS_MEDIA
1812 if( $iw == '' && $nt->isAlwaysKnown() ) {
1813 $this->mOutput
->addLink( $nt );
1814 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1816 # Links will be added to the output link list after checking
1817 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1819 wfProfileOut( __METHOD__
."-always_known" );
1821 wfProfileOut( __METHOD__
);
1826 * Make a link placeholder. The text returned can be later resolved to a real link with
1827 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1828 * parsing of interwiki links, and secondly to allow all existence checks and
1829 * article length checks (for stub links) to be bundled into a single query.
1833 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1834 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1838 * Render a forced-blue link inline; protect against double expansion of
1839 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1840 * Since this little disaster has to split off the trail text to avoid
1841 * breaking URLs in the following text without breaking trails on the
1842 * wiki links, it's been made into a horrible function.
1845 * @param string $text
1846 * @param string $query
1847 * @param string $trail
1848 * @param string $prefix
1849 * @return string HTML-wikitext mix oh yuck
1851 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1852 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1853 $sk = $this->mOptions
->getSkin();
1854 // FIXME: use link() instead of deprecated makeKnownLinkObj()
1855 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1856 return $this->armorLinks( $link ) . $trail;
1860 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1861 * going to go through further parsing steps before inline URL expansion.
1863 * Not needed quite as much as it used to be since free links are a bit
1864 * more sensible these days. But bracketed links are still an issue.
1866 * @param string more-or-less HTML
1867 * @return string less-or-more HTML with NOPARSE bits
1869 function armorLinks( $text ) {
1870 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1871 "{$this->mUniqPrefix}NOPARSE$1", $text );
1875 * Return true if subpage links should be expanded on this page.
1878 function areSubpagesAllowed() {
1879 # Some namespaces don't allow subpages
1880 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
1884 * Handle link to subpage if necessary
1885 * @param string $target the source of the link
1886 * @param string &$text the link text, modified as necessary
1887 * @return string the full name of the link
1890 function maybeDoSubpageLink($target, &$text) {
1891 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
1895 * Used by doBlockLevels()
1898 /* private */ function closeParagraph() {
1900 if ( $this->mLastSection
!= '' ) {
1901 $result = '</' . $this->mLastSection
. ">\n";
1903 $this->mInPre
= false;
1904 $this->mLastSection
= '';
1907 # getCommon() returns the length of the longest common substring
1908 # of both arguments, starting at the beginning of both.
1910 /* private */ function getCommon( $st1, $st2 ) {
1911 $fl = strlen( $st1 );
1912 $shorter = strlen( $st2 );
1913 if ( $fl < $shorter ) { $shorter = $fl; }
1915 for ( $i = 0; $i < $shorter; ++
$i ) {
1916 if ( $st1{$i} != $st2{$i} ) { break; }
1920 # These next three functions open, continue, and close the list
1921 # element appropriate to the prefix character passed into them.
1923 /* private */ function openList( $char ) {
1924 $result = $this->closeParagraph();
1926 if ( '*' === $char ) { $result .= '<ul><li>'; }
1927 elseif ( '#' === $char ) { $result .= '<ol><li>'; }
1928 elseif ( ':' === $char ) { $result .= '<dl><dd>'; }
1929 elseif ( ';' === $char ) {
1930 $result .= '<dl><dt>';
1931 $this->mDTopen
= true;
1933 else { $result = '<!-- ERR 1 -->'; }
1938 /* private */ function nextItem( $char ) {
1939 if ( '*' === $char ||
'#' === $char ) { return '</li><li>'; }
1940 elseif ( ':' === $char ||
';' === $char ) {
1942 if ( $this->mDTopen
) { $close = '</dt>'; }
1943 if ( ';' === $char ) {
1944 $this->mDTopen
= true;
1945 return $close . '<dt>';
1947 $this->mDTopen
= false;
1948 return $close . '<dd>';
1951 return '<!-- ERR 2 -->';
1954 /* private */ function closeList( $char ) {
1955 if ( '*' === $char ) { $text = '</li></ul>'; }
1956 elseif ( '#' === $char ) { $text = '</li></ol>'; }
1957 elseif ( ':' === $char ) {
1958 if ( $this->mDTopen
) {
1959 $this->mDTopen
= false;
1960 $text = '</dt></dl>';
1962 $text = '</dd></dl>';
1965 else { return '<!-- ERR 3 -->'; }
1971 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
1973 * @param $linestart bool whether or not this is at the start of a line.
1975 * @return string the lists rendered as HTML
1977 function doBlockLevels( $text, $linestart ) {
1978 wfProfileIn( __METHOD__
);
1980 # Parsing through the text line by line. The main thing
1981 # happening here is handling of block-level elements p, pre,
1982 # and making lists from lines starting with * # : etc.
1984 $textLines = StringUtils
::explode( "\n", $text );
1986 $lastPrefix = $output = '';
1987 $this->mDTopen
= $inBlockElem = false;
1989 $paragraphStack = false;
1991 foreach ( $textLines as $oLine ) {
1993 if ( !$linestart ) {
2003 $lastPrefixLength = strlen( $lastPrefix );
2004 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2005 $preOpenMatch = preg_match('/<pre/i', $oLine );
2006 // If not in a <pre> element, scan for and figure out what prefixes are there.
2007 if ( !$this->mInPre
) {
2008 # Multiple prefixes may abut each other for nested lists.
2009 $prefixLength = strspn( $oLine, '*#:;' );
2010 $prefix = substr( $oLine, 0, $prefixLength );
2013 // ; and : are both from definition-lists, so they're equivalent
2014 // for the purposes of determining whether or not we need to open/close
2016 $prefix2 = str_replace( ';', ':', $prefix );
2017 $t = substr( $oLine, $prefixLength );
2018 $this->mInPre
= (bool)$preOpenMatch;
2020 # Don't interpret any other prefixes in preformatted text
2022 $prefix = $prefix2 = '';
2027 if( $prefixLength && $lastPrefix === $prefix2 ) {
2028 # Same as the last item, so no need to deal with nesting or opening stuff
2029 $output .= $this->nextItem( substr( $prefix, -1 ) );
2030 $paragraphStack = false;
2032 if ( substr( $prefix, -1 ) === ';') {
2033 # The one nasty exception: definition lists work like this:
2034 # ; title : definition text
2035 # So we check for : in the remainder text to split up the
2036 # title and definition, without b0rking links.
2038 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2040 $output .= $term . $this->nextItem( ':' );
2043 } elseif( $prefixLength ||
$lastPrefixLength ) {
2044 // We need to open or close prefixes, or both.
2046 # Either open or close a level...
2047 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2048 $paragraphStack = false;
2050 // Close all the prefixes which aren't shared.
2051 while( $commonPrefixLength < $lastPrefixLength ) {
2052 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2053 --$lastPrefixLength;
2056 // Continue the current prefix if appropriate.
2057 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2058 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2061 // Open prefixes where appropriate.
2062 while ( $prefixLength > $commonPrefixLength ) {
2063 $char = substr( $prefix, $commonPrefixLength, 1 );
2064 $output .= $this->openList( $char );
2066 if ( ';' === $char ) {
2067 # FIXME: This is dupe of code above
2068 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2070 $output .= $term . $this->nextItem( ':' );
2073 ++
$commonPrefixLength;
2075 $lastPrefix = $prefix2;
2078 // If we have no prefixes, go to paragraph mode.
2079 if( 0 == $prefixLength ) {
2080 wfProfileIn( __METHOD__
."-paragraph" );
2081 # No prefix (not in list)--go to paragraph mode
2082 // XXX: use a stack for nestable elements like span, table and div
2083 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2084 $closematch = preg_match(
2085 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2086 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2087 if ( $openmatch or $closematch ) {
2088 $paragraphStack = false;
2089 #Â TODO bug 5718: paragraph closed
2090 $output .= $this->closeParagraph();
2091 if ( $preOpenMatch and !$preCloseMatch ) {
2092 $this->mInPre
= true;
2094 if ( $closematch ) {
2095 $inBlockElem = false;
2097 $inBlockElem = true;
2099 } else if ( !$inBlockElem && !$this->mInPre
) {
2100 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' or trim($t) != '' ) ) {
2102 if ($this->mLastSection
!== 'pre') {
2103 $paragraphStack = false;
2104 $output .= $this->closeParagraph().'<pre>';
2105 $this->mLastSection
= 'pre';
2107 $t = substr( $t, 1 );
2110 if ( trim($t) == '' ) {
2111 if ( $paragraphStack ) {
2112 $output .= $paragraphStack.'<br />';
2113 $paragraphStack = false;
2114 $this->mLastSection
= 'p';
2116 if ($this->mLastSection
!== 'p' ) {
2117 $output .= $this->closeParagraph();
2118 $this->mLastSection
= '';
2119 $paragraphStack = '<p>';
2121 $paragraphStack = '</p><p>';
2125 if ( $paragraphStack ) {
2126 $output .= $paragraphStack;
2127 $paragraphStack = false;
2128 $this->mLastSection
= 'p';
2129 } else if ($this->mLastSection
!== 'p') {
2130 $output .= $this->closeParagraph().'<p>';
2131 $this->mLastSection
= 'p';
2136 wfProfileOut( __METHOD__
."-paragraph" );
2138 // somewhere above we forget to get out of pre block (bug 785)
2139 if($preCloseMatch && $this->mInPre
) {
2140 $this->mInPre
= false;
2142 if ($paragraphStack === false) {
2146 while ( $prefixLength ) {
2147 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2150 if ( $this->mLastSection
!= '' ) {
2151 $output .= '</' . $this->mLastSection
. '>';
2152 $this->mLastSection
= '';
2155 wfProfileOut( __METHOD__
);
2160 * Split up a string on ':', ignoring any occurences inside tags
2161 * to prevent illegal overlapping.
2162 * @param string $str the string to split
2163 * @param string &$before set to everything before the ':'
2164 * @param string &$after set to everything after the ':'
2165 * return string the position of the ':', or false if none found
2167 function findColonNoLinks($str, &$before, &$after) {
2168 wfProfileIn( __METHOD__
);
2170 $pos = strpos( $str, ':' );
2171 if( $pos === false ) {
2173 wfProfileOut( __METHOD__
);
2177 $lt = strpos( $str, '<' );
2178 if( $lt === false ||
$lt > $pos ) {
2179 // Easy; no tag nesting to worry about
2180 $before = substr( $str, 0, $pos );
2181 $after = substr( $str, $pos+
1 );
2182 wfProfileOut( __METHOD__
);
2186 // Ugly state machine to walk through avoiding tags.
2187 $state = self
::COLON_STATE_TEXT
;
2189 $len = strlen( $str );
2190 for( $i = 0; $i < $len; $i++
) {
2194 // (Using the number is a performance hack for common cases)
2195 case 0: // self::COLON_STATE_TEXT:
2198 // Could be either a <start> tag or an </end> tag
2199 $state = self
::COLON_STATE_TAGSTART
;
2204 $before = substr( $str, 0, $i );
2205 $after = substr( $str, $i +
1 );
2206 wfProfileOut( __METHOD__
);
2209 // Embedded in a tag; don't break it.
2212 // Skip ahead looking for something interesting
2213 $colon = strpos( $str, ':', $i );
2214 if( $colon === false ) {
2215 // Nothing else interesting
2216 wfProfileOut( __METHOD__
);
2219 $lt = strpos( $str, '<', $i );
2220 if( $stack === 0 ) {
2221 if( $lt === false ||
$colon < $lt ) {
2223 $before = substr( $str, 0, $colon );
2224 $after = substr( $str, $colon +
1 );
2225 wfProfileOut( __METHOD__
);
2229 if( $lt === false ) {
2230 // Nothing else interesting to find; abort!
2231 // We're nested, but there's no close tags left. Abort!
2234 // Skip ahead to next tag start
2236 $state = self
::COLON_STATE_TAGSTART
;
2239 case 1: // self::COLON_STATE_TAG:
2244 $state = self
::COLON_STATE_TEXT
;
2247 // Slash may be followed by >?
2248 $state = self
::COLON_STATE_TAGSLASH
;
2254 case 2: // self::COLON_STATE_TAGSTART:
2257 $state = self
::COLON_STATE_CLOSETAG
;
2260 $state = self
::COLON_STATE_COMMENT
;
2263 // Illegal early close? This shouldn't happen D:
2264 $state = self
::COLON_STATE_TEXT
;
2267 $state = self
::COLON_STATE_TAG
;
2270 case 3: // self::COLON_STATE_CLOSETAG:
2275 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2276 wfProfileOut( __METHOD__
);
2279 $state = self
::COLON_STATE_TEXT
;
2282 case self
::COLON_STATE_TAGSLASH
:
2284 // Yes, a self-closed tag <blah/>
2285 $state = self
::COLON_STATE_TEXT
;
2287 // Probably we're jumping the gun, and this is an attribute
2288 $state = self
::COLON_STATE_TAG
;
2291 case 5: // self::COLON_STATE_COMMENT:
2293 $state = self
::COLON_STATE_COMMENTDASH
;
2296 case self
::COLON_STATE_COMMENTDASH
:
2298 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2300 $state = self
::COLON_STATE_COMMENT
;
2303 case self
::COLON_STATE_COMMENTDASHDASH
:
2305 $state = self
::COLON_STATE_TEXT
;
2307 $state = self
::COLON_STATE_COMMENT
;
2311 throw new MWException( "State machine error in " . __METHOD__
);
2315 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2318 wfProfileOut( __METHOD__
);
2323 * Return value of a magic variable (like PAGENAME)
2327 function getVariableValue( $index, $frame=false ) {
2328 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2329 global $wgScriptPath, $wgStylePath;
2332 * Some of these require message or data lookups and can be
2333 * expensive to check many times.
2335 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2336 if ( isset( $this->mVarCache
[$index] ) ) {
2337 return $this->mVarCache
[$index];
2341 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2342 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2345 global $wgLocaltimezone;
2346 if ( isset( $wgLocaltimezone ) ) {
2347 $oldtz = date_default_timezone_get();
2348 date_default_timezone_set( $wgLocaltimezone );
2351 $localTimestamp = date( 'YmdHis', $ts );
2352 $localMonth = date( 'm', $ts );
2353 $localMonth1 = date( 'n', $ts );
2354 $localMonthName = date( 'n', $ts );
2355 $localDay = date( 'j', $ts );
2356 $localDay2 = date( 'd', $ts );
2357 $localDayOfWeek = date( 'w', $ts );
2358 $localWeek = date( 'W', $ts );
2359 $localYear = date( 'Y', $ts );
2360 $localHour = date( 'H', $ts );
2361 if ( isset( $wgLocaltimezone ) ) {
2362 date_default_timezone_set( $oldtz );
2366 case 'currentmonth':
2367 $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2369 case 'currentmonth1':
2370 $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2372 case 'currentmonthname':
2373 $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2375 case 'currentmonthnamegen':
2376 $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2378 case 'currentmonthabbrev':
2379 $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2382 $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2385 $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2388 $value = $wgContLang->formatNum( $localMonth );
2391 $value = $wgContLang->formatNum( $localMonth1 );
2393 case 'localmonthname':
2394 $value = $wgContLang->getMonthName( $localMonthName );
2396 case 'localmonthnamegen':
2397 $value = $wgContLang->getMonthNameGen( $localMonthName );
2399 case 'localmonthabbrev':
2400 $value = $wgContLang->getMonthAbbreviation( $localMonthName );
2403 $value = $wgContLang->formatNum( $localDay );
2406 $value = $wgContLang->formatNum( $localDay2 );
2409 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2412 $value = $this->mTitle
->getPartialURL();
2414 case 'fullpagename':
2415 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2417 case 'fullpagenamee':
2418 $value = $this->mTitle
->getPrefixedURL();
2421 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2423 case 'subpagenamee':
2424 $value = $this->mTitle
->getSubpageUrlForm();
2426 case 'basepagename':
2427 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2429 case 'basepagenamee':
2430 $value = wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2432 case 'talkpagename':
2433 if( $this->mTitle
->canTalk() ) {
2434 $talkPage = $this->mTitle
->getTalkPage();
2435 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2440 case 'talkpagenamee':
2441 if( $this->mTitle
->canTalk() ) {
2442 $talkPage = $this->mTitle
->getTalkPage();
2443 $value = $talkPage->getPrefixedUrl();
2448 case 'subjectpagename':
2449 $subjPage = $this->mTitle
->getSubjectPage();
2450 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2452 case 'subjectpagenamee':
2453 $subjPage = $this->mTitle
->getSubjectPage();
2454 $value = $subjPage->getPrefixedUrl();
2457 // Let the edit saving system know we should parse the page
2458 // *after* a revision ID has been assigned.
2459 $this->mOutput
->setFlag( 'vary-revision' );
2460 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2461 $value = $this->mRevisionId
;
2464 // Let the edit saving system know we should parse the page
2465 // *after* a revision ID has been assigned. This is for null edits.
2466 $this->mOutput
->setFlag( 'vary-revision' );
2467 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2468 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2470 case 'revisionday2':
2471 // Let the edit saving system know we should parse the page
2472 // *after* a revision ID has been assigned. This is for null edits.
2473 $this->mOutput
->setFlag( 'vary-revision' );
2474 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2475 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2477 case 'revisionmonth':
2478 // Let the edit saving system know we should parse the page
2479 // *after* a revision ID has been assigned. This is for null edits.
2480 $this->mOutput
->setFlag( 'vary-revision' );
2481 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2482 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2484 case 'revisionyear':
2485 // Let the edit saving system know we should parse the page
2486 // *after* a revision ID has been assigned. This is for null edits.
2487 $this->mOutput
->setFlag( 'vary-revision' );
2488 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2489 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2491 case 'revisiontimestamp':
2492 // Let the edit saving system know we should parse the page
2493 // *after* a revision ID has been assigned. This is for null edits.
2494 $this->mOutput
->setFlag( 'vary-revision' );
2495 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2496 $value = $this->getRevisionTimestamp();
2498 case 'revisionuser':
2499 // Let the edit saving system know we should parse the page
2500 // *after* a revision ID has been assigned. This is for null edits.
2501 $this->mOutput
->setFlag( 'vary-revision' );
2502 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2503 $value = $this->getRevisionUser();
2506 $value = str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2509 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2512 $value = $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2515 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2517 case 'subjectspace':
2518 $value = $this->mTitle
->getSubjectNsText();
2520 case 'subjectspacee':
2521 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2523 case 'currentdayname':
2524 $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2527 $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2530 $value = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2533 $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2536 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2537 // int to remove the padding
2538 $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2541 $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2543 case 'localdayname':
2544 $value = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2547 $value = $wgContLang->formatNum( $localYear, true );
2550 $value = $wgContLang->time( $localTimestamp, false, false );
2553 $value = $wgContLang->formatNum( $localHour, true );
2556 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2557 // int to remove the padding
2558 $value = $wgContLang->formatNum( (int)$localWeek );
2561 $value = $wgContLang->formatNum( $localDayOfWeek );
2563 case 'numberofarticles':
2564 $value = $wgContLang->formatNum( SiteStats
::articles() );
2566 case 'numberoffiles':
2567 $value = $wgContLang->formatNum( SiteStats
::images() );
2569 case 'numberofusers':
2570 $value = $wgContLang->formatNum( SiteStats
::users() );
2572 case 'numberofactiveusers':
2573 $value = $wgContLang->formatNum( SiteStats
::activeUsers() );
2575 case 'numberofpages':
2576 $value = $wgContLang->formatNum( SiteStats
::pages() );
2578 case 'numberofadmins':
2579 $value = $wgContLang->formatNum( SiteStats
::numberingroup('sysop') );
2581 case 'numberofedits':
2582 $value = $wgContLang->formatNum( SiteStats
::edits() );
2584 case 'numberofviews':
2585 $value = $wgContLang->formatNum( SiteStats
::views() );
2587 case 'currenttimestamp':
2588 $value = wfTimestamp( TS_MW
, $ts );
2590 case 'localtimestamp':
2591 $value = $localTimestamp;
2593 case 'currentversion':
2594 $value = SpecialVersion
::getVersion();
2601 return $wgServerName;
2603 return $wgScriptPath;
2605 return $wgStylePath;
2606 case 'directionmark':
2607 return $wgContLang->getDirMark();
2608 case 'contentlanguage':
2609 global $wgContLanguageCode;
2610 return $wgContLanguageCode;
2613 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) )
2620 $this->mVarCache
[$index] = $value;
2626 * initialise the magic variables (like CURRENTMONTHNAME)
2630 function initialiseVariables() {
2631 wfProfileIn( __METHOD__
);
2632 $variableIDs = MagicWord
::getVariableIDs();
2634 $this->mVariables
= new MagicWordArray( $variableIDs );
2635 wfProfileOut( __METHOD__
);
2639 * Preprocess some wikitext and return the document tree.
2640 * This is the ghost of replace_variables().
2642 * @param string $text The text to parse
2643 * @param integer flags Bitwise combination of:
2644 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2645 * included. Default is to assume a direct page view.
2647 * The generated DOM tree must depend only on the input text and the flags.
2648 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2650 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2651 * change in the DOM tree for a given text, must be passed through the section identifier
2652 * in the section edit link and thus back to extractSections().
2654 * The output of this function is currently only cached in process memory, but a persistent
2655 * cache may be implemented at a later date which takes further advantage of these strict
2656 * dependency requirements.
2660 function preprocessToDom ( $text, $flags = 0 ) {
2661 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2666 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2668 public static function splitWhitespace( $s ) {
2669 $ltrimmed = ltrim( $s );
2670 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2671 $trimmed = rtrim( $ltrimmed );
2672 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2674 $w2 = substr( $ltrimmed, -$diff );
2678 return array( $w1, $trimmed, $w2 );
2682 * Replace magic variables, templates, and template arguments
2683 * with the appropriate text. Templates are substituted recursively,
2684 * taking care to avoid infinite loops.
2686 * Note that the substitution depends on value of $mOutputType:
2687 * self::OT_WIKI: only {{subst:}} templates
2688 * self::OT_PREPROCESS: templates but not extension tags
2689 * self::OT_HTML: all templates and extension tags
2691 * @param string $tex The text to transform
2692 * @param PPFrame $frame Object describing the arguments passed to the template.
2693 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2694 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2695 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2698 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2699 # Is there any text? Also, Prevent too big inclusions!
2700 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2703 wfProfileIn( __METHOD__
);
2705 if ( $frame === false ) {
2706 $frame = $this->getPreprocessor()->newFrame();
2707 } elseif ( !( $frame instanceof PPFrame
) ) {
2708 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2709 $frame = $this->getPreprocessor()->newCustomFrame($frame);
2712 $dom = $this->preprocessToDom( $text );
2713 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2714 $text = $frame->expand( $dom, $flags );
2716 wfProfileOut( __METHOD__
);
2720 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2721 static function createAssocArgs( $args ) {
2722 $assocArgs = array();
2724 foreach( $args as $arg ) {
2725 $eqpos = strpos( $arg, '=' );
2726 if ( $eqpos === false ) {
2727 $assocArgs[$index++
] = $arg;
2729 $name = trim( substr( $arg, 0, $eqpos ) );
2730 $value = trim( substr( $arg, $eqpos+
1 ) );
2731 if ( $value === false ) {
2734 if ( $name !== false ) {
2735 $assocArgs[$name] = $value;
2744 * Warn the user when a parser limitation is reached
2745 * Will warn at most once the user per limitation type
2747 * @param string $limitationType, should be one of:
2748 * 'expensive-parserfunction' (corresponding messages: 'expensive-parserfunction-warning', 'expensive-parserfunction-category')
2749 * 'post-expand-template-argument' (corresponding messages: 'post-expand-template-argument-warning', 'post-expand-template-argument-category')
2750 * 'post-expand-template-inclusion' (corresponding messages: 'post-expand-template-inclusion-warning', 'post-expand-template-inclusion-category')
2751 * @params int $current, $max When an explicit limit has been
2752 * exceeded, provide the values (optional)
2754 function limitationWarn( $limitationType, $current=null, $max=null) {
2755 //does no harm if $current and $max are present but are unnecessary for the message
2756 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
2757 $this->mOutput
->addWarning( $warning );
2758 $this->addTrackingCategory( "$limitationType-category" );
2762 * Return the text of a template, after recursively
2763 * replacing any variables or templates within the template.
2765 * @param array $piece The parts of the template
2766 * $piece['title']: the title, i.e. the part before the |
2767 * $piece['parts']: the parameter array
2768 * $piece['lineStart']: whether the brace was at the start of a line
2769 * @param PPFrame The current frame, contains template arguments
2770 * @return string the text of the template
2773 function braceSubstitution( $piece, $frame ) {
2774 global $wgContLang, $wgNonincludableNamespaces;
2775 wfProfileIn( __METHOD__
);
2776 wfProfileIn( __METHOD__
.'-setup' );
2779 $found = false; # $text has been filled
2780 $nowiki = false; # wiki markup in $text should be escaped
2781 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2782 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2783 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2784 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2786 # Title object, where $text came from
2789 # $part1 is the bit before the first |, and must contain only title characters.
2790 # Various prefixes will be stripped from it later.
2791 $titleWithSpaces = $frame->expand( $piece['title'] );
2792 $part1 = trim( $titleWithSpaces );
2795 # Original title text preserved for various purposes
2796 $originalTitle = $part1;
2798 # $args is a list of argument nodes, starting from index 0, not including $part1
2799 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2800 wfProfileOut( __METHOD__
.'-setup' );
2803 wfProfileIn( __METHOD__
.'-modifiers' );
2805 $mwSubst = MagicWord
::get( 'subst' );
2806 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2807 # One of two possibilities is true:
2808 # 1) Found SUBST but not in the PST phase
2809 # 2) Didn't find SUBST and in the PST phase
2810 # In either case, return without further processing
2811 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2818 if ( !$found && $args->getLength() == 0 ) {
2819 $id = $this->mVariables
->matchStartToEnd( $part1 );
2820 if ( $id !== false ) {
2821 $text = $this->getVariableValue( $id, $frame );
2822 if (MagicWord
::getCacheTTL($id)>-1)
2823 $this->mOutput
->mContainsOldMagic
= true;
2828 # MSG, MSGNW and RAW
2831 $mwMsgnw = MagicWord
::get( 'msgnw' );
2832 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2835 # Remove obsolete MSG:
2836 $mwMsg = MagicWord
::get( 'msg' );
2837 $mwMsg->matchStartAndRemove( $part1 );
2841 $mwRaw = MagicWord
::get( 'raw' );
2842 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2843 $forceRawInterwiki = true;
2846 wfProfileOut( __METHOD__
.'-modifiers' );
2850 wfProfileIn( __METHOD__
. '-pfunc' );
2852 $colonPos = strpos( $part1, ':' );
2853 if ( $colonPos !== false ) {
2854 # Case sensitive functions
2855 $function = substr( $part1, 0, $colonPos );
2856 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2857 $function = $this->mFunctionSynonyms
[1][$function];
2859 # Case insensitive functions
2860 $function = $wgContLang->lc( $function );
2861 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2862 $function = $this->mFunctionSynonyms
[0][$function];
2868 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2869 $initialArgs = array( &$this );
2870 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2871 if ( $flags & SFH_OBJECT_ARGS
) {
2872 # Add a frame parameter, and pass the arguments as an array
2873 $allArgs = $initialArgs;
2874 $allArgs[] = $frame;
2875 for ( $i = 0; $i < $args->getLength(); $i++
) {
2876 $funcArgs[] = $args->item( $i );
2878 $allArgs[] = $funcArgs;
2880 # Convert arguments to plain text
2881 for ( $i = 0; $i < $args->getLength(); $i++
) {
2882 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2884 $allArgs = array_merge( $initialArgs, $funcArgs );
2887 # Workaround for PHP bug 35229 and similar
2888 if ( !is_callable( $callback ) ) {
2889 wfProfileOut( __METHOD__
. '-pfunc' );
2890 wfProfileOut( __METHOD__
);
2891 throw new MWException( "Tag hook for $function is not callable\n" );
2893 $result = call_user_func_array( $callback, $allArgs );
2896 $preprocessFlags = 0;
2898 if ( is_array( $result ) ) {
2899 if ( isset( $result[0] ) ) {
2901 unset( $result[0] );
2904 // Extract flags into the local scope
2905 // This allows callers to set flags such as nowiki, found, etc.
2911 $text = $this->preprocessToDom( $text, $preprocessFlags );
2916 wfProfileOut( __METHOD__
. '-pfunc' );
2919 # Finish mangling title and then check for loops.
2920 # Set $title to a Title object and $titleText to the PDBK
2923 # Split the title into page and subpage
2925 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2926 if ($subpage !== '') {
2927 $ns = $this->mTitle
->getNamespace();
2929 $title = Title
::newFromText( $part1, $ns );
2931 $titleText = $title->getPrefixedText();
2932 # Check for language variants if the template is not found
2933 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2934 $wgContLang->findVariantLink( $part1, $title, true );
2936 # Do recursion depth check
2937 $limit = $this->mOptions
->getMaxTemplateDepth();
2938 if ( $frame->depth
>= $limit ) {
2940 $text = '<span class="error">' . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit ) . '</span>';
2945 # Load from database
2946 if ( !$found && $title ) {
2947 wfProfileIn( __METHOD__
. '-loadtpl' );
2948 if ( !$title->isExternal() ) {
2949 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2950 $text = SpecialPage
::capturePath( $title );
2951 if ( is_string( $text ) ) {
2954 $this->disableCache();
2956 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2957 $found = false; //access denied
2958 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
2960 list( $text, $title ) = $this->getTemplateDom( $title );
2961 if ( $text !== false ) {
2967 # If the title is valid but undisplayable, make a link to it
2968 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2969 $text = "[[:$titleText]]";
2972 } elseif ( $title->isTrans() ) {
2973 // Interwiki transclusion
2974 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
2975 $text = $this->interwikiTransclude( $title, 'render' );
2978 $text = $this->interwikiTransclude( $title, 'raw' );
2979 // Preprocess it like a template
2980 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
2986 # Do infinite loop check
2987 # This has to be done after redirect resolution to avoid infinite loops via redirects
2988 if ( !$frame->loopCheck( $title ) ) {
2990 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
2991 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
2993 wfProfileOut( __METHOD__
. '-loadtpl' );
2996 # If we haven't found text to substitute by now, we're done
2997 # Recover the source wikitext and return it
2999 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3000 wfProfileOut( __METHOD__
);
3001 return array( 'object' => $text );
3004 # Expand DOM-style return values in a child frame
3005 if ( $isChildObj ) {
3006 # Clean up argument array
3007 $newFrame = $frame->newChild( $args, $title );
3010 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3011 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3012 # Expansion is eligible for the empty-frame cache
3013 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3014 $text = $this->mTplExpandCache
[$titleText];
3016 $text = $newFrame->expand( $text );
3017 $this->mTplExpandCache
[$titleText] = $text;
3020 # Uncached expansion
3021 $text = $newFrame->expand( $text );
3024 if ( $isLocalObj && $nowiki ) {
3025 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3026 $isLocalObj = false;
3029 # Replace raw HTML by a placeholder
3030 # Add a blank line preceding, to prevent it from mucking up
3031 # immediately preceding headings
3033 $text = "\n\n" . $this->insertStripItem( $text );
3035 # Escape nowiki-style return values
3036 elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3037 $text = wfEscapeWikiText( $text );
3039 # Bug 529: if the template begins with a table or block-level
3040 # element, it should be treated as beginning a new line.
3041 # This behaviour is somewhat controversial.
3042 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3043 $text = "\n" . $text;
3046 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3047 # Error, oversize inclusion
3048 $text = "[[$originalTitle]]" .
3049 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3050 $this->limitationWarn( 'post-expand-template-inclusion' );
3053 if ( $isLocalObj ) {
3054 $ret = array( 'object' => $text );
3056 $ret = array( 'text' => $text );
3059 wfProfileOut( __METHOD__
);
3064 * Get the semi-parsed DOM representation of a template with a given title,
3065 * and its redirect destination title. Cached.
3067 function getTemplateDom( $title ) {
3068 $cacheTitle = $title;
3069 $titleText = $title->getPrefixedDBkey();
3071 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3072 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3073 $title = Title
::makeTitle( $ns, $dbk );
3074 $titleText = $title->getPrefixedDBkey();
3076 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3077 return array( $this->mTplDomCache
[$titleText], $title );
3080 // Cache miss, go to the database
3081 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3083 if ( $text === false ) {
3084 $this->mTplDomCache
[$titleText] = false;
3085 return array( false, $title );
3088 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3089 $this->mTplDomCache
[ $titleText ] = $dom;
3091 if (! $title->equals($cacheTitle)) {
3092 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3093 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3096 return array( $dom, $title );
3100 * Fetch the unparsed text of a template and register a reference to it.
3102 function fetchTemplateAndTitle( $title ) {
3103 $templateCb = $this->mOptions
->getTemplateCallback();
3104 $stuff = call_user_func( $templateCb, $title, $this );
3105 $text = $stuff['text'];
3106 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3107 if ( isset( $stuff['deps'] ) ) {
3108 foreach ( $stuff['deps'] as $dep ) {
3109 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3112 return array($text,$finalTitle);
3115 function fetchTemplate( $title ) {
3116 $rv = $this->fetchTemplateAndTitle($title);
3121 * Static function to get a template
3122 * Can be overridden via ParserOptions::setTemplateCallback().
3124 static function statelessFetchTemplate( $title, $parser=false ) {
3125 $text = $skip = false;
3126 $finalTitle = $title;
3129 // Loop to fetch the article, with up to 1 redirect
3130 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3131 # Give extensions a chance to select the revision instead
3132 $id = false; // Assume current
3133 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3139 'page_id' => $title->getArticleID(),
3143 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3144 $rev_id = $rev ?
$rev->getId() : 0;
3145 // If there is no current revision, there is no page
3146 if( $id === false && !$rev ) {
3147 $linkCache = LinkCache
::singleton();
3148 $linkCache->addBadLinkObj( $title );
3153 'page_id' => $title->getArticleID(),
3154 'rev_id' => $rev_id );
3157 $text = $rev->getText();
3158 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3160 $message = $wgContLang->lcfirst( $title->getText() );
3161 $text = wfMsgForContentNoTrans( $message );
3162 if( wfEmptyMsg( $message, $text ) ) {
3169 if ( $text === false ) {
3173 $finalTitle = $title;
3174 $title = Title
::newFromRedirect( $text );
3178 'finalTitle' => $finalTitle,
3183 * Transclude an interwiki link.
3185 function interwikiTransclude( $title, $action ) {
3186 global $wgEnableScaryTranscluding;
3188 if (!$wgEnableScaryTranscluding)
3189 return wfMsg('scarytranscludedisabled');
3191 $url = $title->getFullUrl( "action=$action" );
3193 if (strlen($url) > 255)
3194 return wfMsg('scarytranscludetoolong');
3195 return $this->fetchScaryTemplateMaybeFromCache($url);
3198 function fetchScaryTemplateMaybeFromCache($url) {
3199 global $wgTranscludeCacheExpiry;
3200 $dbr = wfGetDB(DB_SLAVE
);
3201 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3202 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3203 array('tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3205 return $obj->tc_contents
;
3208 $text = Http
::get($url);
3210 return wfMsg('scarytranscludefailed', $url);
3212 $dbw = wfGetDB(DB_MASTER
);
3213 $dbw->replace('transcache', array('tc_url'), array(
3215 'tc_time' => $dbw->timestamp( time() ),
3216 'tc_contents' => $text));
3222 * Triple brace replacement -- used for template arguments
3225 function argSubstitution( $piece, $frame ) {
3226 wfProfileIn( __METHOD__
);
3229 $parts = $piece['parts'];
3230 $nameWithSpaces = $frame->expand( $piece['title'] );
3231 $argName = trim( $nameWithSpaces );
3233 $text = $frame->getArgument( $argName );
3234 if ( $text === false && $parts->getLength() > 0
3238 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3241 # No match in frame, use the supplied default
3242 $object = $parts->item( 0 )->getChildren();
3244 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3245 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3246 $this->limitationWarn( 'post-expand-template-argument' );
3249 if ( $text === false && $object === false ) {
3251 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3253 if ( $error !== false ) {
3256 if ( $object !== false ) {
3257 $ret = array( 'object' => $object );
3259 $ret = array( 'text' => $text );
3262 wfProfileOut( __METHOD__
);
3267 * Return the text to be used for a given extension tag.
3268 * This is the ghost of strip().
3270 * @param array $params Associative array of parameters:
3271 * name PPNode for the tag name
3272 * attr PPNode for unparsed text where tag attributes are thought to be
3273 * attributes Optional associative array of parsed attributes
3274 * inner Contents of extension element
3275 * noClose Original text did not have a close tag
3276 * @param PPFrame $frame
3278 function extensionSubstitution( $params, $frame ) {
3279 global $wgRawHtml, $wgContLang;
3281 $name = $frame->expand( $params['name'] );
3282 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3283 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3285 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3287 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3288 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3289 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3290 $name = strtolower( $name );
3291 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3292 if ( isset( $params['attributes'] ) ) {
3293 $attributes = $attributes +
$params['attributes'];
3301 throw new MWException( '<html> extension tag encountered unexpectedly' );
3304 $content = strtr($content, array('-{' => '-{', '}-' => '}-'));
3305 $output = Xml
::escapeTagsOnly( $content );
3308 $output = $this->renderImageGallery( $content, $attributes );
3311 $output = $this->renderHyperlink( $content, $attributes, $frame );
3314 if ( $this->mOptions
->getUseTeX() ) {
3315 $output = $wgContLang->armourMath(
3316 MathRenderer
::renderMath( $content, $attributes ) );
3319 /* else let a tag hook handle it (bug 21222) */
3321 if( isset( $this->mTagHooks
[$name] ) ) {
3322 # Workaround for PHP bug 35229 and similar
3323 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3324 throw new MWException( "Tag hook for $name is not callable\n" );
3326 $output = call_user_func_array( $this->mTagHooks
[$name],
3327 array( $content, $attributes, $this, $frame ) );
3328 } elseif( isset( $this->mFunctionTagHooks
[$name] ) ) {
3329 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3330 if( !is_callable( $callback ) )
3331 throw new MWException( "Tag hook for $name is not callable\n" );
3333 $output = call_user_func_array( $callback,
3334 array( &$this, $frame, $content, $attributes ) );
3336 $output = '<span class="error">Invalid tag extension name: ' .
3337 htmlspecialchars( $name ) . '</span>';
3341 if ( is_null( $attrText ) ) {
3344 if ( isset( $params['attributes'] ) ) {
3345 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3346 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3347 htmlspecialchars( $attrValue ) . '"';
3350 if ( $content === null ) {
3351 $output = "<$name$attrText/>";
3353 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3354 $output = "<$name$attrText>$content$close";
3358 if( $isFunctionTag ) {
3360 } elseif ( $name === 'html' ||
$name === 'nowiki' ) {
3361 $this->mStripState
->nowiki
->setPair( $marker, $output );
3363 $this->mStripState
->general
->setPair( $marker, $output );
3369 * Increment an include size counter
3371 * @param string $type The type of expansion
3372 * @param integer $size The size of the text
3373 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3375 function incrementIncludeSize( $type, $size ) {
3376 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3379 $this->mIncludeSizes
[$type] +
= $size;
3385 * Increment the expensive function count
3387 * @return boolean False if the limit has been exceeded
3389 function incrementExpensiveFunctionCount() {
3390 global $wgExpensiveParserFunctionLimit;
3391 $this->mExpensiveFunctionCount++
;
3392 if($this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit) {
3399 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3400 * Fills $this->mDoubleUnderscores, returns the modified text
3402 function doDoubleUnderscore( $text ) {
3403 global $wgDisableLangConversion;
3404 wfProfileIn( __METHOD__
);
3406 // The position of __TOC__ needs to be recorded
3407 $mw = MagicWord
::get( 'toc' );
3408 if( $mw->match( $text ) ) {
3409 $this->mShowToc
= true;
3410 $this->mForceTocPosition
= true;
3412 // Set a placeholder. At the end we'll fill it in with the TOC.
3413 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3415 // Only keep the first one.
3416 $text = $mw->replace( '', $text );
3419 // Now match and remove the rest of them
3420 $mwa = MagicWord
::getDoubleUnderscoreArray();
3421 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3423 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3424 $this->mOutput
->mNoGallery
= true;
3426 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3427 $this->mShowToc
= false;
3429 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3430 $this->mOutput
->setProperty( 'hiddencat', 'y' );
3431 $this->addTrackingCategory( 'hidden-category-category' );
3433 # (bug 8068) Allow control over whether robots index a page.
3435 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3436 # is not desirable, the last one on the page should win.
3437 if( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3438 $this->mOutput
->setIndexPolicy( 'noindex' );
3439 $this->addTrackingCategory( 'noindex-category' );
3441 if( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ){
3442 $this->mOutput
->setIndexPolicy( 'index' );
3443 $this->addTrackingCategory( 'index-category' );
3446 if ( !$wgDisableLangConversion ) {
3447 if( isset( $this->mDoubleUnderscores
['notitleconvert'] ) ){
3448 $this->mDoTitleConvert
= false;
3451 // Don't convert talk pages
3452 if( isset( $this->mDoubleUnderscores
['nocontentconvert'] )
3453 && !$this->mTitle
->isTalkPage() ){
3454 $this->mDoContentConvert
= false;
3458 wfProfileOut( __METHOD__
);
3463 * Add a tracking category, getting the title from a system message,
3464 * or print a debug message if the title is invalid.
3465 * @param $msg String message key
3466 * @return Bool whether the addition was successful
3468 protected function addTrackingCategory( $msg ){
3469 $cat = wfMsgForContent( $msg );
3471 # Allow tracking categories to be disabled by setting them to "-"
3472 if( $cat === '-' ) return false;
3474 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3475 if ( $containerCategory ) {
3476 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3479 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3485 * This function accomplishes several tasks:
3486 * 1) Auto-number headings if that option is enabled
3487 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3488 * 3) Add a Table of contents on the top for users who have enabled the option
3489 * 4) Auto-anchor headings
3491 * It loops through all headlines, collects the necessary data, then splits up the
3492 * string and re-inserts the newly formatted headlines.
3494 * @param string $text
3495 * @param string $origText Original, untouched wikitext
3496 * @param boolean $isMain
3499 function formatHeadings( $text, $origText, $isMain=true ) {
3500 global $wgMaxTocLevel, $wgContLang, $wgEnforceHtmlIds;
3502 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3503 $showEditLink = $this->mOptions
->getEditSection();
3505 // Do not call quickUserCan unless necessary
3506 if( $showEditLink && !$this->mTitle
->quickUserCan( 'edit' ) ) {
3510 # Inhibit editsection links if requested in the page
3511 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ||
$this->mOptions
->getIsPrintable() ) {
3515 # Get all headlines for numbering them and adding funky stuff like [edit]
3516 # links - this is for later, but we need the number of headlines right now
3518 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3520 # if there are fewer than 4 headlines in the article, do not show TOC
3521 # unless it's been explicitly enabled.
3522 $enoughToc = $this->mShowToc
&&
3523 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3525 # Allow user to stipulate that a page should have a "new section"
3526 # link added via __NEWSECTIONLINK__
3527 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3528 $this->mOutput
->setNewSection( true );
3531 # Allow user to remove the "new section"
3532 # link via __NONEWSECTIONLINK__
3533 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3534 $this->mOutput
->hideNewSection( true );
3537 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3538 # override above conditions and always show TOC above first header
3539 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3540 $this->mShowToc
= true;
3544 # We need this to perform operations on the HTML
3545 $sk = $this->mOptions
->getSkin();
3551 # Ugh .. the TOC should have neat indentation levels which can be
3552 # passed to the skin functions. These are determined here
3556 $sublevelCount = array();
3557 $levelCount = array();
3563 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3564 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3565 $oldType = $this->mOutputType
;
3566 $this->setOutputType( self
::OT_WIKI
);
3567 $frame = $this->getPreprocessor()->newFrame();
3568 $root = $this->preprocessToDom( $origText );
3569 $node = $root->getFirstChild();
3573 foreach( $matches[3] as $headline ) {
3574 $isTemplate = false;
3576 $sectionIndex = false;
3578 $markerMatches = array();
3579 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3580 $serial = $markerMatches[1];
3581 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3582 $isTemplate = ($titleText != $baseTitleText);
3583 $headline = preg_replace("/^$markerRegex/", "", $headline);
3587 $prevlevel = $level;
3588 $prevtoclevel = $toclevel;
3590 $level = $matches[1][$headlineCount];
3592 if ( $level > $prevlevel ) {
3593 # Increase TOC level
3595 $sublevelCount[$toclevel] = 0;
3596 if( $toclevel<$wgMaxTocLevel ) {
3597 $prevtoclevel = $toclevel;
3598 $toc .= $sk->tocIndent();
3602 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3603 # Decrease TOC level, find level to jump to
3605 for ($i = $toclevel; $i > 0; $i--) {
3606 if ( $levelCount[$i] == $level ) {
3607 # Found last matching level
3611 elseif ( $levelCount[$i] < $level ) {
3612 # Found first matching level below current level
3617 if( $i == 0 ) $toclevel = 1;
3618 if( $toclevel<$wgMaxTocLevel ) {
3619 if($prevtoclevel < $wgMaxTocLevel) {
3620 # Unindent only if the previous toc level was shown :p
3621 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3622 $prevtoclevel = $toclevel;
3624 $toc .= $sk->tocLineEnd();
3629 # No change in level, end TOC line
3630 if( $toclevel<$wgMaxTocLevel ) {
3631 $toc .= $sk->tocLineEnd();
3635 $levelCount[$toclevel] = $level;
3637 # count number of headlines for each level
3638 @$sublevelCount[$toclevel]++
;
3640 for( $i = 1; $i <= $toclevel; $i++
) {
3641 if( !empty( $sublevelCount[$i] ) ) {
3645 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3650 # The safe header is a version of the header text safe to use for links
3651 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3652 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3654 # Remove link placeholders by the link text.
3655 # <!--LINK number-->
3657 # link text with suffix
3658 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3660 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3661 $tocline = preg_replace(
3662 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3666 $tocline = trim( $tocline );
3668 # For the anchor, strip out HTML-y stuff period
3669 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3670 $safeHeadline = preg_replace( '/[ _]+/', ' ', $safeHeadline );
3671 $safeHeadline = trim( $safeHeadline );
3673 # Save headline for section edit hint before it's escaped
3674 $headlineHint = $safeHeadline;
3676 if ( $wgEnforceHtmlIds ) {
3677 $legacyHeadline = false;
3678 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
3681 # For reverse compatibility, provide an id that's
3682 # HTML4-compatible, like we used to.
3684 # It may be worth noting, academically, that it's possible for
3685 # the legacy anchor to conflict with a non-legacy headline
3686 # anchor on the page. In this case likely the "correct" thing
3687 # would be to either drop the legacy anchors or make sure
3688 # they're numbered first. However, this would require people
3689 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3690 # manually, so let's not bother worrying about it.
3691 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
3693 $safeHeadline = Sanitizer
::escapeId( $safeHeadline, 'xml' );
3695 if ( $legacyHeadline == $safeHeadline ) {
3696 # No reason to have both (in fact, we can't)
3697 $legacyHeadline = false;
3698 } elseif ( $legacyHeadline != Sanitizer
::escapeId(
3699 $legacyHeadline, 'xml' ) ) {
3700 # The legacy id is invalid XML. We used to allow this, but
3701 # there's no reason to do so anymore. Backward
3702 # compatibility will fail slightly in this case, but it's
3704 $legacyHeadline = false;
3708 # HTML names must be case-insensitively unique (bug 10721). FIXME:
3709 # Does this apply to Unicode characters? Because we aren't
3710 # handling those here.
3711 $arrayKey = strtolower( $safeHeadline );
3712 if ( $legacyHeadline === false ) {
3713 $legacyArrayKey = false;
3715 $legacyArrayKey = strtolower( $legacyHeadline );
3718 # count how many in assoc. array so we can track dupes in anchors
3719 if ( isset( $refers[$arrayKey] ) ) {
3720 $refers[$arrayKey]++
;
3722 $refers[$arrayKey] = 1;
3724 if ( isset( $refers[$legacyArrayKey] ) ) {
3725 $refers[$legacyArrayKey]++
;
3727 $refers[$legacyArrayKey] = 1;
3730 # Don't number the heading if it is the only one (looks silly)
3731 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3732 # the two are different if the line contains a link
3733 $headline=$numbering . ' ' . $headline;
3736 # Create the anchor for linking from the TOC to the section
3737 $anchor = $safeHeadline;
3738 $legacyAnchor = $legacyHeadline;
3739 if ( $refers[$arrayKey] > 1 ) {
3740 $anchor .= '_' . $refers[$arrayKey];
3742 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3743 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3745 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3746 $toc .= $sk->tocLine($anchor, $tocline,
3747 $numbering, $toclevel, ($isTemplate ?
false : $sectionIndex));
3750 # Add the section to the section tree
3751 # Find the DOM node for this header
3752 while ( $node && !$isTemplate ) {
3753 if ( $node->getName() === 'h' ) {
3754 $bits = $node->splitHeading();
3755 if ( $bits['i'] == $sectionIndex )
3758 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
3759 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
3760 $node = $node->getNextSibling();
3763 'toclevel' => $toclevel,
3766 'number' => $numbering,
3767 'index' => ($isTemplate ?
'T-' : '' ) . $sectionIndex,
3768 'fromtitle' => $titleText,
3769 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
3770 'anchor' => $anchor,
3773 # give headline the correct <h#> tag
3774 if( $showEditLink && $sectionIndex !== false ) {
3776 # Put a T flag in the section identifier, to indicate to extractSections()
3777 # that sections inside <includeonly> should be counted.
3778 $editlink = $sk->doEditSectionLink(Title
::newFromText( $titleText ), "T-$sectionIndex");
3780 $editlink = $sk->doEditSectionLink($this->mTitle
, $sectionIndex, $headlineHint);
3785 $head[$headlineCount] = $sk->makeHeadline( $level,
3786 $matches['attrib'][$headlineCount], $anchor, $headline,
3787 $editlink, $legacyAnchor );
3792 $this->setOutputType( $oldType );
3794 # Never ever show TOC if no headers
3795 if( $numVisible < 1 ) {
3800 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3801 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3803 $toc = $sk->tocList( $toc );
3804 $this->mOutput
->setTOCHTML( $toc );
3808 $this->mOutput
->setSections( $tocraw );
3811 # split up and insert constructed headlines
3813 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3816 foreach( $blocks as $block ) {
3817 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3818 # This is the [edit] link that appears for the top block of text when
3819 # section editing is enabled
3821 # Disabled because it broke block formatting
3822 # For example, a bullet point in the top line
3823 # $full .= $sk->editSectionLink(0);
3826 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3827 # Top anchor now in skin
3831 if( !empty( $head[$i] ) ) {
3836 if( $this->mForceTocPosition
) {
3837 return str_replace( '<!--MWTOC-->', $toc, $full );
3844 * Merge $tree2 into $tree1 by replacing the section with index
3845 * $section in $tree1 and its descendants with the sections in $tree2.
3846 * Note that in the returned section tree, only the 'index' and
3847 * 'byteoffset' fields are guaranteed to be correct.
3848 * @param $tree1 array Section tree from ParserOutput::getSectons()
3849 * @param $tree2 array Section tree
3850 * @param $section int Section index
3851 * @param $title Title Title both section trees come from
3852 * @param $len2 int Length of the original wikitext for $tree2
3853 * @return array Merged section tree
3855 public static function mergeSectionTrees( $tree1, $tree2, $section, $title, $len2 ) {
3858 $targetLevel = false;
3862 $numbering = array( 0 );
3863 $titletext = $title->getPrefixedDBkey();
3864 foreach ( $tree1 as $s ) {
3865 if ( $targetLevel !== false ) {
3866 if ( $s['level'] <= $targetLevel )
3867 // We've skipped enough
3868 $targetLevel = false;
3872 if ( $s['index'] != $section ||
3873 $s['fromtitle'] != $titletext ) {
3874 self
::incrementNumbering( $numbering,
3875 $s['toclevel'], $lastLevel );
3877 // Rewrite index, byteoffset and number
3878 if ( $s['fromtitle'] == $titletext ) {
3879 $s['index'] = $nextIndex++
;
3881 $s['byteoffset'] +
= $len2;
3883 $s['number'] = implode( '.', array_map(
3884 array( $wgContLang, 'formatnum' ),
3886 $lastLevel = $s['toclevel'];
3889 // We're at $section
3890 // Insert sections from $tree2 here
3891 foreach ( $tree2 as $s2 ) {
3892 // Rewrite the fields in $s2
3893 // before inserting it
3894 $s2['toclevel'] +
= $s['toclevel'] - 1;
3895 $s2['level'] +
= $s['level'] - 1;
3896 $s2['index'] = $nextIndex++
;
3897 $s2['byteoffset'] +
= $s['byteoffset'];
3899 self
::incrementNumbering( $numbering,
3900 $s2['toclevel'], $lastLevel );
3901 $s2['number'] = implode( '.', array_map(
3902 array( $wgContLang, 'formatnum' ),
3904 $lastLevel = $s2['toclevel'];
3907 // Skip all descendants of $section in $tree1
3908 $targetLevel = $s['level'];
3916 * Increment a section number. Helper function for mergeSectionTrees()
3917 * @param $number array Array representing a section number
3918 * @param $level int Current TOC level (depth)
3919 * @param $lastLevel int Level of previous TOC entry
3921 private static function incrementNumbering( &$number, $level, $lastLevel ) {
3922 if ( $level > $lastLevel )
3923 $number[$level - 1] = 1;
3924 else if ( $level < $lastLevel ) {
3925 foreach ( $number as $key => $unused )
3926 if ( $key >= $level )
3927 unset( $number[$key] );
3928 $number[$level - 1]++
;
3930 $number[$level - 1]++
;
3934 * Transform wiki markup when saving a page by doing \r\n -> \n
3935 * conversion, substitting signatures, {{subst:}} templates, etc.
3937 * @param string $text the text to transform
3938 * @param Title &$title the Title object for the current article
3939 * @param User $user the User object describing the current user
3940 * @param ParserOptions $options parsing options
3941 * @param bool $clearState whether to clear the parser state first
3942 * @return string the altered wiki markup
3945 function preSaveTransform( $text, Title
$title, $user, $options, $clearState = true ) {
3946 $this->mOptions
= $options;
3947 $this->setTitle( $title );
3948 $this->setOutputType( self
::OT_WIKI
);
3950 if ( $clearState ) {
3951 $this->clearState();
3957 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3958 $text = $this->pstPass2( $text, $user );
3959 $text = $this->mStripState
->unstripBoth( $text );
3964 * Pre-save transform helper function
3967 function pstPass2( $text, $user ) {
3968 global $wgContLang, $wgLocaltimezone;
3970 /* Note: This is the timestamp saved as hardcoded wikitext to
3971 * the database, we use $wgContLang here in order to give
3972 * everyone the same signature and use the default one rather
3973 * than the one selected in each user's preferences.
3975 * (see also bug 12815)
3977 $ts = $this->mOptions
->getTimestamp();
3978 if ( isset( $wgLocaltimezone ) ) {
3979 $tz = $wgLocaltimezone;
3981 $tz = date_default_timezone_get();
3984 $unixts = wfTimestamp( TS_UNIX
, $ts );
3985 $oldtz = date_default_timezone_get();
3986 date_default_timezone_set( $tz );
3987 $ts = date( 'YmdHis', $unixts );
3988 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
3990 /* Allow translation of timezones trough wiki. date() can return
3991 * whatever crap the system uses, localised or not, so we cannot
3992 * ship premade translations.
3994 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
3995 $value = wfMsgForContent( $key );
3996 if ( !wfEmptyMsg( $key, $value ) ) $tzMsg = $value;
3998 date_default_timezone_set( $oldtz );
4000 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4002 # Variable replacement
4003 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4004 $text = $this->replaceVariables( $text );
4007 $sigText = $this->getUserSig( $user );
4008 $text = strtr( $text, array(
4010 '~~~~' => "$sigText $d",
4014 # Context links: [[|name]] and [[name (context)|]]
4016 global $wgLegalTitleChars;
4017 $tc = "[$wgLegalTitleChars]";
4018 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4020 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4021 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
4022 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4023 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4025 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4026 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4027 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4028 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4030 $t = $this->mTitle
->getText();
4032 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4033 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4034 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4035 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4037 # if there's no context, don't bother duplicating the title
4038 $text = preg_replace( $p2, '[[\\1]]', $text );
4041 # Trim trailing whitespace
4042 $text = rtrim( $text );
4048 * Fetch the user's signature text, if any, and normalize to
4049 * validated, ready-to-insert wikitext.
4050 * If you have pre-fetched the nickname or the fancySig option, you can
4051 * specify them here to save a database query.
4056 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4057 global $wgMaxSigChars;
4059 $username = $user->getName();
4061 // If not given, retrieve from the user object.
4062 if ( $nickname === false )
4063 $nickname = $user->getOption( 'nickname' );
4065 if ( is_null( $fancySig ) )
4066 $fancySig = $user->getBoolOption( 'fancysig' );
4068 $nickname = $nickname == null ?
$username : $nickname;
4070 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4071 $nickname = $username;
4072 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4073 } elseif( $fancySig !== false ) {
4074 # Sig. might contain markup; validate this
4075 if( $this->validateSig( $nickname ) !== false ) {
4076 # Validated; clean up (if needed) and return it
4077 return $this->cleanSig( $nickname, true );
4079 # Failed to validate; fall back to the default
4080 $nickname = $username;
4081 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4085 // Make sure nickname doesnt get a sig in a sig
4086 $nickname = $this->cleanSigInSig( $nickname );
4088 # If we're still here, make it a link to the user page
4089 $userText = wfEscapeWikiText( $username );
4090 $nickText = wfEscapeWikiText( $nickname );
4091 if ( $user->isAnon() ) {
4092 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4094 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4099 * Check that the user's signature contains no bad XML
4101 * @param string $text
4102 * @return mixed An expanded string, or false if invalid.
4104 function validateSig( $text ) {
4105 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4109 * Clean up signature text
4111 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4112 * 2) Substitute all transclusions
4114 * @param string $text
4115 * @param $parsing Whether we're cleaning (preferences save) or parsing
4116 * @return string Signature text
4118 function cleanSig( $text, $parsing = false ) {
4121 $this->clearState();
4122 $this->setTitle( $wgTitle );
4123 $this->mOptions
= new ParserOptions
;
4124 $this->setOutputType
= self
::OT_PREPROCESS
;
4127 # Option to disable this feature
4128 if ( !$this->mOptions
->getCleanSignatures() ) {
4132 # FIXME: regex doesn't respect extension tags or nowiki
4133 # => Move this logic to braceSubstitution()
4134 $substWord = MagicWord
::get( 'subst' );
4135 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4136 $substText = '{{' . $substWord->getSynonym( 0 );
4138 $text = preg_replace( $substRegex, $substText, $text );
4139 $text = $this->cleanSigInSig( $text );
4140 $dom = $this->preprocessToDom( $text );
4141 $frame = $this->getPreprocessor()->newFrame();
4142 $text = $frame->expand( $dom );
4145 $text = $this->mStripState
->unstripBoth( $text );
4152 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4153 * @param string $text
4154 * @return string Signature text with /~{3,5}/ removed
4156 function cleanSigInSig( $text ) {
4157 $text = preg_replace( '/~{3,5}/', '', $text );
4162 * Set up some variables which are usually set up in parse()
4163 * so that an external function can call some class members with confidence
4166 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
4167 $this->setTitle( $title );
4168 $this->mOptions
= $options;
4169 $this->setOutputType( $outputType );
4170 if ( $clearState ) {
4171 $this->clearState();
4176 * Wrapper for preprocess()
4178 * @param string $text the text to preprocess
4179 * @param ParserOptions $options options
4183 function transformMsg( $text, $options ) {
4185 static $executing = false;
4187 # Guard against infinite recursion
4193 wfProfileIn(__METHOD__
);
4194 $text = $this->preprocess( $text, $wgTitle, $options );
4197 wfProfileOut(__METHOD__
);
4202 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4203 * The callback should have the following form:
4204 * function myParserHook( $text, $params, &$parser ) { ... }
4206 * Transform and return $text. Use $parser for any required context, e.g. use
4207 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4211 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
4212 * @param mixed $callback The callback function (and object) to use for the tag
4214 * @return The old value of the mTagHooks array associated with the hook
4216 function setHook( $tag, $callback ) {
4217 $tag = strtolower( $tag );
4218 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4219 $this->mTagHooks
[$tag] = $callback;
4220 if( !in_array( $tag, $this->mStripList
) ) {
4221 $this->mStripList
[] = $tag;
4227 function setTransparentTagHook( $tag, $callback ) {
4228 $tag = strtolower( $tag );
4229 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4230 $this->mTransparentTagHooks
[$tag] = $callback;
4236 * Remove all tag hooks
4238 function clearTagHooks() {
4239 $this->mTagHooks
= array();
4240 $this->mStripList
= $this->mDefaultStripList
;
4244 * Create a function, e.g. {{sum:1|2|3}}
4245 * The callback function should have the form:
4246 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4248 * Or with SFH_OBJECT_ARGS:
4249 * function myParserFunction( $parser, $frame, $args ) { ... }
4251 * The callback may either return the text result of the function, or an array with the text
4252 * in element 0, and a number of flags in the other elements. The names of the flags are
4253 * specified in the keys. Valid flags are:
4254 * found The text returned is valid, stop processing the template. This
4256 * nowiki Wiki markup in the return value should be escaped
4257 * isHTML The returned text is HTML, armour it against wikitext transformation
4261 * @param string $id The magic word ID
4262 * @param mixed $callback The callback function (and object) to use
4263 * @param integer $flags a combination of the following flags:
4264 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4266 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4267 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4268 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4269 * the arguments, and to control the way they are expanded.
4271 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4272 * arguments, for instance:
4273 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4275 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4276 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4277 * working if/when this is changed.
4279 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4282 * Please read the documentation in includes/parser/Preprocessor.php for more information
4283 * about the methods available in PPFrame and PPNode.
4285 * @return The old callback function for this name, if any
4287 function setFunctionHook( $id, $callback, $flags = 0 ) {
4290 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4291 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4293 # Add to function cache
4294 $mw = MagicWord
::get( $id );
4296 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4298 $synonyms = $mw->getSynonyms();
4299 $sensitive = intval( $mw->isCaseSensitive() );
4301 foreach ( $synonyms as $syn ) {
4303 if ( !$sensitive ) {
4304 $syn = $wgContLang->lc( $syn );
4307 if ( !( $flags & SFH_NO_HASH
) ) {
4310 # Remove trailing colon
4311 if ( substr( $syn, -1, 1 ) === ':' ) {
4312 $syn = substr( $syn, 0, -1 );
4314 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4320 * Get all registered function hook identifiers
4324 function getFunctionHooks() {
4325 return array_keys( $this->mFunctionHooks
);
4329 * Create a tag function, e.g. <test>some stuff</test>.
4330 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4331 * Unlike parser functions, their content is not preprocessed.
4333 function setFunctionTagHook( $tag, $callback, $flags ) {
4334 $tag = strtolower( $tag );
4335 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4336 $this->mFunctionTagHooks
[$tag] : null;
4337 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4339 if( !in_array( $tag, $this->mStripList
) ) {
4340 $this->mStripList
[] = $tag;
4347 * FIXME: update documentation. makeLinkObj() is deprecated.
4348 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4349 * Placeholders created in Skin::makeLinkObj()
4350 * Returns an array of link CSS classes, indexed by PDBK.
4352 function replaceLinkHolders( &$text, $options = 0 ) {
4353 return $this->mLinkHolders
->replace( $text );
4357 * Replace <!--LINK--> link placeholders with plain text of links
4358 * (not HTML-formatted).
4359 * @param string $text
4362 function replaceLinkHoldersText( $text ) {
4363 return $this->mLinkHolders
->replaceText( $text );
4367 * Tag hook handler for 'pre'.
4369 function renderPreTag( $text, $attribs ) {
4370 // Backwards-compatibility hack
4371 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4373 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4374 return Xml
::openElement( 'pre', $attribs ) .
4375 Xml
::escapeTagsOnly( $content ) .
4380 * Tag hook handler for 'a'. Renders a HTML <a> tag, allowing most attributes, filtering href against
4381 * allowed protocols and spam blacklist.
4383 function renderHyperlink( $text, $params, $frame = false ) {
4384 foreach ( $params as $name => $value ) {
4385 $params[ $name ] = $this->replaceVariables( $value, $frame );
4388 $whitelist = Sanitizer
::attributeWhitelist( 'a' );
4389 $params = Sanitizer
::validateAttributes( $params, $whitelist );
4391 $content = $this->recursiveTagParse( trim( $text ), $frame );
4393 if ( isset( $params[ 'href' ] ) ) {
4394 $href = $params[ 'href' ];
4395 $this->mOutput
->addExternalLink( $href );
4396 unset( $params[ 'href' ] );
4399 return Xml
::openElement( 'a', $params ) . $content . Xml
::closeElement( 'a' );
4402 $sk = $this->mOptions
->getSkin();
4403 $html = $sk->makeExternalLink( $href, $content, false, '', $params );
4409 * Renders an image gallery from a text with one line per image.
4410 * text labels may be given by using |-style alternative text. E.g.
4411 * Image:one.jpg|The number "1"
4412 * Image:tree.jpg|A tree
4413 * given as text will return the HTML of a gallery with two images,
4414 * labeled 'The number "1"' and
4417 function renderImageGallery( $text, $params ) {
4418 $ig = new ImageGallery();
4419 $ig->setContextTitle( $this->mTitle
);
4420 $ig->setShowBytes( false );
4421 $ig->setShowFilename( false );
4422 $ig->setParser( $this );
4423 $ig->setHideBadImages();
4424 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4425 $ig->useSkin( $this->mOptions
->getSkin() );
4426 $ig->mRevisionId
= $this->mRevisionId
;
4428 if( isset( $params['caption'] ) ) {
4429 $caption = $params['caption'];
4430 $caption = htmlspecialchars( $caption );
4431 $caption = $this->replaceInternalLinks( $caption );
4432 $ig->setCaptionHtml( $caption );
4434 if( isset( $params['perrow'] ) ) {
4435 $ig->setPerRow( $params['perrow'] );
4437 if( isset( $params['widths'] ) ) {
4438 $ig->setWidths( $params['widths'] );
4440 if( isset( $params['heights'] ) ) {
4441 $ig->setHeights( $params['heights'] );
4444 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4446 $lines = StringUtils
::explode( "\n", $text );
4447 foreach ( $lines as $line ) {
4448 # match lines like these:
4449 # Image:someimage.jpg|This is some image
4451 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4453 if ( count( $matches ) == 0 ) {
4457 if ( strpos( $matches[0], '%' ) !== false )
4458 $matches[1] = urldecode( $matches[1] );
4459 $tp = Title
::newFromText( $matches[1]/*, NS_FILE*/ );
4461 if( is_null( $nt ) ) {
4462 # Bogus title. Ignore these so we don't bomb out later.
4465 if ( isset( $matches[3] ) ) {
4466 $label = $matches[3];
4471 $html = $this->recursiveTagParse( trim( $label ) );
4473 $ig->add( $nt, $html );
4475 # Only add real images (bug #5586)
4476 if ( $nt->getNamespace() == NS_FILE
) {
4477 $this->mOutput
->addImage( $nt->getDBkey() );
4480 return $ig->toHTML();
4483 function getImageParams( $handler ) {
4485 $handlerClass = get_class( $handler );
4489 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4490 // Initialise static lists
4491 static $internalParamNames = array(
4492 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4493 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4494 'bottom', 'text-bottom' ),
4495 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4496 'upright', 'border', 'link', 'alt' ),
4498 static $internalParamMap;
4499 if ( !$internalParamMap ) {
4500 $internalParamMap = array();
4501 foreach ( $internalParamNames as $type => $names ) {
4502 foreach ( $names as $name ) {
4503 $magicName = str_replace( '-', '_', "img_$name" );
4504 $internalParamMap[$magicName] = array( $type, $name );
4509 // Add handler params
4510 $paramMap = $internalParamMap;
4512 $handlerParamMap = $handler->getParamMap();
4513 foreach ( $handlerParamMap as $magic => $paramName ) {
4514 $paramMap[$magic] = array( 'handler', $paramName );
4517 $this->mImageParams
[$handlerClass] = $paramMap;
4518 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4520 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4524 * Parse image options text and use it to make an image
4525 * @param Title $title
4526 * @param string $options
4527 * @param LinkHolderArray $holders
4529 function makeImage( $title, $options, $holders = false ) {
4530 # Check if the options text is of the form "options|alt text"
4532 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4533 # * left no resizing, just left align. label is used for alt= only
4534 # * right same, but right aligned
4535 # * none same, but not aligned
4536 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4537 # * center center the image
4538 # * frame Keep original image size, no magnify-button.
4539 # * framed Same as "frame"
4540 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4541 # * upright reduce width for upright images, rounded to full __0 px
4542 # * border draw a 1px border around the image
4543 # * alt Text for HTML alt attribute (defaults to empty)
4544 # * link Set the target of the image link. Can be external, interwiki, or local
4545 # vertical-align values (no % or length right now):
4555 $parts = StringUtils
::explode( "|", $options );
4556 $sk = $this->mOptions
->getSkin();
4558 # Give extensions a chance to select the file revision for us
4559 $skip = $time = $descQuery = false;
4560 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4563 return $sk->link( $title );
4567 $imagename = $title->getDBkey();
4568 $file = wfFindFile( $title, array( 'time' => $time ) );
4570 $handler = $file ?
$file->getHandler() : false;
4572 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4574 # Process the input parameters
4576 $params = array( 'frame' => array(), 'handler' => array(),
4577 'horizAlign' => array(), 'vertAlign' => array() );
4578 foreach( $parts as $part ) {
4579 $part = trim( $part );
4580 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4582 if( isset( $paramMap[$magicName] ) ) {
4583 list( $type, $paramName ) = $paramMap[$magicName];
4585 // Special case; width and height come in one variable together
4586 if( $type === 'handler' && $paramName === 'width' ) {
4588 # (bug 13500) In both cases (width/height and width only),
4589 # permit trailing "px" for backward compatibility.
4590 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4591 $width = intval( $m[1] );
4592 $height = intval( $m[2] );
4593 if ( $handler->validateParam( 'width', $width ) ) {
4594 $params[$type]['width'] = $width;
4597 if ( $handler->validateParam( 'height', $height ) ) {
4598 $params[$type]['height'] = $height;
4601 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4602 $width = intval( $value );
4603 if ( $handler->validateParam( 'width', $width ) ) {
4604 $params[$type]['width'] = $width;
4607 } // else no validation -- bug 13436
4609 if ( $type === 'handler' ) {
4610 # Validate handler parameter
4611 $validated = $handler->validateParam( $paramName, $value );
4613 # Validate internal parameters
4614 switch( $paramName ) {
4617 // @todo Fixme: possibly check validity here for
4618 // manualthumb? downstream behavior seems odd with
4619 // missing manual thumbs.
4621 $value = $this->stripAltText( $value, $holders );
4624 $chars = self
::EXT_LINK_URL_CLASS
;
4625 $prots = $this->mUrlProtocols
;
4626 if ( $value === '' ) {
4627 $paramName = 'no-link';
4630 } elseif ( preg_match( "/^$prots/", $value ) ) {
4631 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4632 $paramName = 'link-url';
4633 $this->mOutput
->addExternalLink( $value );
4637 $linkTitle = Title
::newFromText( $value );
4639 $paramName = 'link-title';
4640 $value = $linkTitle;
4641 $this->mOutput
->addLink( $linkTitle );
4647 // Most other things appear to be empty or numeric...
4648 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4653 $params[$type][$paramName] = $value;
4657 if ( !$validated ) {
4662 # Process alignment parameters
4663 if ( $params['horizAlign'] ) {
4664 $params['frame']['align'] = key( $params['horizAlign'] );
4666 if ( $params['vertAlign'] ) {
4667 $params['frame']['valign'] = key( $params['vertAlign'] );
4670 $params['frame']['caption'] = $caption;
4672 # Will the image be presented in a frame, with the caption below?
4673 $imageIsFramed = isset( $params['frame']['frame'] ) ||
4674 isset( $params['frame']['framed'] ) ||
4675 isset( $params['frame']['thumbnail'] ) ||
4676 isset( $params['frame']['manualthumb'] );
4678 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4679 # came to also set the caption, ordinary text after the image -- which
4680 # makes no sense, because that just repeats the text multiple times in
4681 # screen readers. It *also* came to set the title attribute.
4683 # Now that we have an alt attribute, we should not set the alt text to
4684 # equal the caption: that's worse than useless, it just repeats the
4685 # text. This is the framed/thumbnail case. If there's no caption, we
4686 # use the unnamed parameter for alt text as well, just for the time be-
4687 # ing, if the unnamed param is set and the alt param is not.
4689 # For the future, we need to figure out if we want to tweak this more,
4690 # e.g., introducing a title= parameter for the title; ignoring the un-
4691 # named parameter entirely for images without a caption; adding an ex-
4692 # plicit caption= parameter and preserving the old magic unnamed para-
4694 if ( $imageIsFramed ) { # Framed image
4695 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
4696 # No caption or alt text, add the filename as the alt text so
4697 # that screen readers at least get some description of the image
4698 $params['frame']['alt'] = $title->getText();
4700 # Do not set $params['frame']['title'] because tooltips don't make sense
4702 } else { # Inline image
4703 if ( !isset( $params['frame']['alt'] ) ) {
4704 # No alt text, use the "caption" for the alt text
4705 if ( $caption !== '') {
4706 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
4708 # No caption, fall back to using the filename for the
4710 $params['frame']['alt'] = $title->getText();
4713 # Use the "caption" for the tooltip text
4714 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4717 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4719 # Linker does the rest
4720 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4722 # Give the handler a chance to modify the parser object
4724 $handler->parserTransformHook( $this, $file );
4730 protected function stripAltText( $caption, $holders ) {
4731 # Strip bad stuff out of the title (tooltip). We can't just use
4732 # replaceLinkHoldersText() here, because if this function is called
4733 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4735 $tooltip = $holders->replaceText( $caption );
4737 $tooltip = $this->replaceLinkHoldersText( $caption );
4740 # make sure there are no placeholders in thumbnail attributes
4741 # that are later expanded to html- so expand them now and
4743 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
4744 $tooltip = Sanitizer
::stripAllTags( $tooltip );
4750 * Set a flag in the output object indicating that the content is dynamic and
4751 * shouldn't be cached.
4753 function disableCache() {
4754 wfDebug( "Parser output marked as uncacheable.\n" );
4755 $this->mOutput
->mCacheTime
= -1;
4759 * Callback from the Sanitizer for expanding items found in HTML attribute
4760 * values, so they can be safely tested and escaped.
4761 * @param string $text
4762 * @param PPFrame $frame
4766 function attributeStripCallback( &$text, $frame = false ) {
4767 $text = $this->replaceVariables( $text, $frame );
4768 $text = $this->mStripState
->unstripBoth( $text );
4777 function Title( $x = null ) { return wfSetVar( $this->mTitle
, $x ); }
4778 function Options( $x = null ) { return wfSetVar( $this->mOptions
, $x ); }
4779 function OutputType( $x = null ) { return wfSetVar( $this->mOutputType
, $x ); }
4785 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4790 * Break wikitext input into sections, and either pull or replace
4791 * some particular section's text.
4793 * External callers should use the getSection and replaceSection methods.
4795 * @param string $text Page wikitext
4796 * @param string $section A section identifier string of the form:
4797 * <flag1> - <flag2> - ... - <section number>
4799 * Currently the only recognised flag is "T", which means the target section number
4800 * was derived during a template inclusion parse, in other words this is a template
4801 * section edit link. If no flags are given, it was an ordinary section edit link.
4802 * This flag is required to avoid a section numbering mismatch when a section is
4803 * enclosed by <includeonly> (bug 6563).
4805 * The section number 0 pulls the text before the first heading; other numbers will
4806 * pull the given section along with its lower-level subsections. If the section is
4807 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4809 * @param string $mode One of "get" or "replace"
4810 * @param string $newText Replacement text for section data.
4811 * @return string for "get", the extracted section text.
4812 * for "replace", the whole page with the section replaced.
4814 private function extractSections( $text, $section, $mode, $newText='' ) {
4816 $this->clearState();
4817 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4818 $this->mOptions
= new ParserOptions
;
4819 $this->setOutputType( self
::OT_WIKI
);
4821 $frame = $this->getPreprocessor()->newFrame();
4823 // Process section extraction flags
4825 $sectionParts = explode( '-', $section );
4826 $sectionIndex = array_pop( $sectionParts );
4827 foreach ( $sectionParts as $part ) {
4828 if ( $part === 'T' ) {
4829 $flags |
= self
::PTD_FOR_INCLUSION
;
4832 // Preprocess the text
4833 $root = $this->preprocessToDom( $text, $flags );
4835 // <h> nodes indicate section breaks
4836 // They can only occur at the top level, so we can find them by iterating the root's children
4837 $node = $root->getFirstChild();
4839 // Find the target section
4840 if ( $sectionIndex == 0 ) {
4841 // Section zero doesn't nest, level=big
4842 $targetLevel = 1000;
4845 if ( $node->getName() === 'h' ) {
4846 $bits = $node->splitHeading();
4847 if ( $bits['i'] == $sectionIndex ) {
4848 $targetLevel = $bits['level'];
4852 if ( $mode === 'replace' ) {
4853 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4855 $node = $node->getNextSibling();
4861 if ( $mode === 'get' ) {
4868 // Find the end of the section, including nested sections
4870 if ( $node->getName() === 'h' ) {
4871 $bits = $node->splitHeading();
4872 $curLevel = $bits['level'];
4873 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4877 if ( $mode === 'get' ) {
4878 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4880 $node = $node->getNextSibling();
4883 // Write out the remainder (in replace mode only)
4884 if ( $mode === 'replace' ) {
4885 // Output the replacement text
4886 // Add two newlines on -- trailing whitespace in $newText is conventionally
4887 // stripped by the editor, so we need both newlines to restore the paragraph gap
4888 // Only add trailing whitespace if there is newText
4889 if($newText != "") {
4890 $outText .= $newText . "\n\n";
4894 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4895 $node = $node->getNextSibling();
4899 if ( is_string( $outText ) ) {
4900 // Re-insert stripped tags
4901 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4908 * This function returns the text of a section, specified by a number ($section).
4909 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4910 * the first section before any such heading (section 0).
4912 * If a section contains subsections, these are also returned.
4914 * @param string $text text to look in
4915 * @param string $section section identifier
4916 * @param string $deftext default to return if section is not found
4917 * @return string text of the requested section
4919 public function getSection( $text, $section, $deftext='' ) {
4920 return $this->extractSections( $text, $section, "get", $deftext );
4923 public function replaceSection( $oldtext, $section, $text ) {
4924 return $this->extractSections( $oldtext, $section, "replace", $text );
4928 * Get the timestamp associated with the current revision, adjusted for
4929 * the default server-local timestamp
4931 function getRevisionTimestamp() {
4932 if ( is_null( $this->mRevisionTimestamp
) ) {
4933 wfProfileIn( __METHOD__
);
4935 $dbr = wfGetDB( DB_SLAVE
);
4936 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4937 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4939 // Normalize timestamp to internal MW format for timezone processing.
4940 // This has the added side-effect of replacing a null value with
4941 // the current time, which gives us more sensible behavior for
4943 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4945 // The cryptic '' timezone parameter tells to use the site-default
4946 // timezone offset instead of the user settings.
4948 // Since this value will be saved into the parser cache, served
4949 // to other users, and potentially even used inside links and such,
4950 // it needs to be consistent for all visitors.
4951 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4953 wfProfileOut( __METHOD__
);
4955 return $this->mRevisionTimestamp
;
4959 * Get the name of the user that edited the last revision
4961 function getRevisionUser() {
4962 // if this template is subst: the revision id will be blank,
4963 // so just use the current user's name
4964 if( $this->mRevisionId
) {
4965 $revision = Revision
::newFromId( $this->mRevisionId
);
4966 $revuser = $revision->getUserText();
4969 $revuser = $wgUser->getName();
4975 * Mutator for $mDefaultSort
4977 * @param $sort New value
4979 public function setDefaultSort( $sort ) {
4980 $this->mDefaultSort
= $sort;
4984 * Accessor for $mDefaultSort
4985 * Will use the title/prefixed title if none is set
4989 public function getDefaultSort() {
4990 global $wgCategoryPrefixedDefaultSortkey;
4991 if( $this->mDefaultSort
!== false ) {
4992 return $this->mDefaultSort
;
4993 } elseif ($this->mTitle
->getNamespace() == NS_CATEGORY ||
4994 !$wgCategoryPrefixedDefaultSortkey) {
4995 return $this->mTitle
->getText();
4997 return $this->mTitle
->getPrefixedText();
5002 * Accessor for $mDefaultSort
5003 * Unlike getDefaultSort(), will return false if none is set
5005 * @return string or false
5007 public function getCustomDefaultSort() {
5008 return $this->mDefaultSort
;
5012 * Try to guess the section anchor name based on a wikitext fragment
5013 * presumably extracted from a heading, for example "Header" from
5016 public function guessSectionNameFromWikiText( $text ) {
5017 # Strip out wikitext links(they break the anchor)
5018 $text = $this->stripSectionName( $text );
5019 $headline = Sanitizer
::decodeCharReferences( $text );
5021 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
5022 $headline = trim( $headline );
5023 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
5024 $replacearray = array(
5029 array_keys( $replacearray ),
5030 array_values( $replacearray ),
5035 * Strips a text string of wikitext for use in a section anchor
5037 * Accepts a text string and then removes all wikitext from the
5038 * string and leaves only the resultant text (i.e. the result of
5039 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5040 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5041 * to create valid section anchors by mimicing the output of the
5042 * parser when headings are parsed.
5044 * @param $text string Text string to be stripped of wikitext
5045 * for use in a Section anchor
5046 * @return Filtered text string
5048 public function stripSectionName( $text ) {
5049 # Strip internal link markup
5050 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
5051 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
5053 # Strip external link markup (FIXME: Not Tolerant to blank link text
5054 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5055 # on how many empty links there are on the page - need to figure that out.
5056 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
5058 # Parse wikitext quotes (italics & bold)
5059 $text = $this->doQuotes($text);
5062 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5066 function srvus( $text ) {
5067 return $this->testSrvus( $text, $this->mOutputType
);
5071 * strip/replaceVariables/unstrip for preprocessor regression testing
5073 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
5074 $this->clearState();
5075 if ( ! ( $title instanceof Title
) ) {
5076 $title = Title
::newFromText( $title );
5078 $this->mTitle
= $title;
5079 $this->mOptions
= $options;
5080 $this->setOutputType( $outputType );
5081 $text = $this->replaceVariables( $text );
5082 $text = $this->mStripState
->unstripBoth( $text );
5083 $text = Sanitizer
::removeHTMLtags( $text );
5087 function testPst( $text, $title, $options ) {
5089 if ( ! ( $title instanceof Title
) ) {
5090 $title = Title
::newFromText( $title );
5092 return $this->preSaveTransform( $text, $title, $wgUser, $options );
5095 function testPreprocess( $text, $title, $options ) {
5096 if ( ! ( $title instanceof Title
) ) {
5097 $title = Title
::newFromText( $title );
5099 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5102 function markerSkipCallback( $s, $callback ) {
5105 while ( $i < strlen( $s ) ) {
5106 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5107 if ( $markerStart === false ) {
5108 $out .= call_user_func( $callback, substr( $s, $i ) );
5111 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5112 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5113 if ( $markerEnd === false ) {
5114 $out .= substr( $s, $markerStart );
5117 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5118 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5126 function serialiseHalfParsedText( $text ) {
5128 $data['text'] = $text;
5130 // First, find all strip markers, and store their
5131 // data in an array.
5132 $stripState = new StripState
;
5134 while( ( $start_pos = strpos( $text, $this->mUniqPrefix
, $pos ) ) && ( $end_pos = strpos( $text, self
::MARKER_SUFFIX
, $pos ) ) ) {
5135 $end_pos +
= strlen( self
::MARKER_SUFFIX
);
5136 $marker = substr( $text, $start_pos, $end_pos-$start_pos );
5138 if ( !empty( $this->mStripState
->general
->data
[$marker] ) ) {
5139 $replaceArray = $stripState->general
;
5140 $stripText = $this->mStripState
->general
->data
[$marker];
5141 } elseif ( !empty( $this->mStripState
->nowiki
->data
[$marker] ) ) {
5142 $replaceArray = $stripState->nowiki
;
5143 $stripText = $this->mStripState
->nowiki
->data
[$marker];
5145 throw new MWException( "Hanging strip marker: '$marker'." );
5148 $replaceArray->setPair( $marker, $stripText );
5151 $data['stripstate'] = $stripState;
5153 // Now, find all of our links, and store THEIR
5154 // data in an array! :)
5155 $links = array( 'internal' => array(), 'interwiki' => array() );
5159 while( ( $start_pos = strpos( $text, '<!--LINK ', $pos ) ) ) {
5160 list( $ns, $trail ) = explode( ':', substr( $text, $start_pos +
strlen( '<!--LINK ' ) ), 2 );
5163 if (empty( $links['internal'][$ns] )) {
5164 $links['internal'][$ns] = array();
5167 $key = trim( substr( $trail, 0, strpos( $trail, '-->' ) ) );
5168 $links['internal'][$ns][] = $this->mLinkHolders
->internals
[$ns][$key];
5169 $pos = $start_pos +
strlen( "<!--LINK $ns:$key-->" );
5175 while( ( $start_pos = strpos( $text, '<!--IWLINK ', $pos ) ) ) {
5176 $data = substr( $text, $start_pos );
5177 $key = trim( substr( $data, 0, strpos( $data, '-->' ) ) );
5178 $links['interwiki'][] = $this->mLinkHolders
->interwiki
[$key];
5179 $pos = $start_pos +
strlen( "<!--IWLINK $key-->" );
5182 $data['linkholder'] = $links;
5187 function unserialiseHalfParsedText( $data, $intPrefix = null /* Unique identifying prefix */ ) {
5189 $intPrefix = $this->getRandomString();
5191 // First, extract the strip state.
5192 $stripState = $data['stripstate'];
5193 $this->mStripState
->general
->merge( $stripState->general
);
5194 $this->mStripState
->nowiki
->merge( $stripState->nowiki
);
5196 // Now, extract the text, and renumber links
5197 $text = $data['text'];
5198 $links = $data['linkholder'];
5201 foreach( $links['internal'] as $ns => $nsLinks ) {
5202 foreach( $nsLinks as $key => $entry ) {
5203 $newKey = $intPrefix . '-' . $key;
5204 $this->mLinkHolders
->internals
[$ns][$newKey] = $entry;
5206 $text = str_replace( "<!--LINK $ns:$key-->", "<!--LINK $ns:$newKey-->", $text );
5211 foreach( $links['interwiki'] as $key => $entry ) {
5212 $newKey = "$intPrefix-$key";
5213 $this->mLinkHolders
->interwikis
[$newKey] = $entry;
5215 $text = str_replace( "<!--IWLINK $key-->", "<!--IWLINK $newKey-->", $text );
5218 // Should be good to go.
5224 * @todo document, briefly.
5228 var $general, $nowiki;
5230 function __construct() {
5231 $this->general
= new ReplacementArray
;
5232 $this->nowiki
= new ReplacementArray
;
5235 function unstripGeneral( $text ) {
5236 wfProfileIn( __METHOD__
);
5239 $text = $this->general
->replace( $text );
5240 } while ( $text !== $oldText );
5241 wfProfileOut( __METHOD__
);
5245 function unstripNoWiki( $text ) {
5246 wfProfileIn( __METHOD__
);
5249 $text = $this->nowiki
->replace( $text );
5250 } while ( $text !== $oldText );
5251 wfProfileOut( __METHOD__
);
5255 function unstripBoth( $text ) {
5256 wfProfileIn( __METHOD__
);
5259 $text = $this->general
->replace( $text );
5260 $text = $this->nowiki
->replace( $text );
5261 } while ( $text !== $oldText );
5262 wfProfileOut( __METHOD__
);
5268 * @todo document, briefly.
5271 class OnlyIncludeReplacer
{
5274 function replace( $matches ) {
5275 if ( substr( $matches[1], -1 ) === "\n" ) {
5276 $this->output
.= substr( $matches[1], 0, -1 );
5278 $this->output
.= $matches[1];