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 ( !$t ||
$t instanceof FakeTitle
) {
262 $t = Title
::newFromText( 'NO TITLE' );
264 if ( strval( $t->getFragment() ) !== '' ) {
265 # Strip the fragment to avoid various odd effects
266 $this->mTitle
= clone $t;
267 $this->mTitle
->setFragment( '' );
274 * Accessor for mUniqPrefix.
278 function uniqPrefix() {
279 if( !isset( $this->mUniqPrefix
) ) {
280 // @todo Fixme: this is probably *horribly wrong*
281 // LanguageConverter seems to want $wgParser's uniqPrefix, however
282 // if this is called for a parser cache hit, the parser may not
283 // have ever been initialized in the first place.
284 // Not really sure what the heck is supposed to be going on here.
286 //throw new MWException( "Accessing uninitialized mUniqPrefix" );
288 return $this->mUniqPrefix
;
292 * Convert wikitext to HTML
293 * Do not call this function recursively.
295 * @param $text String: text we want to parse
296 * @param $title A title object
297 * @param $options ParserOptions
298 * @param $linestart boolean
299 * @param $clearState boolean
300 * @param $revid Int: number to pass in {{REVISIONID}}
301 * @return ParserOutput a ParserOutput
303 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
305 * First pass--just handle <nowiki> sections, pass the rest off
306 * to internalParse() which does all the real work.
309 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang;
310 $fname = __METHOD__
.'-' . wfGetCaller();
311 wfProfileIn( __METHOD__
);
312 wfProfileIn( $fname );
318 $this->mOptions
= $options;
319 $this->setTitle( $title ); // Page title has to be set for the pre-processor
321 $oldRevisionId = $this->mRevisionId
;
322 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
323 if( $revid !== null ) {
324 $this->mRevisionId
= $revid;
325 $this->mRevisionTimestamp
= null;
327 $this->setOutputType( self
::OT_HTML
);
328 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
330 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
331 $text = $this->internalParse( $text );
332 // internalParse took care of the notitleconvert bit, so title conversion is here.
333 if ( $this->mDoTitleConvert
&& !$this->mTitle
->isConversionTable()) {
334 $converted = $wgContLang->convert( $title );
335 if ( !$converted instanceOf Title
) {
336 $converted = Title
::newFromText( $converted );
338 $this->setTitle( $converted );
341 $text = $this->mStripState
->unstripGeneral( $text );
343 # Clean up special characters, only run once, next-to-last before doBlockLevels
345 # french spaces, last one Guillemet-left
346 # only if there is something before the space
347 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
348 # french spaces, Guillemet-right
349 '/(\\302\\253) /' => '\\1 ',
350 '/ (!\s*important)/' => ' \\1', #Beware of CSS magic word !important, bug #11874.
352 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
354 $text = $this->doBlockLevels( $text, $linestart );
356 $this->replaceLinkHolders( $text );
358 # the position of the convert() call should not be changed. it
359 # assumes that the links are all replaced and the only thing left
360 # is the <nowiki> mark.
361 if ( $this->mDoContentConvert
&& !$this->mTitle
->isConversionTable()) {
362 $text = $wgContLang->convert( $text );
365 $text = $this->mStripState
->unstripNoWiki( $text );
367 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
369 //!JF Move to its own function
371 $uniq_prefix = $this->mUniqPrefix
;
373 $elements = array_keys( $this->mTransparentTagHooks
);
374 $text = self
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
376 foreach( $matches as $marker => $data ) {
377 list( $element, $content, $params, $tag ) = $data;
378 $tagName = strtolower( $element );
379 if( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
380 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName],
381 array( $content, $params, $this ) );
385 $this->mStripState
->general
->setPair( $marker, $output );
387 $text = $this->mStripState
->unstripGeneral( $text );
389 $text = Sanitizer
::normalizeCharReferences( $text );
391 if ( ( $wgUseTidy && $this->mOptions
->mTidy
) ||
$wgAlwaysUseTidy ) {
392 $text = MWTidy
::tidy( $text );
394 # attempt to sanitize at least some nesting problems
395 # (bug #2702 and quite a few others)
397 # ''Something [http://www.cool.com cool''] -->
398 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
399 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
400 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
401 # fix up an anchor inside another anchor, only
402 # at least for a single single nested link (bug 3695)
403 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
404 '\\1\\2</a>\\3</a>\\1\\4</a>',
405 # fix div inside inline elements- doBlockLevels won't wrap a line which
406 # contains a div, so fix it up here; replace
407 # div with escaped text
408 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
409 '\\1\\3<div\\5>\\6</div>\\8\\9',
410 # remove empty italic or bold tag pairs, some
411 # introduced by rules above
412 '/<([bi])><\/\\1>/' => '',
415 $text = preg_replace(
416 array_keys( $tidyregs ),
417 array_values( $tidyregs ),
420 global $wgExpensiveParserFunctionLimit;
421 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
422 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
425 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
427 # Information on include size limits, for the benefit of users who try to skirt them
428 if ( $this->mOptions
->getEnableLimitReport() ) {
429 global $wgExpensiveParserFunctionLimit;
430 $max = $this->mOptions
->getMaxIncludeSize();
431 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
433 "NewPP limit report\n" .
434 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
435 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
436 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
438 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
439 $text .= "\n<!-- \n$limitReport-->\n";
441 $this->mOutput
->setText( $text );
442 $this->mRevisionId
= $oldRevisionId;
443 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
444 wfProfileOut( $fname );
445 wfProfileOut( __METHOD__
);
447 return $this->mOutput
;
451 * Recursive parser entry point that can be called from an extension tag
454 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
456 * @param $text String: text extension wants to have parsed
457 * @param PPFrame $frame: The frame to use for expanding any template variables
459 function recursiveTagParse( $text, $frame=false ) {
460 wfProfileIn( __METHOD__
);
461 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
462 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
463 $text = $this->internalParse( $text, false, $frame );
464 wfProfileOut( __METHOD__
);
469 * Expand templates and variables in the text, producing valid, static wikitext.
470 * Also removes comments.
472 function preprocess( $text, $title, $options, $revid = null ) {
473 wfProfileIn( __METHOD__
);
475 $this->setOutputType( self
::OT_PREPROCESS
);
476 $this->mOptions
= $options;
477 $this->setTitle( $title );
478 if( $revid !== null ) {
479 $this->mRevisionId
= $revid;
481 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
482 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
483 $text = $this->replaceVariables( $text );
484 $text = $this->mStripState
->unstripBoth( $text );
485 wfProfileOut( __METHOD__
);
490 * Get a random string
495 function getRandomString() {
496 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
499 function &getTitle() { return $this->mTitle
; }
500 function getOptions() { return $this->mOptions
; }
501 function getRevisionId() { return $this->mRevisionId
; }
502 function getOutput() { return $this->mOutput
; }
503 function nextLinkID() { return $this->mLinkID++
; }
505 function getFunctionLang() {
506 global $wgLang, $wgContLang;
508 $target = $this->mOptions
->getTargetLanguage();
509 if ( $target !== null ) {
512 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
517 * Get a preprocessor object
519 function getPreprocessor() {
520 if ( !isset( $this->mPreprocessor
) ) {
521 $class = $this->mPreprocessorClass
;
522 $this->mPreprocessor
= new $class( $this );
524 return $this->mPreprocessor
;
528 * Replaces all occurrences of HTML-style comments and the given tags
529 * in the text with a random marker and returns the next text. The output
530 * parameter $matches will be an associative array filled with data in
532 * 'UNIQ-xxxxx' => array(
535 * array( 'param' => 'x' ),
536 * '<element param="x">tag content</element>' ) )
538 * @param $elements list of element names. Comments are always extracted.
539 * @param $text Source text string.
540 * @param $uniq_prefix
545 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
550 $taglist = implode( '|', $elements );
551 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
553 while ( $text != '' ) {
554 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
556 if( count( $p ) < 5 ) {
559 if( count( $p ) > 5 ) {
573 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . self
::MARKER_SUFFIX
;
574 $stripped .= $marker;
576 if ( $close === '/>' ) {
577 // Empty element tag, <tag />
582 if( $element === '!--' ) {
585 $end = "/(<\\/$element\\s*>)/i";
587 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
589 if( count( $q ) < 3 ) {
590 # No end tag -- let it run out to the end of the text.
599 $matches[$marker] = array( $element,
601 Sanitizer
::decodeTagAttributes( $attributes ),
602 "<$element$attributes$close$content$tail" );
608 * Get a list of strippable XML-like elements
610 function getStripList() {
612 $elements = $this->mStripList
;
614 $elements[] = 'html';
616 if( $this->mOptions
->getUseTeX() ) {
617 $elements[] = 'math';
623 * @deprecated use replaceVariables
625 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
630 * Restores pre, math, and other extensions removed by strip()
632 * always call unstripNoWiki() after this one
634 * @deprecated use $this->mStripState->unstrip()
636 function unstrip( $text, $state ) {
637 return $state->unstripGeneral( $text );
641 * Always call this after unstrip() to preserve the order
644 * @deprecated use $this->mStripState->unstrip()
646 function unstripNoWiki( $text, $state ) {
647 return $state->unstripNoWiki( $text );
651 * @deprecated use $this->mStripState->unstripBoth()
653 function unstripForHTML( $text ) {
654 return $this->mStripState
->unstripBoth( $text );
658 * Add an item to the strip state
659 * Returns the unique tag which must be inserted into the stripped text
660 * The tag will be replaced with the original text in unstrip()
664 function insertStripItem( $text ) {
665 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
666 $this->mMarkerIndex++
;
667 $this->mStripState
->general
->setPair( $rnd, $text );
672 * Interface with html tidy
673 * @deprecated Use MWTidy::tidy()
675 public static function tidy( $text ) {
676 wfDeprecated( __METHOD__
);
677 return MWTidy
::tidy( $text );
681 * parse the wiki syntax used to render tables
685 function doTableStuff ( $text ) {
686 wfProfileIn( __METHOD__
);
688 $lines = StringUtils
::explode( "\n", $text );
690 $td_history = array (); // Is currently a td tag open?
691 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
692 $tr_history = array (); // Is currently a tr tag open?
693 $tr_attributes = array (); // history of tr attributes
694 $has_opened_tr = array(); // Did this table open a <tr> element?
695 $indent_level = 0; // indent level of the table
697 foreach ( $lines as $outLine ) {
698 $line = trim( $outLine );
700 if( $line == '' ) { // empty line, go to next line
701 $out .= $outLine."\n";
704 $first_character = $line[0];
707 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
708 // First check if we are starting a new table
709 $indent_level = strlen( $matches[1] );
711 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
712 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
714 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
715 array_push ( $td_history , false );
716 array_push ( $last_tag_history , '' );
717 array_push ( $tr_history , false );
718 array_push ( $tr_attributes , '' );
719 array_push ( $has_opened_tr , false );
720 } else if ( count ( $td_history ) == 0 ) {
721 // Don't do any of the following
722 $out .= $outLine."\n";
724 } else if ( substr ( $line , 0 , 2 ) === '|}' ) {
725 // We are ending a table
726 $line = '</table>' . substr ( $line , 2 );
727 $last_tag = array_pop ( $last_tag_history );
729 if ( !array_pop ( $has_opened_tr ) ) {
730 $line = "<tr><td></td></tr>{$line}";
733 if ( array_pop ( $tr_history ) ) {
734 $line = "</tr>{$line}";
737 if ( array_pop ( $td_history ) ) {
738 $line = "</{$last_tag}>{$line}";
740 array_pop ( $tr_attributes );
741 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
742 } else if ( substr ( $line , 0 , 2 ) === '|-' ) {
743 // Now we have a table row
744 $line = preg_replace( '#^\|-+#', '', $line );
746 // Whats after the tag is now only attributes
747 $attributes = $this->mStripState
->unstripBoth( $line );
748 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'tr' );
749 array_pop ( $tr_attributes );
750 array_push ( $tr_attributes , $attributes );
753 $last_tag = array_pop ( $last_tag_history );
754 array_pop ( $has_opened_tr );
755 array_push ( $has_opened_tr , true );
757 if ( array_pop ( $tr_history ) ) {
761 if ( array_pop ( $td_history ) ) {
762 $line = "</{$last_tag}>{$line}";
766 array_push ( $tr_history , false );
767 array_push ( $td_history , false );
768 array_push ( $last_tag_history , '' );
770 else if ( $first_character === '|' ||
$first_character === '!' ||
substr ( $line , 0 , 2 ) === '|+' ) {
771 // This might be cell elements, td, th or captions
772 if ( substr ( $line , 0 , 2 ) === '|+' ) {
773 $first_character = '+';
774 $line = substr ( $line , 1 );
777 $line = substr ( $line , 1 );
779 if ( $first_character === '!' ) {
780 $line = str_replace ( '!!' , '||' , $line );
783 // Split up multiple cells on the same line.
784 // FIXME : This can result in improper nesting of tags processed
785 // by earlier parser steps, but should avoid splitting up eg
786 // attribute values containing literal "||".
787 $cells = StringUtils
::explodeMarkup( '||' , $line );
791 // Loop through each table cell
792 foreach ( $cells as $cell )
795 if ( $first_character !== '+' )
797 $tr_after = array_pop ( $tr_attributes );
798 if ( !array_pop ( $tr_history ) ) {
799 $previous = "<tr{$tr_after}>\n";
801 array_push ( $tr_history , true );
802 array_push ( $tr_attributes , '' );
803 array_pop ( $has_opened_tr );
804 array_push ( $has_opened_tr , true );
807 $last_tag = array_pop ( $last_tag_history );
809 if ( array_pop ( $td_history ) ) {
810 $previous = "</{$last_tag}>{$previous}";
813 if ( $first_character === '|' ) {
815 } else if ( $first_character === '!' ) {
817 } else if ( $first_character === '+' ) {
818 $last_tag = 'caption';
823 array_push ( $last_tag_history , $last_tag );
825 // A cell could contain both parameters and data
826 $cell_data = explode ( '|' , $cell , 2 );
828 // Bug 553: Note that a '|' inside an invalid link should not
829 // be mistaken as delimiting cell parameters
830 if ( strpos( $cell_data[0], '[[' ) !== false ) {
831 $cell = "{$previous}<{$last_tag}>{$cell}";
832 } else if ( count ( $cell_data ) == 1 )
833 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
835 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
836 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
837 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
841 array_push ( $td_history , true );
844 $out .= $outLine . "\n";
847 // Closing open td, tr && table
848 while ( count ( $td_history ) > 0 )
850 if ( array_pop ( $td_history ) ) {
853 if ( array_pop ( $tr_history ) ) {
856 if ( !array_pop ( $has_opened_tr ) ) {
857 $out .= "<tr><td></td></tr>\n" ;
860 $out .= "</table>\n";
863 // Remove trailing line-ending (b/c)
864 if ( substr( $out, -1 ) === "\n" ) {
865 $out = substr( $out, 0, -1 );
868 // special case: don't return empty table
869 if( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
873 wfProfileOut( __METHOD__
);
879 * Helper function for parse() that transforms wiki markup into
880 * HTML. Only called for $mOutputType == self::OT_HTML.
884 function internalParse( $text, $isMain = true, $frame=false ) {
885 wfProfileIn( __METHOD__
);
889 # Hook to suspend the parser in this state
890 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
891 wfProfileOut( __METHOD__
);
895 // if $frame is provided, then use $frame for replacing any variables
897 // use frame depth to infer how include/noinclude tags should be handled
898 // depth=0 means this is the top-level document; otherwise it's an included document
902 $flag = Parser
::PTD_FOR_INCLUSION
;
903 $dom = $this->preprocessToDom( $text, $flag );
904 $text = $frame->expand( $dom );
906 // if $frame is not provided, then use old-style replaceVariables
908 $text = $this->replaceVariables( $text );
911 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
912 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
914 // Tables need to come after variable replacement for things to work
915 // properly; putting them before other transformations should keep
916 // exciting things like link expansions from showing up in surprising
918 $text = $this->doTableStuff( $text );
920 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
922 $text = $this->doDoubleUnderscore( $text );
924 $text = $this->doHeadings( $text );
925 if( $this->mOptions
->getUseDynamicDates() ) {
926 $df = DateFormatter
::getInstance();
927 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
929 $text = $this->doAllQuotes( $text );
930 $text = $this->replaceInternalLinks( $text );
931 $text = $this->replaceExternalLinks( $text );
933 # replaceInternalLinks may sometimes leave behind
934 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
935 $text = str_replace($this->mUniqPrefix
.'NOPARSE', '', $text);
937 $text = $this->doMagicLinks( $text );
938 $text = $this->formatHeadings( $text, $origText, $isMain );
940 wfProfileOut( __METHOD__
);
945 * Replace special strings like "ISBN xxx" and "RFC xxx" with
946 * magic external links.
951 function doMagicLinks( $text ) {
952 wfProfileIn( __METHOD__
);
953 $prots = $this->mUrlProtocols
;
954 $urlChar = self
::EXT_LINK_URL_CLASS
;
955 $text = preg_replace_callback(
957 (<a.*?</a>) | # m[1]: Skip link text
958 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
959 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
960 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
961 ISBN\s+(\b # m[5]: ISBN, capture number
962 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
963 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
964 [0-9Xx] # check digit
966 )!x', array( &$this, 'magicLinkCallback' ), $text );
967 wfProfileOut( __METHOD__
);
971 function magicLinkCallback( $m ) {
972 if ( isset( $m[1] ) && $m[1] !== '' ) {
975 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
978 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
980 return $this->makeFreeExternalLink( $m[0] );
981 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
984 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
987 $CssClass = 'mw-magiclink-rfc';
989 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
991 $urlmsg = 'pubmedurl';
992 $CssClass = 'mw-magiclink-pmid';
995 throw new MWException( __METHOD__
.': unrecognised match type "' .
996 substr($m[0], 0, 20 ) . '"' );
998 $url = wfMsg( $urlmsg, $id);
999 $sk = $this->mOptions
->getSkin();
1000 $la = $sk->getExternalLinkAttributes( "external $CssClass" );
1001 return "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1002 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1005 $num = strtr( $isbn, array(
1010 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1012 $titleObj->escapeLocalUrl() .
1013 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1020 * Make a free external link, given a user-supplied URL
1024 function makeFreeExternalLink( $url ) {
1026 wfProfileIn( __METHOD__
);
1028 $sk = $this->mOptions
->getSkin();
1031 # The characters '<' and '>' (which were escaped by
1032 # removeHTMLtags()) should not be included in
1033 # URLs, per RFC 2396.
1035 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1036 $trail = substr($url, $m2[0][1]) . $trail;
1037 $url = substr($url, 0, $m2[0][1]);
1040 # Move trailing punctuation to $trail
1042 # If there is no left bracket, then consider right brackets fair game too
1043 if ( strpos( $url, '(' ) === false ) {
1047 $numSepChars = strspn( strrev( $url ), $sep );
1048 if ( $numSepChars ) {
1049 $trail = substr( $url, -$numSepChars ) . $trail;
1050 $url = substr( $url, 0, -$numSepChars );
1053 $url = Sanitizer
::cleanUrl( $url );
1055 # Is this an external image?
1056 $text = $this->maybeMakeExternalImage( $url );
1057 if ( $text === false ) {
1058 # Not an image, make a link
1059 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1060 $this->getExternalLinkAttribs( $url ) );
1061 # Register it in the output object...
1062 # Replace unnecessary URL escape codes with their equivalent characters
1063 $pasteurized = self
::replaceUnusualEscapes( $url );
1064 $this->mOutput
->addExternalLink( $pasteurized );
1066 wfProfileOut( __METHOD__
);
1067 return $text . $trail;
1072 * Parse headers and return html
1076 function doHeadings( $text ) {
1077 wfProfileIn( __METHOD__
);
1078 for ( $i = 6; $i >= 1; --$i ) {
1079 $h = str_repeat( '=', $i );
1080 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1081 "<h$i>\\1</h$i>", $text );
1083 wfProfileOut( __METHOD__
);
1088 * Replace single quotes with HTML markup
1090 * @return string the altered text
1092 function doAllQuotes( $text ) {
1093 wfProfileIn( __METHOD__
);
1095 $lines = StringUtils
::explode( "\n", $text );
1096 foreach ( $lines as $line ) {
1097 $outtext .= $this->doQuotes( $line ) . "\n";
1099 $outtext = substr($outtext, 0,-1);
1100 wfProfileOut( __METHOD__
);
1105 * Helper function for doAllQuotes()
1107 public function doQuotes( $text ) {
1108 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1109 if ( count( $arr ) == 1 )
1113 # First, do some preliminary work. This may shift some apostrophes from
1114 # being mark-up to being text. It also counts the number of occurrences
1115 # of bold and italics mark-ups.
1119 foreach ( $arr as $r )
1121 if ( ( $i %
2 ) == 1 )
1123 # If there are ever four apostrophes, assume the first is supposed to
1124 # be text, and the remaining three constitute mark-up for bold text.
1125 if ( strlen( $arr[$i] ) == 4 )
1130 # If there are more than 5 apostrophes in a row, assume they're all
1131 # text except for the last 5.
1132 else if ( strlen( $arr[$i] ) > 5 )
1134 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1137 # Count the number of occurrences of bold and italics mark-ups.
1138 # We are not counting sequences of five apostrophes.
1139 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1140 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1141 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1146 # If there is an odd number of both bold and italics, it is likely
1147 # that one of the bold ones was meant to be an apostrophe followed
1148 # by italics. Which one we cannot know for certain, but it is more
1149 # likely to be one that has a single-letter word before it.
1150 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1153 $firstsingleletterword = -1;
1154 $firstmultiletterword = -1;
1156 foreach ( $arr as $r )
1158 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1160 $x1 = substr ($arr[$i-1], -1);
1161 $x2 = substr ($arr[$i-1], -2, 1);
1163 if ($firstspace == -1) $firstspace = $i;
1164 } else if ($x2 === ' ') {
1165 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1167 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1173 # If there is a single-letter word, use it!
1174 if ($firstsingleletterword > -1)
1176 $arr [ $firstsingleletterword ] = "''";
1177 $arr [ $firstsingleletterword-1 ] .= "'";
1179 # If not, but there's a multi-letter word, use that one.
1180 else if ($firstmultiletterword > -1)
1182 $arr [ $firstmultiletterword ] = "''";
1183 $arr [ $firstmultiletterword-1 ] .= "'";
1185 # ... otherwise use the first one that has neither.
1186 # (notice that it is possible for all three to be -1 if, for example,
1187 # there is only one pentuple-apostrophe in the line)
1188 else if ($firstspace > -1)
1190 $arr [ $firstspace ] = "''";
1191 $arr [ $firstspace-1 ] .= "'";
1195 # Now let's actually convert our apostrophic mush to HTML!
1200 foreach ($arr as $r)
1204 if ($state === 'both')
1211 if (strlen ($r) == 2)
1214 { $output .= '</i>'; $state = ''; }
1215 else if ($state === 'bi')
1216 { $output .= '</i>'; $state = 'b'; }
1217 else if ($state === 'ib')
1218 { $output .= '</b></i><b>'; $state = 'b'; }
1219 else if ($state === 'both')
1220 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1221 else # $state can be 'b' or ''
1222 { $output .= '<i>'; $state .= 'i'; }
1224 else if (strlen ($r) == 3)
1227 { $output .= '</b>'; $state = ''; }
1228 else if ($state === 'bi')
1229 { $output .= '</i></b><i>'; $state = 'i'; }
1230 else if ($state === 'ib')
1231 { $output .= '</b>'; $state = 'i'; }
1232 else if ($state === 'both')
1233 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1234 else # $state can be 'i' or ''
1235 { $output .= '<b>'; $state .= 'b'; }
1237 else if (strlen ($r) == 5)
1240 { $output .= '</b><i>'; $state = 'i'; }
1241 else if ($state === 'i')
1242 { $output .= '</i><b>'; $state = 'b'; }
1243 else if ($state === 'bi')
1244 { $output .= '</i></b>'; $state = ''; }
1245 else if ($state === 'ib')
1246 { $output .= '</b></i>'; $state = ''; }
1247 else if ($state === 'both')
1248 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1249 else # ($state == '')
1250 { $buffer = ''; $state = 'both'; }
1255 # Now close all remaining tags. Notice that the order is important.
1256 if ($state === 'b' ||
$state === 'ib')
1258 if ($state === 'i' ||
$state === 'bi' ||
$state === 'ib')
1260 if ($state === 'bi')
1262 # There might be lonely ''''', so make sure we have a buffer
1263 if ($state === 'both' && $buffer)
1264 $output .= '<b><i>'.$buffer.'</i></b>';
1270 * Replace external links (REL)
1272 * Note: this is all very hackish and the order of execution matters a lot.
1273 * Make sure to run maintenance/parserTests.php if you change this code.
1277 function replaceExternalLinks( $text ) {
1279 wfProfileIn( __METHOD__
);
1281 $sk = $this->mOptions
->getSkin();
1283 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1284 $s = array_shift( $bits );
1287 while ( $i<count( $bits ) ) {
1289 $protocol = $bits[$i++
];
1290 $text = $bits[$i++
];
1291 $trail = $bits[$i++
];
1293 # The characters '<' and '>' (which were escaped by
1294 # removeHTMLtags()) should not be included in
1295 # URLs, per RFC 2396.
1297 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1298 $text = substr($url, $m2[0][1]) . ' ' . $text;
1299 $url = substr($url, 0, $m2[0][1]);
1302 # If the link text is an image URL, replace it with an <img> tag
1303 # This happened by accident in the original parser, but some people used it extensively
1304 $img = $this->maybeMakeExternalImage( $text );
1305 if ( $img !== false ) {
1311 # Set linktype for CSS - if URL==text, link is essentially free
1312 $linktype = ($text === $url) ?
'free' : 'text';
1314 # No link text, e.g. [http://domain.tld/some.link]
1315 if ( $text == '' ) {
1316 # Autonumber if allowed. See bug #5918
1317 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1318 $langObj = $this->getFunctionLang();
1319 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1320 $linktype = 'autonumber';
1322 # Otherwise just use the URL
1323 $text = htmlspecialchars( $url );
1327 # Have link text, e.g. [http://domain.tld/some.link text]s
1329 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1332 $text = $wgContLang->markNoConversion($text);
1334 $url = Sanitizer
::cleanUrl( $url );
1336 # Use the encoded URL
1337 # This means that users can paste URLs directly into the text
1338 # Funny characters like ö aren't valid in URLs anyway
1339 # This was changed in August 2004
1340 $s .= $sk->makeExternalLink( $url, $text, false, $linktype,
1341 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1343 # Register link in the output object.
1344 # Replace unnecessary URL escape codes with the referenced character
1345 # This prevents spammers from hiding links from the filters
1346 $pasteurized = self
::replaceUnusualEscapes( $url );
1347 $this->mOutput
->addExternalLink( $pasteurized );
1350 wfProfileOut( __METHOD__
);
1355 * Get an associative array of additional HTML attributes appropriate for a
1356 * particular external link. This currently may include rel => nofollow
1357 * (depending on configuration, namespace, and the URL's domain) and/or a
1358 * target attribute (depending on configuration).
1360 * @param string $url Optional URL, to extract the domain from for rel =>
1361 * nofollow if appropriate
1362 * @return array Associative array of HTML attributes
1364 function getExternalLinkAttribs( $url = false ) {
1366 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1367 $ns = $this->mTitle
->getNamespace();
1368 if( $wgNoFollowLinks && !in_array($ns, $wgNoFollowNsExceptions) ) {
1369 $attribs['rel'] = 'nofollow';
1371 global $wgNoFollowDomainExceptions;
1372 if ( $wgNoFollowDomainExceptions ) {
1373 $bits = wfParseUrl( $url );
1374 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1375 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1376 if( substr( $bits['host'], -strlen( $domain ) )
1378 unset( $attribs['rel'] );
1385 if ( $this->mOptions
->getExternalLinkTarget() ) {
1386 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1393 * Replace unusual URL escape codes with their equivalent characters
1397 * @todo This can merge genuinely required bits in the path or query string,
1398 * breaking legit URLs. A proper fix would treat the various parts of
1399 * the URL differently; as a workaround, just use the output for
1400 * statistical records, not for actual linking/output.
1402 static function replaceUnusualEscapes( $url ) {
1403 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1404 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1408 * Callback function used in replaceUnusualEscapes().
1409 * Replaces unusual URL escape codes with their equivalent character
1413 private static function replaceUnusualEscapesCallback( $matches ) {
1414 $char = urldecode( $matches[0] );
1415 $ord = ord( $char );
1416 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1417 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1418 // No, shouldn't be escaped
1421 // Yes, leave it escaped
1427 * make an image if it's allowed, either through the global
1428 * option, through the exception, or through the on-wiki whitelist
1431 function maybeMakeExternalImage( $url ) {
1432 $sk = $this->mOptions
->getSkin();
1433 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1434 $imagesexception = !empty($imagesfrom);
1436 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1437 if( $imagesexception && is_array( $imagesfrom ) ) {
1438 $imagematch = false;
1439 foreach( $imagesfrom as $match ) {
1440 if( strpos( $url, $match ) === 0 ) {
1445 } elseif( $imagesexception ) {
1446 $imagematch = (strpos( $url, $imagesfrom ) === 0);
1448 $imagematch = false;
1450 if ( $this->mOptions
->getAllowExternalImages()
1451 ||
( $imagesexception && $imagematch ) ) {
1452 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1454 $text = $sk->makeExternalImage( $url );
1457 if( !$text && $this->mOptions
->getEnableImageWhitelist()
1458 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1459 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1460 foreach( $whitelist as $entry ) {
1461 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1462 if( strpos( $entry, '#' ) === 0 ||
$entry === '' )
1464 if( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1465 # Image matches a whitelist entry
1466 $text = $sk->makeExternalImage( $url );
1475 * Process [[ ]] wikilinks
1476 * @return processed text
1480 function replaceInternalLinks( $s ) {
1481 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1486 * Process [[ ]] wikilinks (RIL)
1487 * @return LinkHolderArray
1491 function replaceInternalLinks2( &$s ) {
1494 wfProfileIn( __METHOD__
);
1496 wfProfileIn( __METHOD__
.'-setup' );
1497 static $tc = FALSE, $e1, $e1_img;
1498 # the % is needed to support urlencoded titles as well
1500 $tc = Title
::legalChars() . '#%';
1501 # Match a link having the form [[namespace:link|alternate]]trail
1502 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1503 # Match cases where there is no "]]", which might still be images
1504 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1507 $sk = $this->mOptions
->getSkin();
1508 $holders = new LinkHolderArray( $this );
1510 #split the entire text string on occurences of [[
1511 $a = StringUtils
::explode( '[[', ' ' . $s );
1512 #get the first element (all text up to first [[), and remove the space we added
1515 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1516 $s = substr( $s, 1 );
1518 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1520 if ( $useLinkPrefixExtension ) {
1521 # Match the end of a line for a word that's not followed by whitespace,
1522 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1523 $e2 = wfMsgForContent( 'linkprefix' );
1526 if( is_null( $this->mTitle
) ) {
1527 wfProfileOut( __METHOD__
.'-setup' );
1528 wfProfileOut( __METHOD__
);
1529 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1531 $nottalk = !$this->mTitle
->isTalkPage();
1533 if ( $useLinkPrefixExtension ) {
1535 if ( preg_match( $e2, $s, $m ) ) {
1536 $first_prefix = $m[2];
1538 $first_prefix = false;
1544 if($wgContLang->hasVariants()) {
1545 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1547 $selflink = array($this->mTitle
->getPrefixedText());
1549 $useSubpages = $this->areSubpagesAllowed();
1550 wfProfileOut( __METHOD__
.'-setup' );
1552 # Loop for each link
1553 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1554 # Check for excessive memory usage
1555 if ( $holders->isBig() ) {
1557 # Do the existence check, replace the link holders and clear the array
1558 $holders->replace( $s );
1562 if ( $useLinkPrefixExtension ) {
1563 wfProfileIn( __METHOD__
.'-prefixhandling' );
1564 if ( preg_match( $e2, $s, $m ) ) {
1572 $prefix = $first_prefix;
1573 $first_prefix = false;
1575 wfProfileOut( __METHOD__
.'-prefixhandling' );
1578 $might_be_img = false;
1580 wfProfileIn( __METHOD__
."-e1" );
1581 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1583 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1584 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1585 # the real problem is with the $e1 regex
1588 # Still some problems for cases where the ] is meant to be outside punctuation,
1589 # and no image is in sight. See bug 2095.
1592 substr( $m[3], 0, 1 ) === ']' &&
1593 strpos($text, '[') !== false
1596 $text .= ']'; # so that replaceExternalLinks($text) works later
1597 $m[3] = substr( $m[3], 1 );
1599 # fix up urlencoded title texts
1600 if( strpos( $m[1], '%' ) !== false ) {
1601 # Should anchors '#' also be rejected?
1602 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode($m[1]) );
1605 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1606 $might_be_img = true;
1608 if ( strpos( $m[1], '%' ) !== false ) {
1609 $m[1] = urldecode($m[1]);
1612 } else { # Invalid form; output directly
1613 $s .= $prefix . '[[' . $line ;
1614 wfProfileOut( __METHOD__
."-e1" );
1617 wfProfileOut( __METHOD__
."-e1" );
1618 wfProfileIn( __METHOD__
."-misc" );
1620 # Don't allow internal links to pages containing
1621 # PROTO: where PROTO is a valid URL protocol; these
1622 # should be external links.
1623 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1624 $s .= $prefix . '[[' . $line ;
1625 wfProfileOut( __METHOD__
."-misc" );
1629 # Make subpage if necessary
1630 if ( $useSubpages ) {
1631 $link = $this->maybeDoSubpageLink( $m[1], $text );
1636 $noforce = (substr( $m[1], 0, 1 ) !== ':');
1638 # Strip off leading ':'
1639 $link = substr( $link, 1 );
1642 wfProfileOut( __METHOD__
."-misc" );
1643 wfProfileIn( __METHOD__
."-title" );
1644 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1645 if ( $nt === null ) {
1646 $s .= $prefix . '[[' . $line;
1647 wfProfileOut( __METHOD__
."-title" );
1651 $ns = $nt->getNamespace();
1652 $iw = $nt->getInterWiki();
1653 wfProfileOut( __METHOD__
."-title" );
1655 if ( $might_be_img ) { # if this is actually an invalid link
1656 wfProfileIn( __METHOD__
."-might_be_img" );
1657 if ( $ns == NS_FILE
&& $noforce ) { #but might be an image
1660 #look at the next 'line' to see if we can close it there
1662 $next_line = $a->current();
1663 if ( $next_line === false ||
$next_line === null ) {
1666 $m = explode( ']]', $next_line, 3 );
1667 if ( count( $m ) == 3 ) {
1668 # the first ]] closes the inner link, the second the image
1670 $text .= "[[{$m[0]}]]{$m[1]}";
1673 } elseif ( count( $m ) == 2 ) {
1674 #if there's exactly one ]] that's fine, we'll keep looking
1675 $text .= "[[{$m[0]}]]{$m[1]}";
1677 #if $next_line is invalid too, we need look no further
1678 $text .= '[[' . $next_line;
1683 # we couldn't find the end of this imageLink, so output it raw
1684 #but don't ignore what might be perfectly normal links in the text we've examined
1685 $holders->merge( $this->replaceInternalLinks2( $text ) );
1686 $s .= "{$prefix}[[$link|$text";
1687 # note: no $trail, because without an end, there *is* no trail
1688 wfProfileOut( __METHOD__
."-might_be_img" );
1691 } else { #it's not an image, so output it raw
1692 $s .= "{$prefix}[[$link|$text";
1693 # note: no $trail, because without an end, there *is* no trail
1694 wfProfileOut( __METHOD__
."-might_be_img" );
1697 wfProfileOut( __METHOD__
."-might_be_img" );
1700 $wasblank = ( $text == '' );
1701 if ( $wasblank ) $text = $link;
1703 # Link not escaped by : , create the various objects
1707 wfProfileIn( __METHOD__
."-interwiki" );
1708 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1709 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1710 $s = rtrim($s . $prefix);
1711 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1712 wfProfileOut( __METHOD__
."-interwiki" );
1715 wfProfileOut( __METHOD__
."-interwiki" );
1717 if ( $ns == NS_FILE
) {
1718 wfProfileIn( __METHOD__
."-image" );
1719 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1721 # if no parameters were passed, $text
1722 # becomes something like "File:Foo.png",
1723 # which we don't want to pass on to the
1727 # recursively parse links inside the image caption
1728 # actually, this will parse them in any other parameters, too,
1729 # but it might be hard to fix that, and it doesn't matter ATM
1730 $text = $this->replaceExternalLinks($text);
1731 $holders->merge( $this->replaceInternalLinks2( $text ) );
1733 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1734 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1736 $this->mOutput
->addImage( $nt->getDBkey() );
1737 wfProfileOut( __METHOD__
."-image" );
1742 if ( $ns == NS_CATEGORY
) {
1743 wfProfileIn( __METHOD__
."-category" );
1744 $s = rtrim($s . "\n"); # bug 87
1747 $sortkey = $this->getDefaultSort();
1751 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1752 $sortkey = str_replace( "\n", '', $sortkey );
1753 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1754 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1757 * Strip the whitespace Category links produce, see bug 87
1758 * @todo We might want to use trim($tmp, "\n") here.
1760 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1762 wfProfileOut( __METHOD__
."-category" );
1767 # Self-link checking
1768 if( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1769 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1770 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1775 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1776 # FIXME: Should do batch file existence checks, see comment below
1777 if( $ns == NS_MEDIA
) {
1778 wfProfileIn( __METHOD__
."-media" );
1779 # Give extensions a chance to select the file revision for us
1780 $skip = $time = false;
1781 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1783 $link = $sk->link( $nt );
1785 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1787 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1788 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1789 $this->mOutput
->addImage( $nt->getDBkey() );
1790 wfProfileOut( __METHOD__
."-media" );
1794 wfProfileIn( __METHOD__
."-always_known" );
1795 # Some titles, such as valid special pages or files in foreign repos, should
1796 # be shown as bluelinks even though they're not included in the page table
1798 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1799 # batch file existence checks for NS_FILE and NS_MEDIA
1800 if( $iw == '' && $nt->isAlwaysKnown() ) {
1801 $this->mOutput
->addLink( $nt );
1802 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1804 # Links will be added to the output link list after checking
1805 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1807 wfProfileOut( __METHOD__
."-always_known" );
1809 wfProfileOut( __METHOD__
);
1814 * Make a link placeholder. The text returned can be later resolved to a real link with
1815 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1816 * parsing of interwiki links, and secondly to allow all existence checks and
1817 * article length checks (for stub links) to be bundled into a single query.
1821 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1822 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1826 * Render a forced-blue link inline; protect against double expansion of
1827 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1828 * Since this little disaster has to split off the trail text to avoid
1829 * breaking URLs in the following text without breaking trails on the
1830 * wiki links, it's been made into a horrible function.
1833 * @param string $text
1834 * @param string $query
1835 * @param string $trail
1836 * @param string $prefix
1837 * @return string HTML-wikitext mix oh yuck
1839 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1840 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1841 $sk = $this->mOptions
->getSkin();
1842 // FIXME: use link() instead of deprecated makeKnownLinkObj()
1843 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1844 return $this->armorLinks( $link ) . $trail;
1848 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1849 * going to go through further parsing steps before inline URL expansion.
1851 * Not needed quite as much as it used to be since free links are a bit
1852 * more sensible these days. But bracketed links are still an issue.
1854 * @param string more-or-less HTML
1855 * @return string less-or-more HTML with NOPARSE bits
1857 function armorLinks( $text ) {
1858 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1859 "{$this->mUniqPrefix}NOPARSE$1", $text );
1863 * Return true if subpage links should be expanded on this page.
1866 function areSubpagesAllowed() {
1867 # Some namespaces don't allow subpages
1868 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
1872 * Handle link to subpage if necessary
1873 * @param string $target the source of the link
1874 * @param string &$text the link text, modified as necessary
1875 * @return string the full name of the link
1878 function maybeDoSubpageLink($target, &$text) {
1879 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
1883 * Used by doBlockLevels()
1886 /* private */ function closeParagraph() {
1888 if ( $this->mLastSection
!= '' ) {
1889 $result = '</' . $this->mLastSection
. ">\n";
1891 $this->mInPre
= false;
1892 $this->mLastSection
= '';
1895 # getCommon() returns the length of the longest common substring
1896 # of both arguments, starting at the beginning of both.
1898 /* private */ function getCommon( $st1, $st2 ) {
1899 $fl = strlen( $st1 );
1900 $shorter = strlen( $st2 );
1901 if ( $fl < $shorter ) { $shorter = $fl; }
1903 for ( $i = 0; $i < $shorter; ++
$i ) {
1904 if ( $st1{$i} != $st2{$i} ) { break; }
1908 # These next three functions open, continue, and close the list
1909 # element appropriate to the prefix character passed into them.
1911 /* private */ function openList( $char ) {
1912 $result = $this->closeParagraph();
1914 if ( '*' === $char ) { $result .= '<ul><li>'; }
1915 elseif ( '#' === $char ) { $result .= '<ol><li>'; }
1916 elseif ( ':' === $char ) { $result .= '<dl><dd>'; }
1917 elseif ( ';' === $char ) {
1918 $result .= '<dl><dt>';
1919 $this->mDTopen
= true;
1921 else { $result = '<!-- ERR 1 -->'; }
1926 /* private */ function nextItem( $char ) {
1927 if ( '*' === $char ||
'#' === $char ) { return '</li><li>'; }
1928 elseif ( ':' === $char ||
';' === $char ) {
1930 if ( $this->mDTopen
) { $close = '</dt>'; }
1931 if ( ';' === $char ) {
1932 $this->mDTopen
= true;
1933 return $close . '<dt>';
1935 $this->mDTopen
= false;
1936 return $close . '<dd>';
1939 return '<!-- ERR 2 -->';
1942 /* private */ function closeList( $char ) {
1943 if ( '*' === $char ) { $text = '</li></ul>'; }
1944 elseif ( '#' === $char ) { $text = '</li></ol>'; }
1945 elseif ( ':' === $char ) {
1946 if ( $this->mDTopen
) {
1947 $this->mDTopen
= false;
1948 $text = '</dt></dl>';
1950 $text = '</dd></dl>';
1953 else { return '<!-- ERR 3 -->'; }
1959 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
1961 * @param $linestart bool whether or not this is at the start of a line.
1963 * @return string the lists rendered as HTML
1965 function doBlockLevels( $text, $linestart ) {
1966 wfProfileIn( __METHOD__
);
1968 # Parsing through the text line by line. The main thing
1969 # happening here is handling of block-level elements p, pre,
1970 # and making lists from lines starting with * # : etc.
1972 $textLines = StringUtils
::explode( "\n", $text );
1974 $lastPrefix = $output = '';
1975 $this->mDTopen
= $inBlockElem = false;
1977 $paragraphStack = false;
1979 foreach ( $textLines as $oLine ) {
1981 if ( !$linestart ) {
1991 $lastPrefixLength = strlen( $lastPrefix );
1992 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
1993 $preOpenMatch = preg_match('/<pre/i', $oLine );
1994 // If not in a <pre> element, scan for and figure out what prefixes are there.
1995 if ( !$this->mInPre
) {
1996 # Multiple prefixes may abut each other for nested lists.
1997 $prefixLength = strspn( $oLine, '*#:;' );
1998 $prefix = substr( $oLine, 0, $prefixLength );
2001 // ; and : are both from definition-lists, so they're equivalent
2002 // for the purposes of determining whether or not we need to open/close
2004 $prefix2 = str_replace( ';', ':', $prefix );
2005 $t = substr( $oLine, $prefixLength );
2006 $this->mInPre
= (bool)$preOpenMatch;
2008 # Don't interpret any other prefixes in preformatted text
2010 $prefix = $prefix2 = '';
2015 if( $prefixLength && $lastPrefix === $prefix2 ) {
2016 # Same as the last item, so no need to deal with nesting or opening stuff
2017 $output .= $this->nextItem( substr( $prefix, -1 ) );
2018 $paragraphStack = false;
2020 if ( substr( $prefix, -1 ) === ';') {
2021 # The one nasty exception: definition lists work like this:
2022 # ; title : definition text
2023 # So we check for : in the remainder text to split up the
2024 # title and definition, without b0rking links.
2026 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2028 $output .= $term . $this->nextItem( ':' );
2031 } elseif( $prefixLength ||
$lastPrefixLength ) {
2032 // We need to open or close prefixes, or both.
2034 # Either open or close a level...
2035 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2036 $paragraphStack = false;
2038 // Close all the prefixes which aren't shared.
2039 while( $commonPrefixLength < $lastPrefixLength ) {
2040 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2041 --$lastPrefixLength;
2044 // Continue the current prefix if appropriate.
2045 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2046 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2049 // Open prefixes where appropriate.
2050 while ( $prefixLength > $commonPrefixLength ) {
2051 $char = substr( $prefix, $commonPrefixLength, 1 );
2052 $output .= $this->openList( $char );
2054 if ( ';' === $char ) {
2055 # FIXME: This is dupe of code above
2056 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2058 $output .= $term . $this->nextItem( ':' );
2061 ++
$commonPrefixLength;
2063 $lastPrefix = $prefix2;
2066 // If we have no prefixes, go to paragraph mode.
2067 if( 0 == $prefixLength ) {
2068 wfProfileIn( __METHOD__
."-paragraph" );
2069 # No prefix (not in list)--go to paragraph mode
2070 // XXX: use a stack for nestable elements like span, table and div
2071 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2072 $closematch = preg_match(
2073 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2074 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2075 if ( $openmatch or $closematch ) {
2076 $paragraphStack = false;
2077 #Â TODO bug 5718: paragraph closed
2078 $output .= $this->closeParagraph();
2079 if ( $preOpenMatch and !$preCloseMatch ) {
2080 $this->mInPre
= true;
2082 if ( $closematch ) {
2083 $inBlockElem = false;
2085 $inBlockElem = true;
2087 } else if ( !$inBlockElem && !$this->mInPre
) {
2088 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' or trim($t) != '' ) ) {
2090 if ($this->mLastSection
!== 'pre') {
2091 $paragraphStack = false;
2092 $output .= $this->closeParagraph().'<pre>';
2093 $this->mLastSection
= 'pre';
2095 $t = substr( $t, 1 );
2098 if ( trim($t) == '' ) {
2099 if ( $paragraphStack ) {
2100 $output .= $paragraphStack.'<br />';
2101 $paragraphStack = false;
2102 $this->mLastSection
= 'p';
2104 if ($this->mLastSection
!== 'p' ) {
2105 $output .= $this->closeParagraph();
2106 $this->mLastSection
= '';
2107 $paragraphStack = '<p>';
2109 $paragraphStack = '</p><p>';
2113 if ( $paragraphStack ) {
2114 $output .= $paragraphStack;
2115 $paragraphStack = false;
2116 $this->mLastSection
= 'p';
2117 } else if ($this->mLastSection
!== 'p') {
2118 $output .= $this->closeParagraph().'<p>';
2119 $this->mLastSection
= 'p';
2124 wfProfileOut( __METHOD__
."-paragraph" );
2126 // somewhere above we forget to get out of pre block (bug 785)
2127 if($preCloseMatch && $this->mInPre
) {
2128 $this->mInPre
= false;
2130 if ($paragraphStack === false) {
2134 while ( $prefixLength ) {
2135 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2138 if ( $this->mLastSection
!= '' ) {
2139 $output .= '</' . $this->mLastSection
. '>';
2140 $this->mLastSection
= '';
2143 wfProfileOut( __METHOD__
);
2148 * Split up a string on ':', ignoring any occurences inside tags
2149 * to prevent illegal overlapping.
2150 * @param string $str the string to split
2151 * @param string &$before set to everything before the ':'
2152 * @param string &$after set to everything after the ':'
2153 * return string the position of the ':', or false if none found
2155 function findColonNoLinks($str, &$before, &$after) {
2156 wfProfileIn( __METHOD__
);
2158 $pos = strpos( $str, ':' );
2159 if( $pos === false ) {
2161 wfProfileOut( __METHOD__
);
2165 $lt = strpos( $str, '<' );
2166 if( $lt === false ||
$lt > $pos ) {
2167 // Easy; no tag nesting to worry about
2168 $before = substr( $str, 0, $pos );
2169 $after = substr( $str, $pos+
1 );
2170 wfProfileOut( __METHOD__
);
2174 // Ugly state machine to walk through avoiding tags.
2175 $state = self
::COLON_STATE_TEXT
;
2177 $len = strlen( $str );
2178 for( $i = 0; $i < $len; $i++
) {
2182 // (Using the number is a performance hack for common cases)
2183 case 0: // self::COLON_STATE_TEXT:
2186 // Could be either a <start> tag or an </end> tag
2187 $state = self
::COLON_STATE_TAGSTART
;
2192 $before = substr( $str, 0, $i );
2193 $after = substr( $str, $i +
1 );
2194 wfProfileOut( __METHOD__
);
2197 // Embedded in a tag; don't break it.
2200 // Skip ahead looking for something interesting
2201 $colon = strpos( $str, ':', $i );
2202 if( $colon === false ) {
2203 // Nothing else interesting
2204 wfProfileOut( __METHOD__
);
2207 $lt = strpos( $str, '<', $i );
2208 if( $stack === 0 ) {
2209 if( $lt === false ||
$colon < $lt ) {
2211 $before = substr( $str, 0, $colon );
2212 $after = substr( $str, $colon +
1 );
2213 wfProfileOut( __METHOD__
);
2217 if( $lt === false ) {
2218 // Nothing else interesting to find; abort!
2219 // We're nested, but there's no close tags left. Abort!
2222 // Skip ahead to next tag start
2224 $state = self
::COLON_STATE_TAGSTART
;
2227 case 1: // self::COLON_STATE_TAG:
2232 $state = self
::COLON_STATE_TEXT
;
2235 // Slash may be followed by >?
2236 $state = self
::COLON_STATE_TAGSLASH
;
2242 case 2: // self::COLON_STATE_TAGSTART:
2245 $state = self
::COLON_STATE_CLOSETAG
;
2248 $state = self
::COLON_STATE_COMMENT
;
2251 // Illegal early close? This shouldn't happen D:
2252 $state = self
::COLON_STATE_TEXT
;
2255 $state = self
::COLON_STATE_TAG
;
2258 case 3: // self::COLON_STATE_CLOSETAG:
2263 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2264 wfProfileOut( __METHOD__
);
2267 $state = self
::COLON_STATE_TEXT
;
2270 case self
::COLON_STATE_TAGSLASH
:
2272 // Yes, a self-closed tag <blah/>
2273 $state = self
::COLON_STATE_TEXT
;
2275 // Probably we're jumping the gun, and this is an attribute
2276 $state = self
::COLON_STATE_TAG
;
2279 case 5: // self::COLON_STATE_COMMENT:
2281 $state = self
::COLON_STATE_COMMENTDASH
;
2284 case self
::COLON_STATE_COMMENTDASH
:
2286 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2288 $state = self
::COLON_STATE_COMMENT
;
2291 case self
::COLON_STATE_COMMENTDASHDASH
:
2293 $state = self
::COLON_STATE_TEXT
;
2295 $state = self
::COLON_STATE_COMMENT
;
2299 throw new MWException( "State machine error in " . __METHOD__
);
2303 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2306 wfProfileOut( __METHOD__
);
2311 * Return value of a magic variable (like PAGENAME)
2315 function getVariableValue( $index, $frame=false ) {
2316 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2317 global $wgScriptPath, $wgStylePath;
2320 * Some of these require message or data lookups and can be
2321 * expensive to check many times.
2323 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2324 if ( isset( $this->mVarCache
[$index] ) ) {
2325 return $this->mVarCache
[$index];
2329 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2330 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2333 global $wgLocaltimezone;
2334 if ( isset( $wgLocaltimezone ) ) {
2335 $oldtz = date_default_timezone_get();
2336 date_default_timezone_set( $wgLocaltimezone );
2339 $localTimestamp = date( 'YmdHis', $ts );
2340 $localMonth = date( 'm', $ts );
2341 $localMonth1 = date( 'n', $ts );
2342 $localMonthName = date( 'n', $ts );
2343 $localDay = date( 'j', $ts );
2344 $localDay2 = date( 'd', $ts );
2345 $localDayOfWeek = date( 'w', $ts );
2346 $localWeek = date( 'W', $ts );
2347 $localYear = date( 'Y', $ts );
2348 $localHour = date( 'H', $ts );
2349 if ( isset( $wgLocaltimezone ) ) {
2350 date_default_timezone_set( $oldtz );
2354 case 'currentmonth':
2355 $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2357 case 'currentmonth1':
2358 $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2360 case 'currentmonthname':
2361 $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2363 case 'currentmonthnamegen':
2364 $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2366 case 'currentmonthabbrev':
2367 $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2370 $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2373 $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2376 $value = $wgContLang->formatNum( $localMonth );
2379 $value = $wgContLang->formatNum( $localMonth1 );
2381 case 'localmonthname':
2382 $value = $wgContLang->getMonthName( $localMonthName );
2384 case 'localmonthnamegen':
2385 $value = $wgContLang->getMonthNameGen( $localMonthName );
2387 case 'localmonthabbrev':
2388 $value = $wgContLang->getMonthAbbreviation( $localMonthName );
2391 $value = $wgContLang->formatNum( $localDay );
2394 $value = $wgContLang->formatNum( $localDay2 );
2397 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2400 $value = $this->mTitle
->getPartialURL();
2402 case 'fullpagename':
2403 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2405 case 'fullpagenamee':
2406 $value = $this->mTitle
->getPrefixedURL();
2409 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2411 case 'subpagenamee':
2412 $value = $this->mTitle
->getSubpageUrlForm();
2414 case 'basepagename':
2415 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2417 case 'basepagenamee':
2418 $value = wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2420 case 'talkpagename':
2421 if( $this->mTitle
->canTalk() ) {
2422 $talkPage = $this->mTitle
->getTalkPage();
2423 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2428 case 'talkpagenamee':
2429 if( $this->mTitle
->canTalk() ) {
2430 $talkPage = $this->mTitle
->getTalkPage();
2431 $value = $talkPage->getPrefixedUrl();
2436 case 'subjectpagename':
2437 $subjPage = $this->mTitle
->getSubjectPage();
2438 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2440 case 'subjectpagenamee':
2441 $subjPage = $this->mTitle
->getSubjectPage();
2442 $value = $subjPage->getPrefixedUrl();
2445 // Let the edit saving system know we should parse the page
2446 // *after* a revision ID has been assigned.
2447 $this->mOutput
->setFlag( 'vary-revision' );
2448 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2449 $value = $this->mRevisionId
;
2452 // Let the edit saving system know we should parse the page
2453 // *after* a revision ID has been assigned. This is for null edits.
2454 $this->mOutput
->setFlag( 'vary-revision' );
2455 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2456 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2458 case 'revisionday2':
2459 // Let the edit saving system know we should parse the page
2460 // *after* a revision ID has been assigned. This is for null edits.
2461 $this->mOutput
->setFlag( 'vary-revision' );
2462 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2463 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2465 case 'revisionmonth':
2466 // Let the edit saving system know we should parse the page
2467 // *after* a revision ID has been assigned. This is for null edits.
2468 $this->mOutput
->setFlag( 'vary-revision' );
2469 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2470 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2472 case 'revisionyear':
2473 // Let the edit saving system know we should parse the page
2474 // *after* a revision ID has been assigned. This is for null edits.
2475 $this->mOutput
->setFlag( 'vary-revision' );
2476 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2477 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2479 case 'revisiontimestamp':
2480 // Let the edit saving system know we should parse the page
2481 // *after* a revision ID has been assigned. This is for null edits.
2482 $this->mOutput
->setFlag( 'vary-revision' );
2483 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2484 $value = $this->getRevisionTimestamp();
2486 case 'revisionuser':
2487 // Let the edit saving system know we should parse the page
2488 // *after* a revision ID has been assigned. This is for null edits.
2489 $this->mOutput
->setFlag( 'vary-revision' );
2490 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2491 $value = $this->getRevisionUser();
2494 $value = str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2497 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2500 $value = $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2503 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2505 case 'subjectspace':
2506 $value = $this->mTitle
->getSubjectNsText();
2508 case 'subjectspacee':
2509 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2511 case 'currentdayname':
2512 $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2515 $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2518 $value = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2521 $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2524 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2525 // int to remove the padding
2526 $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2529 $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2531 case 'localdayname':
2532 $value = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2535 $value = $wgContLang->formatNum( $localYear, true );
2538 $value = $wgContLang->time( $localTimestamp, false, false );
2541 $value = $wgContLang->formatNum( $localHour, true );
2544 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2545 // int to remove the padding
2546 $value = $wgContLang->formatNum( (int)$localWeek );
2549 $value = $wgContLang->formatNum( $localDayOfWeek );
2551 case 'numberofarticles':
2552 $value = $wgContLang->formatNum( SiteStats
::articles() );
2554 case 'numberoffiles':
2555 $value = $wgContLang->formatNum( SiteStats
::images() );
2557 case 'numberofusers':
2558 $value = $wgContLang->formatNum( SiteStats
::users() );
2560 case 'numberofactiveusers':
2561 $value = $wgContLang->formatNum( SiteStats
::activeUsers() );
2563 case 'numberofpages':
2564 $value = $wgContLang->formatNum( SiteStats
::pages() );
2566 case 'numberofadmins':
2567 $value = $wgContLang->formatNum( SiteStats
::numberingroup('sysop') );
2569 case 'numberofedits':
2570 $value = $wgContLang->formatNum( SiteStats
::edits() );
2572 case 'numberofviews':
2573 $value = $wgContLang->formatNum( SiteStats
::views() );
2575 case 'currenttimestamp':
2576 $value = wfTimestamp( TS_MW
, $ts );
2578 case 'localtimestamp':
2579 $value = $localTimestamp;
2581 case 'currentversion':
2582 $value = SpecialVersion
::getVersion();
2589 return $wgServerName;
2591 return $wgScriptPath;
2593 return $wgStylePath;
2594 case 'directionmark':
2595 return $wgContLang->getDirMark();
2596 case 'contentlanguage':
2597 global $wgContLanguageCode;
2598 return $wgContLanguageCode;
2601 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) )
2608 $this->mVarCache
[$index] = $value;
2614 * initialise the magic variables (like CURRENTMONTHNAME)
2618 function initialiseVariables() {
2619 wfProfileIn( __METHOD__
);
2620 $variableIDs = MagicWord
::getVariableIDs();
2622 $this->mVariables
= new MagicWordArray( $variableIDs );
2623 wfProfileOut( __METHOD__
);
2627 * Preprocess some wikitext and return the document tree.
2628 * This is the ghost of replace_variables().
2630 * @param string $text The text to parse
2631 * @param integer flags Bitwise combination of:
2632 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2633 * included. Default is to assume a direct page view.
2635 * The generated DOM tree must depend only on the input text and the flags.
2636 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2638 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2639 * change in the DOM tree for a given text, must be passed through the section identifier
2640 * in the section edit link and thus back to extractSections().
2642 * The output of this function is currently only cached in process memory, but a persistent
2643 * cache may be implemented at a later date which takes further advantage of these strict
2644 * dependency requirements.
2648 function preprocessToDom ( $text, $flags = 0 ) {
2649 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2654 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2656 public static function splitWhitespace( $s ) {
2657 $ltrimmed = ltrim( $s );
2658 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2659 $trimmed = rtrim( $ltrimmed );
2660 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2662 $w2 = substr( $ltrimmed, -$diff );
2666 return array( $w1, $trimmed, $w2 );
2670 * Replace magic variables, templates, and template arguments
2671 * with the appropriate text. Templates are substituted recursively,
2672 * taking care to avoid infinite loops.
2674 * Note that the substitution depends on value of $mOutputType:
2675 * self::OT_WIKI: only {{subst:}} templates
2676 * self::OT_PREPROCESS: templates but not extension tags
2677 * self::OT_HTML: all templates and extension tags
2679 * @param string $tex The text to transform
2680 * @param PPFrame $frame Object describing the arguments passed to the template.
2681 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2682 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2683 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2686 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2687 # Is there any text? Also, Prevent too big inclusions!
2688 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2691 wfProfileIn( __METHOD__
);
2693 if ( $frame === false ) {
2694 $frame = $this->getPreprocessor()->newFrame();
2695 } elseif ( !( $frame instanceof PPFrame
) ) {
2696 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2697 $frame = $this->getPreprocessor()->newCustomFrame($frame);
2700 $dom = $this->preprocessToDom( $text );
2701 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2702 $text = $frame->expand( $dom, $flags );
2704 wfProfileOut( __METHOD__
);
2708 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2709 static function createAssocArgs( $args ) {
2710 $assocArgs = array();
2712 foreach( $args as $arg ) {
2713 $eqpos = strpos( $arg, '=' );
2714 if ( $eqpos === false ) {
2715 $assocArgs[$index++
] = $arg;
2717 $name = trim( substr( $arg, 0, $eqpos ) );
2718 $value = trim( substr( $arg, $eqpos+
1 ) );
2719 if ( $value === false ) {
2722 if ( $name !== false ) {
2723 $assocArgs[$name] = $value;
2732 * Warn the user when a parser limitation is reached
2733 * Will warn at most once the user per limitation type
2735 * @param string $limitationType, should be one of:
2736 * 'expensive-parserfunction' (corresponding messages: 'expensive-parserfunction-warning', 'expensive-parserfunction-category')
2737 * 'post-expand-template-argument' (corresponding messages: 'post-expand-template-argument-warning', 'post-expand-template-argument-category')
2738 * 'post-expand-template-inclusion' (corresponding messages: 'post-expand-template-inclusion-warning', 'post-expand-template-inclusion-category')
2739 * @params int $current, $max When an explicit limit has been
2740 * exceeded, provide the values (optional)
2742 function limitationWarn( $limitationType, $current=null, $max=null) {
2743 //does no harm if $current and $max are present but are unnecessary for the message
2744 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
2745 $this->mOutput
->addWarning( $warning );
2746 $this->addTrackingCategory( "$limitationType-category" );
2750 * Return the text of a template, after recursively
2751 * replacing any variables or templates within the template.
2753 * @param array $piece The parts of the template
2754 * $piece['title']: the title, i.e. the part before the |
2755 * $piece['parts']: the parameter array
2756 * $piece['lineStart']: whether the brace was at the start of a line
2757 * @param PPFrame The current frame, contains template arguments
2758 * @return string the text of the template
2761 function braceSubstitution( $piece, $frame ) {
2762 global $wgContLang, $wgNonincludableNamespaces;
2763 wfProfileIn( __METHOD__
);
2764 wfProfileIn( __METHOD__
.'-setup' );
2767 $found = false; # $text has been filled
2768 $nowiki = false; # wiki markup in $text should be escaped
2769 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2770 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2771 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2772 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2774 # Title object, where $text came from
2777 # $part1 is the bit before the first |, and must contain only title characters.
2778 # Various prefixes will be stripped from it later.
2779 $titleWithSpaces = $frame->expand( $piece['title'] );
2780 $part1 = trim( $titleWithSpaces );
2783 # Original title text preserved for various purposes
2784 $originalTitle = $part1;
2786 # $args is a list of argument nodes, starting from index 0, not including $part1
2787 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2788 wfProfileOut( __METHOD__
.'-setup' );
2791 wfProfileIn( __METHOD__
.'-modifiers' );
2793 $mwSubst = MagicWord
::get( 'subst' );
2794 if ( $mwSubst->matchStartAndRemove( $part1 ) xor $this->ot
['wiki'] ) {
2795 # One of two possibilities is true:
2796 # 1) Found SUBST but not in the PST phase
2797 # 2) Didn't find SUBST and in the PST phase
2798 # In either case, return without further processing
2799 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2806 if ( !$found && $args->getLength() == 0 ) {
2807 $id = $this->mVariables
->matchStartToEnd( $part1 );
2808 if ( $id !== false ) {
2809 $text = $this->getVariableValue( $id, $frame );
2810 if (MagicWord
::getCacheTTL($id)>-1)
2811 $this->mOutput
->mContainsOldMagic
= true;
2816 # MSG, MSGNW and RAW
2819 $mwMsgnw = MagicWord
::get( 'msgnw' );
2820 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2823 # Remove obsolete MSG:
2824 $mwMsg = MagicWord
::get( 'msg' );
2825 $mwMsg->matchStartAndRemove( $part1 );
2829 $mwRaw = MagicWord
::get( 'raw' );
2830 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2831 $forceRawInterwiki = true;
2834 wfProfileOut( __METHOD__
.'-modifiers' );
2838 wfProfileIn( __METHOD__
. '-pfunc' );
2840 $colonPos = strpos( $part1, ':' );
2841 if ( $colonPos !== false ) {
2842 # Case sensitive functions
2843 $function = substr( $part1, 0, $colonPos );
2844 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2845 $function = $this->mFunctionSynonyms
[1][$function];
2847 # Case insensitive functions
2848 $function = $wgContLang->lc( $function );
2849 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2850 $function = $this->mFunctionSynonyms
[0][$function];
2856 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2857 $initialArgs = array( &$this );
2858 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2859 if ( $flags & SFH_OBJECT_ARGS
) {
2860 # Add a frame parameter, and pass the arguments as an array
2861 $allArgs = $initialArgs;
2862 $allArgs[] = $frame;
2863 for ( $i = 0; $i < $args->getLength(); $i++
) {
2864 $funcArgs[] = $args->item( $i );
2866 $allArgs[] = $funcArgs;
2868 # Convert arguments to plain text
2869 for ( $i = 0; $i < $args->getLength(); $i++
) {
2870 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2872 $allArgs = array_merge( $initialArgs, $funcArgs );
2875 # Workaround for PHP bug 35229 and similar
2876 if ( !is_callable( $callback ) ) {
2877 wfProfileOut( __METHOD__
. '-pfunc' );
2878 wfProfileOut( __METHOD__
);
2879 throw new MWException( "Tag hook for $function is not callable\n" );
2881 $result = call_user_func_array( $callback, $allArgs );
2884 $preprocessFlags = 0;
2886 if ( is_array( $result ) ) {
2887 if ( isset( $result[0] ) ) {
2889 unset( $result[0] );
2892 // Extract flags into the local scope
2893 // This allows callers to set flags such as nowiki, found, etc.
2899 $text = $this->preprocessToDom( $text, $preprocessFlags );
2904 wfProfileOut( __METHOD__
. '-pfunc' );
2907 # Finish mangling title and then check for loops.
2908 # Set $title to a Title object and $titleText to the PDBK
2911 # Split the title into page and subpage
2913 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2914 if ($subpage !== '') {
2915 $ns = $this->mTitle
->getNamespace();
2917 $title = Title
::newFromText( $part1, $ns );
2919 $titleText = $title->getPrefixedText();
2920 # Check for language variants if the template is not found
2921 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2922 $wgContLang->findVariantLink( $part1, $title, true );
2924 # Do recursion depth check
2925 $limit = $this->mOptions
->getMaxTemplateDepth();
2926 if ( $frame->depth
>= $limit ) {
2928 $text = '<span class="error">' . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit ) . '</span>';
2933 # Load from database
2934 if ( !$found && $title ) {
2935 wfProfileIn( __METHOD__
. '-loadtpl' );
2936 if ( !$title->isExternal() ) {
2937 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
2938 $text = SpecialPage
::capturePath( $title );
2939 if ( is_string( $text ) ) {
2942 $this->disableCache();
2944 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
2945 $found = false; //access denied
2946 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
2948 list( $text, $title ) = $this->getTemplateDom( $title );
2949 if ( $text !== false ) {
2955 # If the title is valid but undisplayable, make a link to it
2956 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
2957 $text = "[[:$titleText]]";
2960 } elseif ( $title->isTrans() ) {
2961 // Interwiki transclusion
2962 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
2963 $text = $this->interwikiTransclude( $title, 'render' );
2966 $text = $this->interwikiTransclude( $title, 'raw' );
2967 // Preprocess it like a template
2968 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
2974 # Do infinite loop check
2975 # This has to be done after redirect resolution to avoid infinite loops via redirects
2976 if ( !$frame->loopCheck( $title ) ) {
2978 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
2979 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
2981 wfProfileOut( __METHOD__
. '-loadtpl' );
2984 # If we haven't found text to substitute by now, we're done
2985 # Recover the source wikitext and return it
2987 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2988 wfProfileOut( __METHOD__
);
2989 return array( 'object' => $text );
2992 # Expand DOM-style return values in a child frame
2993 if ( $isChildObj ) {
2994 # Clean up argument array
2995 $newFrame = $frame->newChild( $args, $title );
2998 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
2999 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3000 # Expansion is eligible for the empty-frame cache
3001 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3002 $text = $this->mTplExpandCache
[$titleText];
3004 $text = $newFrame->expand( $text );
3005 $this->mTplExpandCache
[$titleText] = $text;
3008 # Uncached expansion
3009 $text = $newFrame->expand( $text );
3012 if ( $isLocalObj && $nowiki ) {
3013 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3014 $isLocalObj = false;
3017 # Replace raw HTML by a placeholder
3018 # Add a blank line preceding, to prevent it from mucking up
3019 # immediately preceding headings
3021 $text = "\n\n" . $this->insertStripItem( $text );
3023 # Escape nowiki-style return values
3024 elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3025 $text = wfEscapeWikiText( $text );
3027 # Bug 529: if the template begins with a table or block-level
3028 # element, it should be treated as beginning a new line.
3029 # This behaviour is somewhat controversial.
3030 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3031 $text = "\n" . $text;
3034 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3035 # Error, oversize inclusion
3036 $text = "[[$originalTitle]]" .
3037 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3038 $this->limitationWarn( 'post-expand-template-inclusion' );
3041 if ( $isLocalObj ) {
3042 $ret = array( 'object' => $text );
3044 $ret = array( 'text' => $text );
3047 wfProfileOut( __METHOD__
);
3052 * Get the semi-parsed DOM representation of a template with a given title,
3053 * and its redirect destination title. Cached.
3055 function getTemplateDom( $title ) {
3056 $cacheTitle = $title;
3057 $titleText = $title->getPrefixedDBkey();
3059 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3060 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3061 $title = Title
::makeTitle( $ns, $dbk );
3062 $titleText = $title->getPrefixedDBkey();
3064 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3065 return array( $this->mTplDomCache
[$titleText], $title );
3068 // Cache miss, go to the database
3069 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3071 if ( $text === false ) {
3072 $this->mTplDomCache
[$titleText] = false;
3073 return array( false, $title );
3076 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3077 $this->mTplDomCache
[ $titleText ] = $dom;
3079 if (! $title->equals($cacheTitle)) {
3080 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3081 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3084 return array( $dom, $title );
3088 * Fetch the unparsed text of a template and register a reference to it.
3090 function fetchTemplateAndTitle( $title ) {
3091 $templateCb = $this->mOptions
->getTemplateCallback();
3092 $stuff = call_user_func( $templateCb, $title, $this );
3093 $text = $stuff['text'];
3094 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3095 if ( isset( $stuff['deps'] ) ) {
3096 foreach ( $stuff['deps'] as $dep ) {
3097 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3100 return array($text,$finalTitle);
3103 function fetchTemplate( $title ) {
3104 $rv = $this->fetchTemplateAndTitle($title);
3109 * Static function to get a template
3110 * Can be overridden via ParserOptions::setTemplateCallback().
3112 static function statelessFetchTemplate( $title, $parser=false ) {
3113 $text = $skip = false;
3114 $finalTitle = $title;
3117 // Loop to fetch the article, with up to 1 redirect
3118 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3119 # Give extensions a chance to select the revision instead
3120 $id = false; // Assume current
3121 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3127 'page_id' => $title->getArticleID(),
3131 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3132 $rev_id = $rev ?
$rev->getId() : 0;
3133 // If there is no current revision, there is no page
3134 if( $id === false && !$rev ) {
3135 $linkCache = LinkCache
::singleton();
3136 $linkCache->addBadLinkObj( $title );
3141 'page_id' => $title->getArticleID(),
3142 'rev_id' => $rev_id );
3145 $text = $rev->getText();
3146 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3148 $message = $wgContLang->lcfirst( $title->getText() );
3149 $text = wfMsgForContentNoTrans( $message );
3150 if( wfEmptyMsg( $message, $text ) ) {
3157 if ( $text === false ) {
3161 $finalTitle = $title;
3162 $title = Title
::newFromRedirect( $text );
3166 'finalTitle' => $finalTitle,
3171 * Transclude an interwiki link.
3173 function interwikiTransclude( $title, $action ) {
3174 global $wgEnableScaryTranscluding;
3176 if (!$wgEnableScaryTranscluding)
3177 return wfMsg('scarytranscludedisabled');
3179 $url = $title->getFullUrl( "action=$action" );
3181 if (strlen($url) > 255)
3182 return wfMsg('scarytranscludetoolong');
3183 return $this->fetchScaryTemplateMaybeFromCache($url);
3186 function fetchScaryTemplateMaybeFromCache($url) {
3187 global $wgTranscludeCacheExpiry;
3188 $dbr = wfGetDB(DB_SLAVE
);
3189 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3190 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3191 array('tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3193 return $obj->tc_contents
;
3196 $text = Http
::get($url);
3198 return wfMsg('scarytranscludefailed', $url);
3200 $dbw = wfGetDB(DB_MASTER
);
3201 $dbw->replace('transcache', array('tc_url'), array(
3203 'tc_time' => $dbw->timestamp( time() ),
3204 'tc_contents' => $text));
3210 * Triple brace replacement -- used for template arguments
3213 function argSubstitution( $piece, $frame ) {
3214 wfProfileIn( __METHOD__
);
3217 $parts = $piece['parts'];
3218 $nameWithSpaces = $frame->expand( $piece['title'] );
3219 $argName = trim( $nameWithSpaces );
3221 $text = $frame->getArgument( $argName );
3222 if ( $text === false && $parts->getLength() > 0
3226 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3229 # No match in frame, use the supplied default
3230 $object = $parts->item( 0 )->getChildren();
3232 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3233 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3234 $this->limitationWarn( 'post-expand-template-argument' );
3237 if ( $text === false && $object === false ) {
3239 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3241 if ( $error !== false ) {
3244 if ( $object !== false ) {
3245 $ret = array( 'object' => $object );
3247 $ret = array( 'text' => $text );
3250 wfProfileOut( __METHOD__
);
3255 * Return the text to be used for a given extension tag.
3256 * This is the ghost of strip().
3258 * @param array $params Associative array of parameters:
3259 * name PPNode for the tag name
3260 * attr PPNode for unparsed text where tag attributes are thought to be
3261 * attributes Optional associative array of parsed attributes
3262 * inner Contents of extension element
3263 * noClose Original text did not have a close tag
3264 * @param PPFrame $frame
3266 function extensionSubstitution( $params, $frame ) {
3267 global $wgRawHtml, $wgContLang;
3269 $name = $frame->expand( $params['name'] );
3270 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3271 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3273 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3275 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3276 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3277 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3278 $name = strtolower( $name );
3279 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3280 if ( isset( $params['attributes'] ) ) {
3281 $attributes = $attributes +
$params['attributes'];
3289 throw new MWException( '<html> extension tag encountered unexpectedly' );
3292 $content = strtr($content, array('-{' => '-{', '}-' => '}-'));
3293 $output = Xml
::escapeTagsOnly( $content );
3296 $output = $this->renderImageGallery( $content, $attributes );
3299 $output = $this->renderHyperlink( $content, $attributes, $frame );
3302 if ( $this->mOptions
->getUseTeX() ) {
3303 $output = $wgContLang->armourMath(
3304 MathRenderer
::renderMath( $content, $attributes ) );
3307 /* else let a tag hook handle it (bug 21222) */
3309 if( isset( $this->mTagHooks
[$name] ) ) {
3310 # Workaround for PHP bug 35229 and similar
3311 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3312 throw new MWException( "Tag hook for $name is not callable\n" );
3314 $output = call_user_func_array( $this->mTagHooks
[$name],
3315 array( $content, $attributes, $this, $frame ) );
3316 } elseif( isset( $this->mFunctionTagHooks
[$name] ) ) {
3317 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3318 if( !is_callable( $callback ) )
3319 throw new MWException( "Tag hook for $name is not callable\n" );
3321 $output = call_user_func_array( $callback,
3322 array( &$this, $frame, $content, $attributes ) );
3324 $output = '<span class="error">Invalid tag extension name: ' .
3325 htmlspecialchars( $name ) . '</span>';
3329 if ( is_null( $attrText ) ) {
3332 if ( isset( $params['attributes'] ) ) {
3333 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3334 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3335 htmlspecialchars( $attrValue ) . '"';
3338 if ( $content === null ) {
3339 $output = "<$name$attrText/>";
3341 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3342 $output = "<$name$attrText>$content$close";
3346 if( $isFunctionTag ) {
3348 } elseif ( $name === 'html' ||
$name === 'nowiki' ) {
3349 $this->mStripState
->nowiki
->setPair( $marker, $output );
3351 $this->mStripState
->general
->setPair( $marker, $output );
3357 * Increment an include size counter
3359 * @param string $type The type of expansion
3360 * @param integer $size The size of the text
3361 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3363 function incrementIncludeSize( $type, $size ) {
3364 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3367 $this->mIncludeSizes
[$type] +
= $size;
3373 * Increment the expensive function count
3375 * @return boolean False if the limit has been exceeded
3377 function incrementExpensiveFunctionCount() {
3378 global $wgExpensiveParserFunctionLimit;
3379 $this->mExpensiveFunctionCount++
;
3380 if($this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit) {
3387 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3388 * Fills $this->mDoubleUnderscores, returns the modified text
3390 function doDoubleUnderscore( $text ) {
3391 global $wgDisableLangConversion;
3392 wfProfileIn( __METHOD__
);
3394 // The position of __TOC__ needs to be recorded
3395 $mw = MagicWord
::get( 'toc' );
3396 if( $mw->match( $text ) ) {
3397 $this->mShowToc
= true;
3398 $this->mForceTocPosition
= true;
3400 // Set a placeholder. At the end we'll fill it in with the TOC.
3401 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3403 // Only keep the first one.
3404 $text = $mw->replace( '', $text );
3407 // Now match and remove the rest of them
3408 $mwa = MagicWord
::getDoubleUnderscoreArray();
3409 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3411 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3412 $this->mOutput
->mNoGallery
= true;
3414 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3415 $this->mShowToc
= false;
3417 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3418 $this->mOutput
->setProperty( 'hiddencat', 'y' );
3419 $this->addTrackingCategory( 'hidden-category-category' );
3421 # (bug 8068) Allow control over whether robots index a page.
3423 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3424 # is not desirable, the last one on the page should win.
3425 if( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3426 $this->mOutput
->setIndexPolicy( 'noindex' );
3427 $this->addTrackingCategory( 'noindex-category' );
3429 if( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ){
3430 $this->mOutput
->setIndexPolicy( 'index' );
3431 $this->addTrackingCategory( 'index-category' );
3434 if ( !$wgDisableLangConversion ) {
3435 if( isset( $this->mDoubleUnderscores
['notitleconvert'] ) ){
3436 $this->mDoTitleConvert
= false;
3439 // Don't convert talk pages
3440 if( isset( $this->mDoubleUnderscores
['nocontentconvert'] )
3441 && !$this->mTitle
->isTalkPage() ){
3442 $this->mDoContentConvert
= false;
3446 wfProfileOut( __METHOD__
);
3451 * Add a tracking category, getting the title from a system message,
3452 * or print a debug message if the title is invalid.
3453 * @param $msg String message key
3454 * @return Bool whether the addition was successful
3456 protected function addTrackingCategory( $msg ){
3457 $cat = wfMsgForContent( $msg );
3459 # Allow tracking categories to be disabled by setting them to "-"
3460 if( $cat === '-' ) return false;
3462 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3463 if ( $containerCategory ) {
3464 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3467 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3473 * This function accomplishes several tasks:
3474 * 1) Auto-number headings if that option is enabled
3475 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3476 * 3) Add a Table of contents on the top for users who have enabled the option
3477 * 4) Auto-anchor headings
3479 * It loops through all headlines, collects the necessary data, then splits up the
3480 * string and re-inserts the newly formatted headlines.
3482 * @param string $text
3483 * @param string $origText Original, untouched wikitext
3484 * @param boolean $isMain
3487 function formatHeadings( $text, $origText, $isMain=true ) {
3488 global $wgMaxTocLevel, $wgContLang, $wgEnforceHtmlIds;
3490 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3491 $showEditLink = $this->mOptions
->getEditSection();
3493 // Do not call quickUserCan unless necessary
3494 if( $showEditLink && !$this->mTitle
->quickUserCan( 'edit' ) ) {
3498 # Inhibit editsection links if requested in the page
3499 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ||
$this->mOptions
->getIsPrintable() ) {
3503 # Get all headlines for numbering them and adding funky stuff like [edit]
3504 # links - this is for later, but we need the number of headlines right now
3506 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3508 # if there are fewer than 4 headlines in the article, do not show TOC
3509 # unless it's been explicitly enabled.
3510 $enoughToc = $this->mShowToc
&&
3511 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3513 # Allow user to stipulate that a page should have a "new section"
3514 # link added via __NEWSECTIONLINK__
3515 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3516 $this->mOutput
->setNewSection( true );
3519 # Allow user to remove the "new section"
3520 # link via __NONEWSECTIONLINK__
3521 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3522 $this->mOutput
->hideNewSection( true );
3525 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3526 # override above conditions and always show TOC above first header
3527 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3528 $this->mShowToc
= true;
3532 # We need this to perform operations on the HTML
3533 $sk = $this->mOptions
->getSkin();
3539 # Ugh .. the TOC should have neat indentation levels which can be
3540 # passed to the skin functions. These are determined here
3544 $sublevelCount = array();
3545 $levelCount = array();
3551 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3552 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3553 $oldType = $this->mOutputType
;
3554 $this->setOutputType( self
::OT_WIKI
);
3555 $frame = $this->getPreprocessor()->newFrame();
3556 $root = $this->preprocessToDom( $origText );
3557 $node = $root->getFirstChild();
3561 foreach( $matches[3] as $headline ) {
3562 $isTemplate = false;
3564 $sectionIndex = false;
3566 $markerMatches = array();
3567 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3568 $serial = $markerMatches[1];
3569 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3570 $isTemplate = ($titleText != $baseTitleText);
3571 $headline = preg_replace("/^$markerRegex/", "", $headline);
3575 $prevlevel = $level;
3576 $prevtoclevel = $toclevel;
3578 $level = $matches[1][$headlineCount];
3580 if ( $level > $prevlevel ) {
3581 # Increase TOC level
3583 $sublevelCount[$toclevel] = 0;
3584 if( $toclevel<$wgMaxTocLevel ) {
3585 $prevtoclevel = $toclevel;
3586 $toc .= $sk->tocIndent();
3590 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3591 # Decrease TOC level, find level to jump to
3593 for ($i = $toclevel; $i > 0; $i--) {
3594 if ( $levelCount[$i] == $level ) {
3595 # Found last matching level
3599 elseif ( $levelCount[$i] < $level ) {
3600 # Found first matching level below current level
3605 if( $i == 0 ) $toclevel = 1;
3606 if( $toclevel<$wgMaxTocLevel ) {
3607 if($prevtoclevel < $wgMaxTocLevel) {
3608 # Unindent only if the previous toc level was shown :p
3609 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3610 $prevtoclevel = $toclevel;
3612 $toc .= $sk->tocLineEnd();
3617 # No change in level, end TOC line
3618 if( $toclevel<$wgMaxTocLevel ) {
3619 $toc .= $sk->tocLineEnd();
3623 $levelCount[$toclevel] = $level;
3625 # count number of headlines for each level
3626 @$sublevelCount[$toclevel]++
;
3628 for( $i = 1; $i <= $toclevel; $i++
) {
3629 if( !empty( $sublevelCount[$i] ) ) {
3633 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3638 # The safe header is a version of the header text safe to use for links
3639 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3640 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3642 # Remove link placeholders by the link text.
3643 # <!--LINK number-->
3645 # link text with suffix
3646 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3648 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3649 $tocline = preg_replace(
3650 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3654 $tocline = trim( $tocline );
3656 # For the anchor, strip out HTML-y stuff period
3657 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3658 $safeHeadline = preg_replace( '/[ _]+/', ' ', $safeHeadline );
3659 $safeHeadline = trim( $safeHeadline );
3661 # Save headline for section edit hint before it's escaped
3662 $headlineHint = $safeHeadline;
3664 if ( $wgEnforceHtmlIds ) {
3665 $legacyHeadline = false;
3666 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
3669 # For reverse compatibility, provide an id that's
3670 # HTML4-compatible, like we used to.
3672 # It may be worth noting, academically, that it's possible for
3673 # the legacy anchor to conflict with a non-legacy headline
3674 # anchor on the page. In this case likely the "correct" thing
3675 # would be to either drop the legacy anchors or make sure
3676 # they're numbered first. However, this would require people
3677 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3678 # manually, so let's not bother worrying about it.
3679 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
3681 $safeHeadline = Sanitizer
::escapeId( $safeHeadline, 'xml' );
3683 if ( $legacyHeadline == $safeHeadline ) {
3684 # No reason to have both (in fact, we can't)
3685 $legacyHeadline = false;
3686 } elseif ( $legacyHeadline != Sanitizer
::escapeId(
3687 $legacyHeadline, 'xml' ) ) {
3688 # The legacy id is invalid XML. We used to allow this, but
3689 # there's no reason to do so anymore. Backward
3690 # compatibility will fail slightly in this case, but it's
3692 $legacyHeadline = false;
3696 # HTML names must be case-insensitively unique (bug 10721). FIXME:
3697 # Does this apply to Unicode characters? Because we aren't
3698 # handling those here.
3699 $arrayKey = strtolower( $safeHeadline );
3700 if ( $legacyHeadline === false ) {
3701 $legacyArrayKey = false;
3703 $legacyArrayKey = strtolower( $legacyHeadline );
3706 # count how many in assoc. array so we can track dupes in anchors
3707 if ( isset( $refers[$arrayKey] ) ) {
3708 $refers[$arrayKey]++
;
3710 $refers[$arrayKey] = 1;
3712 if ( isset( $refers[$legacyArrayKey] ) ) {
3713 $refers[$legacyArrayKey]++
;
3715 $refers[$legacyArrayKey] = 1;
3718 # Don't number the heading if it is the only one (looks silly)
3719 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3720 # the two are different if the line contains a link
3721 $headline=$numbering . ' ' . $headline;
3724 # Create the anchor for linking from the TOC to the section
3725 $anchor = $safeHeadline;
3726 $legacyAnchor = $legacyHeadline;
3727 if ( $refers[$arrayKey] > 1 ) {
3728 $anchor .= '_' . $refers[$arrayKey];
3730 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3731 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3733 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3734 $toc .= $sk->tocLine($anchor, $tocline,
3735 $numbering, $toclevel, ($isTemplate ?
false : $sectionIndex));
3738 # Add the section to the section tree
3739 # Find the DOM node for this header
3740 while ( $node && !$isTemplate ) {
3741 if ( $node->getName() === 'h' ) {
3742 $bits = $node->splitHeading();
3743 if ( $bits['i'] == $sectionIndex )
3746 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
3747 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
3748 $node = $node->getNextSibling();
3751 'toclevel' => $toclevel,
3754 'number' => $numbering,
3755 'index' => ($isTemplate ?
'T-' : '' ) . $sectionIndex,
3756 'fromtitle' => $titleText,
3757 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
3758 'anchor' => $anchor,
3761 # give headline the correct <h#> tag
3762 if( $showEditLink && $sectionIndex !== false ) {
3764 # Put a T flag in the section identifier, to indicate to extractSections()
3765 # that sections inside <includeonly> should be counted.
3766 $editlink = $sk->doEditSectionLink(Title
::newFromText( $titleText ), "T-$sectionIndex");
3768 $editlink = $sk->doEditSectionLink($this->mTitle
, $sectionIndex, $headlineHint);
3773 $head[$headlineCount] = $sk->makeHeadline( $level,
3774 $matches['attrib'][$headlineCount], $anchor, $headline,
3775 $editlink, $legacyAnchor );
3780 $this->setOutputType( $oldType );
3782 # Never ever show TOC if no headers
3783 if( $numVisible < 1 ) {
3788 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3789 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3791 $toc = $sk->tocList( $toc );
3792 $this->mOutput
->setTOCHTML( $toc );
3796 $this->mOutput
->setSections( $tocraw );
3799 # split up and insert constructed headlines
3801 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3804 foreach( $blocks as $block ) {
3805 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3806 # This is the [edit] link that appears for the top block of text when
3807 # section editing is enabled
3809 # Disabled because it broke block formatting
3810 # For example, a bullet point in the top line
3811 # $full .= $sk->editSectionLink(0);
3814 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3815 # Top anchor now in skin
3819 if( !empty( $head[$i] ) ) {
3824 if( $this->mForceTocPosition
) {
3825 return str_replace( '<!--MWTOC-->', $toc, $full );
3832 * Merge $tree2 into $tree1 by replacing the section with index
3833 * $section in $tree1 and its descendants with the sections in $tree2.
3834 * Note that in the returned section tree, only the 'index' and
3835 * 'byteoffset' fields are guaranteed to be correct.
3836 * @param $tree1 array Section tree from ParserOutput::getSectons()
3837 * @param $tree2 array Section tree
3838 * @param $section int Section index
3839 * @param $title Title Title both section trees come from
3840 * @param $len2 int Length of the original wikitext for $tree2
3841 * @return array Merged section tree
3843 public static function mergeSectionTrees( $tree1, $tree2, $section, $title, $len2 ) {
3846 $targetLevel = false;
3850 $numbering = array( 0 );
3851 $titletext = $title->getPrefixedDBkey();
3852 foreach ( $tree1 as $s ) {
3853 if ( $targetLevel !== false ) {
3854 if ( $s['level'] <= $targetLevel )
3855 // We've skipped enough
3856 $targetLevel = false;
3860 if ( $s['index'] != $section ||
3861 $s['fromtitle'] != $titletext ) {
3862 self
::incrementNumbering( $numbering,
3863 $s['toclevel'], $lastLevel );
3865 // Rewrite index, byteoffset and number
3866 if ( $s['fromtitle'] == $titletext ) {
3867 $s['index'] = $nextIndex++
;
3869 $s['byteoffset'] +
= $len2;
3871 $s['number'] = implode( '.', array_map(
3872 array( $wgContLang, 'formatnum' ),
3874 $lastLevel = $s['toclevel'];
3877 // We're at $section
3878 // Insert sections from $tree2 here
3879 foreach ( $tree2 as $s2 ) {
3880 // Rewrite the fields in $s2
3881 // before inserting it
3882 $s2['toclevel'] +
= $s['toclevel'] - 1;
3883 $s2['level'] +
= $s['level'] - 1;
3884 $s2['index'] = $nextIndex++
;
3885 $s2['byteoffset'] +
= $s['byteoffset'];
3887 self
::incrementNumbering( $numbering,
3888 $s2['toclevel'], $lastLevel );
3889 $s2['number'] = implode( '.', array_map(
3890 array( $wgContLang, 'formatnum' ),
3892 $lastLevel = $s2['toclevel'];
3895 // Skip all descendants of $section in $tree1
3896 $targetLevel = $s['level'];
3904 * Increment a section number. Helper function for mergeSectionTrees()
3905 * @param $number array Array representing a section number
3906 * @param $level int Current TOC level (depth)
3907 * @param $lastLevel int Level of previous TOC entry
3909 private static function incrementNumbering( &$number, $level, $lastLevel ) {
3910 if ( $level > $lastLevel )
3911 $number[$level - 1] = 1;
3912 else if ( $level < $lastLevel ) {
3913 foreach ( $number as $key => $unused )
3914 if ( $key >= $level )
3915 unset( $number[$key] );
3916 $number[$level - 1]++
;
3918 $number[$level - 1]++
;
3922 * Transform wiki markup when saving a page by doing \r\n -> \n
3923 * conversion, substitting signatures, {{subst:}} templates, etc.
3925 * @param string $text the text to transform
3926 * @param Title &$title the Title object for the current article
3927 * @param User $user the User object describing the current user
3928 * @param ParserOptions $options parsing options
3929 * @param bool $clearState whether to clear the parser state first
3930 * @return string the altered wiki markup
3933 function preSaveTransform( $text, Title
$title, $user, $options, $clearState = true ) {
3934 $this->mOptions
= $options;
3935 $this->setTitle( $title );
3936 $this->setOutputType( self
::OT_WIKI
);
3938 if ( $clearState ) {
3939 $this->clearState();
3945 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3946 $text = $this->pstPass2( $text, $user );
3947 $text = $this->mStripState
->unstripBoth( $text );
3952 * Pre-save transform helper function
3955 function pstPass2( $text, $user ) {
3956 global $wgContLang, $wgLocaltimezone;
3958 /* Note: This is the timestamp saved as hardcoded wikitext to
3959 * the database, we use $wgContLang here in order to give
3960 * everyone the same signature and use the default one rather
3961 * than the one selected in each user's preferences.
3963 * (see also bug 12815)
3965 $ts = $this->mOptions
->getTimestamp();
3966 if ( isset( $wgLocaltimezone ) ) {
3967 $tz = $wgLocaltimezone;
3969 $tz = date_default_timezone_get();
3972 $unixts = wfTimestamp( TS_UNIX
, $ts );
3973 $oldtz = date_default_timezone_get();
3974 date_default_timezone_set( $tz );
3975 $ts = date( 'YmdHis', $unixts );
3976 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
3978 /* Allow translation of timezones trough wiki. date() can return
3979 * whatever crap the system uses, localised or not, so we cannot
3980 * ship premade translations.
3982 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
3983 $value = wfMsgForContent( $key );
3984 if ( !wfEmptyMsg( $key, $value ) ) $tzMsg = $value;
3986 date_default_timezone_set( $oldtz );
3988 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
3990 # Variable replacement
3991 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
3992 $text = $this->replaceVariables( $text );
3995 $sigText = $this->getUserSig( $user );
3996 $text = strtr( $text, array(
3998 '~~~~' => "$sigText $d",
4002 # Context links: [[|name]] and [[name (context)|]]
4004 global $wgLegalTitleChars;
4005 $tc = "[$wgLegalTitleChars]";
4006 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4008 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4009 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
4010 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4011 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4013 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4014 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4015 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4016 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4018 $t = $this->mTitle
->getText();
4020 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4021 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4022 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4023 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4025 # if there's no context, don't bother duplicating the title
4026 $text = preg_replace( $p2, '[[\\1]]', $text );
4029 # Trim trailing whitespace
4030 $text = rtrim( $text );
4036 * Fetch the user's signature text, if any, and normalize to
4037 * validated, ready-to-insert wikitext.
4038 * If you have pre-fetched the nickname or the fancySig option, you can
4039 * specify them here to save a database query.
4044 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4045 global $wgMaxSigChars;
4047 $username = $user->getName();
4049 // If not given, retrieve from the user object.
4050 if ( $nickname === false )
4051 $nickname = $user->getOption( 'nickname' );
4053 if ( is_null( $fancySig ) )
4054 $fancySig = $user->getBoolOption( 'fancysig' );
4056 $nickname = $nickname == null ?
$username : $nickname;
4058 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4059 $nickname = $username;
4060 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4061 } elseif( $fancySig !== false ) {
4062 # Sig. might contain markup; validate this
4063 if( $this->validateSig( $nickname ) !== false ) {
4064 # Validated; clean up (if needed) and return it
4065 return $this->cleanSig( $nickname, true );
4067 # Failed to validate; fall back to the default
4068 $nickname = $username;
4069 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4073 // Make sure nickname doesnt get a sig in a sig
4074 $nickname = $this->cleanSigInSig( $nickname );
4076 # If we're still here, make it a link to the user page
4077 $userText = wfEscapeWikiText( $username );
4078 $nickText = wfEscapeWikiText( $nickname );
4079 if ( $user->isAnon() ) {
4080 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4082 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4087 * Check that the user's signature contains no bad XML
4089 * @param string $text
4090 * @return mixed An expanded string, or false if invalid.
4092 function validateSig( $text ) {
4093 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4097 * Clean up signature text
4099 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4100 * 2) Substitute all transclusions
4102 * @param string $text
4103 * @param $parsing Whether we're cleaning (preferences save) or parsing
4104 * @return string Signature text
4106 function cleanSig( $text, $parsing = false ) {
4109 $this->clearState();
4110 $this->setTitle( $wgTitle );
4111 $this->mOptions
= new ParserOptions
;
4112 $this->setOutputType
= self
::OT_PREPROCESS
;
4115 # Option to disable this feature
4116 if ( !$this->mOptions
->getCleanSignatures() ) {
4120 # FIXME: regex doesn't respect extension tags or nowiki
4121 # => Move this logic to braceSubstitution()
4122 $substWord = MagicWord
::get( 'subst' );
4123 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4124 $substText = '{{' . $substWord->getSynonym( 0 );
4126 $text = preg_replace( $substRegex, $substText, $text );
4127 $text = $this->cleanSigInSig( $text );
4128 $dom = $this->preprocessToDom( $text );
4129 $frame = $this->getPreprocessor()->newFrame();
4130 $text = $frame->expand( $dom );
4133 $text = $this->mStripState
->unstripBoth( $text );
4140 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4141 * @param string $text
4142 * @return string Signature text with /~{3,5}/ removed
4144 function cleanSigInSig( $text ) {
4145 $text = preg_replace( '/~{3,5}/', '', $text );
4150 * Set up some variables which are usually set up in parse()
4151 * so that an external function can call some class members with confidence
4154 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
4155 $this->setTitle( $title );
4156 $this->mOptions
= $options;
4157 $this->setOutputType( $outputType );
4158 if ( $clearState ) {
4159 $this->clearState();
4164 * Wrapper for preprocess()
4166 * @param string $text the text to preprocess
4167 * @param ParserOptions $options options
4171 function transformMsg( $text, $options ) {
4173 static $executing = false;
4175 # Guard against infinite recursion
4181 wfProfileIn(__METHOD__
);
4182 $text = $this->preprocess( $text, $wgTitle, $options );
4185 wfProfileOut(__METHOD__
);
4190 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4191 * The callback should have the following form:
4192 * function myParserHook( $text, $params, &$parser ) { ... }
4194 * Transform and return $text. Use $parser for any required context, e.g. use
4195 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4199 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
4200 * @param mixed $callback The callback function (and object) to use for the tag
4202 * @return The old value of the mTagHooks array associated with the hook
4204 function setHook( $tag, $callback ) {
4205 $tag = strtolower( $tag );
4206 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4207 $this->mTagHooks
[$tag] = $callback;
4208 if( !in_array( $tag, $this->mStripList
) ) {
4209 $this->mStripList
[] = $tag;
4215 function setTransparentTagHook( $tag, $callback ) {
4216 $tag = strtolower( $tag );
4217 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4218 $this->mTransparentTagHooks
[$tag] = $callback;
4224 * Remove all tag hooks
4226 function clearTagHooks() {
4227 $this->mTagHooks
= array();
4228 $this->mStripList
= $this->mDefaultStripList
;
4232 * Create a function, e.g. {{sum:1|2|3}}
4233 * The callback function should have the form:
4234 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4236 * Or with SFH_OBJECT_ARGS:
4237 * function myParserFunction( $parser, $frame, $args ) { ... }
4239 * The callback may either return the text result of the function, or an array with the text
4240 * in element 0, and a number of flags in the other elements. The names of the flags are
4241 * specified in the keys. Valid flags are:
4242 * found The text returned is valid, stop processing the template. This
4244 * nowiki Wiki markup in the return value should be escaped
4245 * isHTML The returned text is HTML, armour it against wikitext transformation
4249 * @param string $id The magic word ID
4250 * @param mixed $callback The callback function (and object) to use
4251 * @param integer $flags a combination of the following flags:
4252 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4254 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4255 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4256 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4257 * the arguments, and to control the way they are expanded.
4259 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4260 * arguments, for instance:
4261 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4263 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4264 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4265 * working if/when this is changed.
4267 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4270 * Please read the documentation in includes/parser/Preprocessor.php for more information
4271 * about the methods available in PPFrame and PPNode.
4273 * @return The old callback function for this name, if any
4275 function setFunctionHook( $id, $callback, $flags = 0 ) {
4278 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4279 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4281 # Add to function cache
4282 $mw = MagicWord
::get( $id );
4284 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4286 $synonyms = $mw->getSynonyms();
4287 $sensitive = intval( $mw->isCaseSensitive() );
4289 foreach ( $synonyms as $syn ) {
4291 if ( !$sensitive ) {
4292 $syn = $wgContLang->lc( $syn );
4295 if ( !( $flags & SFH_NO_HASH
) ) {
4298 # Remove trailing colon
4299 if ( substr( $syn, -1, 1 ) === ':' ) {
4300 $syn = substr( $syn, 0, -1 );
4302 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4308 * Get all registered function hook identifiers
4312 function getFunctionHooks() {
4313 return array_keys( $this->mFunctionHooks
);
4317 * Create a tag function, e.g. <test>some stuff</test>.
4318 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4319 * Unlike parser functions, their content is not preprocessed.
4321 function setFunctionTagHook( $tag, $callback, $flags ) {
4322 $tag = strtolower( $tag );
4323 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4324 $this->mFunctionTagHooks
[$tag] : null;
4325 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4327 if( !in_array( $tag, $this->mStripList
) ) {
4328 $this->mStripList
[] = $tag;
4335 * FIXME: update documentation. makeLinkObj() is deprecated.
4336 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4337 * Placeholders created in Skin::makeLinkObj()
4338 * Returns an array of link CSS classes, indexed by PDBK.
4340 function replaceLinkHolders( &$text, $options = 0 ) {
4341 return $this->mLinkHolders
->replace( $text );
4345 * Replace <!--LINK--> link placeholders with plain text of links
4346 * (not HTML-formatted).
4347 * @param string $text
4350 function replaceLinkHoldersText( $text ) {
4351 return $this->mLinkHolders
->replaceText( $text );
4355 * Tag hook handler for 'pre'.
4357 function renderPreTag( $text, $attribs ) {
4358 // Backwards-compatibility hack
4359 $content = StringUtils
::delimiterReplace( '<nowiki>', '</nowiki>', '$1', $text, 'i' );
4361 $attribs = Sanitizer
::validateTagAttributes( $attribs, 'pre' );
4362 return Xml
::openElement( 'pre', $attribs ) .
4363 Xml
::escapeTagsOnly( $content ) .
4368 * Tag hook handler for 'a'. Renders a HTML <a> tag, allowing most attributes, filtering href against
4369 * allowed protocols and spam blacklist.
4371 function renderHyperlink( $text, $params, $frame = false ) {
4372 foreach ( $params as $name => $value ) {
4373 $params[ $name ] = $this->replaceVariables( $value, $frame );
4376 $whitelist = Sanitizer
::attributeWhitelist( 'a' );
4377 $params = Sanitizer
::validateAttributes( $params, $whitelist );
4379 $content = $this->recursiveTagParse( trim( $text ), $frame );
4381 if ( isset( $params[ 'href' ] ) ) {
4382 $href = $params[ 'href' ];
4383 $this->mOutput
->addExternalLink( $href );
4384 unset( $params[ 'href' ] );
4387 return Xml
::openElement( 'a', $params ) . $content . Xml
::closeElement( 'a' );
4390 $sk = $this->mOptions
->getSkin();
4391 $html = $sk->makeExternalLink( $href, $content, false, '', $params );
4397 * Renders an image gallery from a text with one line per image.
4398 * text labels may be given by using |-style alternative text. E.g.
4399 * Image:one.jpg|The number "1"
4400 * Image:tree.jpg|A tree
4401 * given as text will return the HTML of a gallery with two images,
4402 * labeled 'The number "1"' and
4405 function renderImageGallery( $text, $params ) {
4406 $ig = new ImageGallery();
4407 $ig->setContextTitle( $this->mTitle
);
4408 $ig->setShowBytes( false );
4409 $ig->setShowFilename( false );
4410 $ig->setParser( $this );
4411 $ig->setHideBadImages();
4412 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4413 $ig->useSkin( $this->mOptions
->getSkin() );
4414 $ig->mRevisionId
= $this->mRevisionId
;
4416 if( isset( $params['caption'] ) ) {
4417 $caption = $params['caption'];
4418 $caption = htmlspecialchars( $caption );
4419 $caption = $this->replaceInternalLinks( $caption );
4420 $ig->setCaptionHtml( $caption );
4422 if( isset( $params['perrow'] ) ) {
4423 $ig->setPerRow( $params['perrow'] );
4425 if( isset( $params['widths'] ) ) {
4426 $ig->setWidths( $params['widths'] );
4428 if( isset( $params['heights'] ) ) {
4429 $ig->setHeights( $params['heights'] );
4432 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4434 $lines = StringUtils
::explode( "\n", $text );
4435 foreach ( $lines as $line ) {
4436 # match lines like these:
4437 # Image:someimage.jpg|This is some image
4439 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4441 if ( count( $matches ) == 0 ) {
4445 if ( strpos( $matches[0], '%' ) !== false )
4446 $matches[1] = urldecode( $matches[1] );
4447 $tp = Title
::newFromText( $matches[1]/*, NS_FILE*/ );
4449 if( is_null( $nt ) ) {
4450 # Bogus title. Ignore these so we don't bomb out later.
4453 if ( isset( $matches[3] ) ) {
4454 $label = $matches[3];
4459 $html = $this->recursiveTagParse( trim( $label ) );
4461 $ig->add( $nt, $html );
4463 # Only add real images (bug #5586)
4464 if ( $nt->getNamespace() == NS_FILE
) {
4465 $this->mOutput
->addImage( $nt->getDBkey() );
4468 return $ig->toHTML();
4471 function getImageParams( $handler ) {
4473 $handlerClass = get_class( $handler );
4477 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4478 // Initialise static lists
4479 static $internalParamNames = array(
4480 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4481 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4482 'bottom', 'text-bottom' ),
4483 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4484 'upright', 'border', 'link', 'alt' ),
4486 static $internalParamMap;
4487 if ( !$internalParamMap ) {
4488 $internalParamMap = array();
4489 foreach ( $internalParamNames as $type => $names ) {
4490 foreach ( $names as $name ) {
4491 $magicName = str_replace( '-', '_', "img_$name" );
4492 $internalParamMap[$magicName] = array( $type, $name );
4497 // Add handler params
4498 $paramMap = $internalParamMap;
4500 $handlerParamMap = $handler->getParamMap();
4501 foreach ( $handlerParamMap as $magic => $paramName ) {
4502 $paramMap[$magic] = array( 'handler', $paramName );
4505 $this->mImageParams
[$handlerClass] = $paramMap;
4506 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4508 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4512 * Parse image options text and use it to make an image
4513 * @param Title $title
4514 * @param string $options
4515 * @param LinkHolderArray $holders
4517 function makeImage( $title, $options, $holders = false ) {
4518 # Check if the options text is of the form "options|alt text"
4520 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4521 # * left no resizing, just left align. label is used for alt= only
4522 # * right same, but right aligned
4523 # * none same, but not aligned
4524 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4525 # * center center the image
4526 # * frame Keep original image size, no magnify-button.
4527 # * framed Same as "frame"
4528 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4529 # * upright reduce width for upright images, rounded to full __0 px
4530 # * border draw a 1px border around the image
4531 # * alt Text for HTML alt attribute (defaults to empty)
4532 # * link Set the target of the image link. Can be external, interwiki, or local
4533 # vertical-align values (no % or length right now):
4543 $parts = StringUtils
::explode( "|", $options );
4544 $sk = $this->mOptions
->getSkin();
4546 # Give extensions a chance to select the file revision for us
4547 $skip = $time = $descQuery = false;
4548 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4551 return $sk->link( $title );
4555 $imagename = $title->getDBkey();
4556 $file = wfFindFile( $title, array( 'time' => $time ) );
4558 $handler = $file ?
$file->getHandler() : false;
4560 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4562 # Process the input parameters
4564 $params = array( 'frame' => array(), 'handler' => array(),
4565 'horizAlign' => array(), 'vertAlign' => array() );
4566 foreach( $parts as $part ) {
4567 $part = trim( $part );
4568 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4570 if( isset( $paramMap[$magicName] ) ) {
4571 list( $type, $paramName ) = $paramMap[$magicName];
4573 // Special case; width and height come in one variable together
4574 if( $type === 'handler' && $paramName === 'width' ) {
4576 # (bug 13500) In both cases (width/height and width only),
4577 # permit trailing "px" for backward compatibility.
4578 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4579 $width = intval( $m[1] );
4580 $height = intval( $m[2] );
4581 if ( $handler->validateParam( 'width', $width ) ) {
4582 $params[$type]['width'] = $width;
4585 if ( $handler->validateParam( 'height', $height ) ) {
4586 $params[$type]['height'] = $height;
4589 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4590 $width = intval( $value );
4591 if ( $handler->validateParam( 'width', $width ) ) {
4592 $params[$type]['width'] = $width;
4595 } // else no validation -- bug 13436
4597 if ( $type === 'handler' ) {
4598 # Validate handler parameter
4599 $validated = $handler->validateParam( $paramName, $value );
4601 # Validate internal parameters
4602 switch( $paramName ) {
4605 // @todo Fixme: possibly check validity here for
4606 // manualthumb? downstream behavior seems odd with
4607 // missing manual thumbs.
4609 $value = $this->stripAltText( $value, $holders );
4612 $chars = self
::EXT_LINK_URL_CLASS
;
4613 $prots = $this->mUrlProtocols
;
4614 if ( $value === '' ) {
4615 $paramName = 'no-link';
4618 } elseif ( preg_match( "/^$prots/", $value ) ) {
4619 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4620 $paramName = 'link-url';
4621 $this->mOutput
->addExternalLink( $value );
4625 $linkTitle = Title
::newFromText( $value );
4627 $paramName = 'link-title';
4628 $value = $linkTitle;
4629 $this->mOutput
->addLink( $linkTitle );
4635 // Most other things appear to be empty or numeric...
4636 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4641 $params[$type][$paramName] = $value;
4645 if ( !$validated ) {
4650 # Process alignment parameters
4651 if ( $params['horizAlign'] ) {
4652 $params['frame']['align'] = key( $params['horizAlign'] );
4654 if ( $params['vertAlign'] ) {
4655 $params['frame']['valign'] = key( $params['vertAlign'] );
4658 $params['frame']['caption'] = $caption;
4660 # Will the image be presented in a frame, with the caption below?
4661 $imageIsFramed = isset( $params['frame']['frame'] ) ||
4662 isset( $params['frame']['framed'] ) ||
4663 isset( $params['frame']['thumbnail'] ) ||
4664 isset( $params['frame']['manualthumb'] );
4666 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4667 # came to also set the caption, ordinary text after the image -- which
4668 # makes no sense, because that just repeats the text multiple times in
4669 # screen readers. It *also* came to set the title attribute.
4671 # Now that we have an alt attribute, we should not set the alt text to
4672 # equal the caption: that's worse than useless, it just repeats the
4673 # text. This is the framed/thumbnail case. If there's no caption, we
4674 # use the unnamed parameter for alt text as well, just for the time be-
4675 # ing, if the unnamed param is set and the alt param is not.
4677 # For the future, we need to figure out if we want to tweak this more,
4678 # e.g., introducing a title= parameter for the title; ignoring the un-
4679 # named parameter entirely for images without a caption; adding an ex-
4680 # plicit caption= parameter and preserving the old magic unnamed para-
4682 if ( $imageIsFramed ) { # Framed image
4683 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
4684 # No caption or alt text, add the filename as the alt text so
4685 # that screen readers at least get some description of the image
4686 $params['frame']['alt'] = $title->getText();
4688 # Do not set $params['frame']['title'] because tooltips don't make sense
4690 } else { # Inline image
4691 if ( !isset( $params['frame']['alt'] ) ) {
4692 # No alt text, use the "caption" for the alt text
4693 if ( $caption !== '') {
4694 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
4696 # No caption, fall back to using the filename for the
4698 $params['frame']['alt'] = $title->getText();
4701 # Use the "caption" for the tooltip text
4702 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4705 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4707 # Linker does the rest
4708 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4710 # Give the handler a chance to modify the parser object
4712 $handler->parserTransformHook( $this, $file );
4718 protected function stripAltText( $caption, $holders ) {
4719 # Strip bad stuff out of the title (tooltip). We can't just use
4720 # replaceLinkHoldersText() here, because if this function is called
4721 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4723 $tooltip = $holders->replaceText( $caption );
4725 $tooltip = $this->replaceLinkHoldersText( $caption );
4728 # make sure there are no placeholders in thumbnail attributes
4729 # that are later expanded to html- so expand them now and
4731 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
4732 $tooltip = Sanitizer
::stripAllTags( $tooltip );
4738 * Set a flag in the output object indicating that the content is dynamic and
4739 * shouldn't be cached.
4741 function disableCache() {
4742 wfDebug( "Parser output marked as uncacheable.\n" );
4743 $this->mOutput
->mCacheTime
= -1;
4747 * Callback from the Sanitizer for expanding items found in HTML attribute
4748 * values, so they can be safely tested and escaped.
4749 * @param string $text
4750 * @param PPFrame $frame
4754 function attributeStripCallback( &$text, $frame = false ) {
4755 $text = $this->replaceVariables( $text, $frame );
4756 $text = $this->mStripState
->unstripBoth( $text );
4765 function Title( $x = null ) { return wfSetVar( $this->mTitle
, $x ); }
4766 function Options( $x = null ) { return wfSetVar( $this->mOptions
, $x ); }
4767 function OutputType( $x = null ) { return wfSetVar( $this->mOutputType
, $x ); }
4773 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4778 * Break wikitext input into sections, and either pull or replace
4779 * some particular section's text.
4781 * External callers should use the getSection and replaceSection methods.
4783 * @param string $text Page wikitext
4784 * @param string $section A section identifier string of the form:
4785 * <flag1> - <flag2> - ... - <section number>
4787 * Currently the only recognised flag is "T", which means the target section number
4788 * was derived during a template inclusion parse, in other words this is a template
4789 * section edit link. If no flags are given, it was an ordinary section edit link.
4790 * This flag is required to avoid a section numbering mismatch when a section is
4791 * enclosed by <includeonly> (bug 6563).
4793 * The section number 0 pulls the text before the first heading; other numbers will
4794 * pull the given section along with its lower-level subsections. If the section is
4795 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4797 * @param string $mode One of "get" or "replace"
4798 * @param string $newText Replacement text for section data.
4799 * @return string for "get", the extracted section text.
4800 * for "replace", the whole page with the section replaced.
4802 private function extractSections( $text, $section, $mode, $newText='' ) {
4804 $this->clearState();
4805 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4806 $this->mOptions
= new ParserOptions
;
4807 $this->setOutputType( self
::OT_WIKI
);
4809 $frame = $this->getPreprocessor()->newFrame();
4811 // Process section extraction flags
4813 $sectionParts = explode( '-', $section );
4814 $sectionIndex = array_pop( $sectionParts );
4815 foreach ( $sectionParts as $part ) {
4816 if ( $part === 'T' ) {
4817 $flags |
= self
::PTD_FOR_INCLUSION
;
4820 // Preprocess the text
4821 $root = $this->preprocessToDom( $text, $flags );
4823 // <h> nodes indicate section breaks
4824 // They can only occur at the top level, so we can find them by iterating the root's children
4825 $node = $root->getFirstChild();
4827 // Find the target section
4828 if ( $sectionIndex == 0 ) {
4829 // Section zero doesn't nest, level=big
4830 $targetLevel = 1000;
4833 if ( $node->getName() === 'h' ) {
4834 $bits = $node->splitHeading();
4835 if ( $bits['i'] == $sectionIndex ) {
4836 $targetLevel = $bits['level'];
4840 if ( $mode === 'replace' ) {
4841 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4843 $node = $node->getNextSibling();
4849 if ( $mode === 'get' ) {
4856 // Find the end of the section, including nested sections
4858 if ( $node->getName() === 'h' ) {
4859 $bits = $node->splitHeading();
4860 $curLevel = $bits['level'];
4861 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4865 if ( $mode === 'get' ) {
4866 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4868 $node = $node->getNextSibling();
4871 // Write out the remainder (in replace mode only)
4872 if ( $mode === 'replace' ) {
4873 // Output the replacement text
4874 // Add two newlines on -- trailing whitespace in $newText is conventionally
4875 // stripped by the editor, so we need both newlines to restore the paragraph gap
4876 // Only add trailing whitespace if there is newText
4877 if($newText != "") {
4878 $outText .= $newText . "\n\n";
4882 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4883 $node = $node->getNextSibling();
4887 if ( is_string( $outText ) ) {
4888 // Re-insert stripped tags
4889 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4896 * This function returns the text of a section, specified by a number ($section).
4897 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4898 * the first section before any such heading (section 0).
4900 * If a section contains subsections, these are also returned.
4902 * @param string $text text to look in
4903 * @param string $section section identifier
4904 * @param string $deftext default to return if section is not found
4905 * @return string text of the requested section
4907 public function getSection( $text, $section, $deftext='' ) {
4908 return $this->extractSections( $text, $section, "get", $deftext );
4911 public function replaceSection( $oldtext, $section, $text ) {
4912 return $this->extractSections( $oldtext, $section, "replace", $text );
4916 * Get the timestamp associated with the current revision, adjusted for
4917 * the default server-local timestamp
4919 function getRevisionTimestamp() {
4920 if ( is_null( $this->mRevisionTimestamp
) ) {
4921 wfProfileIn( __METHOD__
);
4923 $dbr = wfGetDB( DB_SLAVE
);
4924 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4925 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4927 // Normalize timestamp to internal MW format for timezone processing.
4928 // This has the added side-effect of replacing a null value with
4929 // the current time, which gives us more sensible behavior for
4931 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4933 // The cryptic '' timezone parameter tells to use the site-default
4934 // timezone offset instead of the user settings.
4936 // Since this value will be saved into the parser cache, served
4937 // to other users, and potentially even used inside links and such,
4938 // it needs to be consistent for all visitors.
4939 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4941 wfProfileOut( __METHOD__
);
4943 return $this->mRevisionTimestamp
;
4947 * Get the name of the user that edited the last revision
4949 function getRevisionUser() {
4950 // if this template is subst: the revision id will be blank,
4951 // so just use the current user's name
4952 if( $this->mRevisionId
) {
4953 $revision = Revision
::newFromId( $this->mRevisionId
);
4954 $revuser = $revision->getUserText();
4957 $revuser = $wgUser->getName();
4963 * Mutator for $mDefaultSort
4965 * @param $sort New value
4967 public function setDefaultSort( $sort ) {
4968 $this->mDefaultSort
= $sort;
4972 * Accessor for $mDefaultSort
4973 * Will use the title/prefixed title if none is set
4977 public function getDefaultSort() {
4978 global $wgCategoryPrefixedDefaultSortkey;
4979 if( $this->mDefaultSort
!== false ) {
4980 return $this->mDefaultSort
;
4981 } elseif ($this->mTitle
->getNamespace() == NS_CATEGORY ||
4982 !$wgCategoryPrefixedDefaultSortkey) {
4983 return $this->mTitle
->getText();
4985 return $this->mTitle
->getPrefixedText();
4990 * Accessor for $mDefaultSort
4991 * Unlike getDefaultSort(), will return false if none is set
4993 * @return string or false
4995 public function getCustomDefaultSort() {
4996 return $this->mDefaultSort
;
5000 * Try to guess the section anchor name based on a wikitext fragment
5001 * presumably extracted from a heading, for example "Header" from
5004 public function guessSectionNameFromWikiText( $text ) {
5005 # Strip out wikitext links(they break the anchor)
5006 $text = $this->stripSectionName( $text );
5007 $headline = Sanitizer
::decodeCharReferences( $text );
5009 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
5010 $headline = trim( $headline );
5011 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
5012 $replacearray = array(
5017 array_keys( $replacearray ),
5018 array_values( $replacearray ),
5023 * Strips a text string of wikitext for use in a section anchor
5025 * Accepts a text string and then removes all wikitext from the
5026 * string and leaves only the resultant text (i.e. the result of
5027 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5028 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5029 * to create valid section anchors by mimicing the output of the
5030 * parser when headings are parsed.
5032 * @param $text string Text string to be stripped of wikitext
5033 * for use in a Section anchor
5034 * @return Filtered text string
5036 public function stripSectionName( $text ) {
5037 # Strip internal link markup
5038 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
5039 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
5041 # Strip external link markup (FIXME: Not Tolerant to blank link text
5042 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5043 # on how many empty links there are on the page - need to figure that out.
5044 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
5046 # Parse wikitext quotes (italics & bold)
5047 $text = $this->doQuotes($text);
5050 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5054 function srvus( $text ) {
5055 return $this->testSrvus( $text, $this->mOutputType
);
5059 * strip/replaceVariables/unstrip for preprocessor regression testing
5061 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
5062 $this->clearState();
5063 if ( ! ( $title instanceof Title
) ) {
5064 $title = Title
::newFromText( $title );
5066 $this->mTitle
= $title;
5067 $this->mOptions
= $options;
5068 $this->setOutputType( $outputType );
5069 $text = $this->replaceVariables( $text );
5070 $text = $this->mStripState
->unstripBoth( $text );
5071 $text = Sanitizer
::removeHTMLtags( $text );
5075 function testPst( $text, $title, $options ) {
5077 if ( ! ( $title instanceof Title
) ) {
5078 $title = Title
::newFromText( $title );
5080 return $this->preSaveTransform( $text, $title, $wgUser, $options );
5083 function testPreprocess( $text, $title, $options ) {
5084 if ( ! ( $title instanceof Title
) ) {
5085 $title = Title
::newFromText( $title );
5087 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5090 function markerSkipCallback( $s, $callback ) {
5093 while ( $i < strlen( $s ) ) {
5094 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5095 if ( $markerStart === false ) {
5096 $out .= call_user_func( $callback, substr( $s, $i ) );
5099 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5100 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5101 if ( $markerEnd === false ) {
5102 $out .= substr( $s, $markerStart );
5105 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5106 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5114 function serialiseHalfParsedText( $text ) {
5116 $data['text'] = $text;
5118 // First, find all strip markers, and store their
5119 // data in an array.
5120 $stripState = new StripState
;
5122 while( ( $start_pos = strpos( $text, $this->mUniqPrefix
, $pos ) ) && ( $end_pos = strpos( $text, self
::MARKER_SUFFIX
, $pos ) ) ) {
5123 $end_pos +
= strlen( self
::MARKER_SUFFIX
);
5124 $marker = substr( $text, $start_pos, $end_pos-$start_pos );
5126 if ( !empty( $this->mStripState
->general
->data
[$marker] ) ) {
5127 $replaceArray = $stripState->general
;
5128 $stripText = $this->mStripState
->general
->data
[$marker];
5129 } elseif ( !empty( $this->mStripState
->nowiki
->data
[$marker] ) ) {
5130 $replaceArray = $stripState->nowiki
;
5131 $stripText = $this->mStripState
->nowiki
->data
[$marker];
5133 throw new MWException( "Hanging strip marker: '$marker'." );
5136 $replaceArray->setPair( $marker, $stripText );
5139 $data['stripstate'] = $stripState;
5141 // Now, find all of our links, and store THEIR
5142 // data in an array! :)
5143 $links = array( 'internal' => array(), 'interwiki' => array() );
5147 while( ( $start_pos = strpos( $text, '<!--LINK ', $pos ) ) ) {
5148 list( $ns, $trail ) = explode( ':', substr( $text, $start_pos +
strlen( '<!--LINK ' ) ), 2 );
5151 if (empty( $links['internal'][$ns] )) {
5152 $links['internal'][$ns] = array();
5155 $key = trim( substr( $trail, 0, strpos( $trail, '-->' ) ) );
5156 $links['internal'][$ns][] = $this->mLinkHolders
->internals
[$ns][$key];
5157 $pos = $start_pos +
strlen( "<!--LINK $ns:$key-->" );
5163 while( ( $start_pos = strpos( $text, '<!--IWLINK ', $pos ) ) ) {
5164 $data = substr( $text, $start_pos );
5165 $key = trim( substr( $data, 0, strpos( $data, '-->' ) ) );
5166 $links['interwiki'][] = $this->mLinkHolders
->interwiki
[$key];
5167 $pos = $start_pos +
strlen( "<!--IWLINK $key-->" );
5170 $data['linkholder'] = $links;
5175 function unserialiseHalfParsedText( $data, $intPrefix = null /* Unique identifying prefix */ ) {
5177 $intPrefix = $this->getRandomString();
5179 // First, extract the strip state.
5180 $stripState = $data['stripstate'];
5181 $this->mStripState
->general
->merge( $stripState->general
);
5182 $this->mStripState
->nowiki
->merge( $stripState->nowiki
);
5184 // Now, extract the text, and renumber links
5185 $text = $data['text'];
5186 $links = $data['linkholder'];
5189 foreach( $links['internal'] as $ns => $nsLinks ) {
5190 foreach( $nsLinks as $key => $entry ) {
5191 $newKey = $intPrefix . '-' . $key;
5192 $this->mLinkHolders
->internals
[$ns][$newKey] = $entry;
5194 $text = str_replace( "<!--LINK $ns:$key-->", "<!--LINK $ns:$newKey-->", $text );
5199 foreach( $links['interwiki'] as $key => $entry ) {
5200 $newKey = "$intPrefix-$key";
5201 $this->mLinkHolders
->interwikis
[$newKey] = $entry;
5203 $text = str_replace( "<!--IWLINK $key-->", "<!--IWLINK $newKey-->", $text );
5206 // Should be good to go.
5212 * @todo document, briefly.
5216 var $general, $nowiki;
5218 function __construct() {
5219 $this->general
= new ReplacementArray
;
5220 $this->nowiki
= new ReplacementArray
;
5223 function unstripGeneral( $text ) {
5224 wfProfileIn( __METHOD__
);
5227 $text = $this->general
->replace( $text );
5228 } while ( $text !== $oldText );
5229 wfProfileOut( __METHOD__
);
5233 function unstripNoWiki( $text ) {
5234 wfProfileIn( __METHOD__
);
5237 $text = $this->nowiki
->replace( $text );
5238 } while ( $text !== $oldText );
5239 wfProfileOut( __METHOD__
);
5243 function unstripBoth( $text ) {
5244 wfProfileIn( __METHOD__
);
5247 $text = $this->general
->replace( $text );
5248 $text = $this->nowiki
->replace( $text );
5249 } while ( $text !== $oldText );
5250 wfProfileOut( __METHOD__
);
5256 * @todo document, briefly.
5259 class OnlyIncludeReplacer
{
5262 function replace( $matches ) {
5263 if ( substr( $matches[1], -1 ) === "\n" ) {
5264 $this->output
.= substr( $matches[1], 0, -1 );
5266 $this->output
.= $matches[1];