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 six 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
29 * getTransclusionText()
30 * Extracts the text of a template with only <includeonly>, etc., parsed
33 * objects: $wgLang, $wgContLang
35 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
38 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
39 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
40 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
43 * * only within ParserOptions
51 * Update this version number when the ParserOutput format
52 * changes in an incompatible way, so the parser cache
53 * can automatically discard old data.
55 const VERSION
= '1.6.4';
57 # Flags for Parser::setFunctionHook
58 # Also available as global constants from Defines.php
59 const SFH_NO_HASH
= 1;
60 const SFH_OBJECT_ARGS
= 2;
62 # Constants needed for external link processing
63 # Everything except bracket, space, or control characters
64 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F]';
65 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
66 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
68 // State constants for the definition list colon extraction
69 const COLON_STATE_TEXT
= 0;
70 const COLON_STATE_TAG
= 1;
71 const COLON_STATE_TAGSTART
= 2;
72 const COLON_STATE_CLOSETAG
= 3;
73 const COLON_STATE_TAGSLASH
= 4;
74 const COLON_STATE_COMMENT
= 5;
75 const COLON_STATE_COMMENTDASH
= 6;
76 const COLON_STATE_COMMENTDASHDASH
= 7;
78 // Flags for preprocessToDom
79 const PTD_FOR_INCLUSION
= 1;
81 // Allowed values for $this->mOutputType
82 // Parameter to startExternalParse().
85 const OT_PREPROCESS
= 3;
87 const OT_INCLUDES
= 4;
89 // Marker Suffix needs to be accessible staticly.
90 const MARKER_SUFFIX
= "-QINU\x7f";
96 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables,
97 $mSubsts, $mImageParams, $mImageParamsMagicArray, $mStripList, $mMarkerIndex,
98 $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols, $mDefaultStripList,
99 $mVarCache, $mConf, $mFunctionTagHooks;
102 # Cleared with clearState():
103 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
104 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
105 var $mLinkHolders, $mLinkID;
106 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
107 var $mTplExpandCache; // empty-frame expansion cache
108 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
109 var $mExpensiveFunctionCount; // number of expensive parser function calls
112 # These are variables reset at least once per parse regardless of $clearState
113 var $mOptions, // ParserOptions object
114 $mTitle, // Title context, used for self-link rendering and similar things
115 $mOutputType, // Output type, one of the OT_xxx constants
116 $ot, // Shortcut alias, see setOutputType()
117 $mRevisionId, // ID to display in {{REVISIONID}} tags
118 $mRevisionTimestamp, // The timestamp of the specified revision ID
119 $mRevIdForTs; // The revision ID which was used to fetch the timestamp
128 function __construct( $conf = array() ) {
129 $this->mConf
= $conf;
130 $this->mTagHooks
= array();
131 $this->mTransparentTagHooks
= array();
132 $this->mFunctionHooks
= array();
133 $this->mFunctionTagHooks
= array();
134 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
135 $this->mDefaultStripList
= $this->mStripList
= array();
136 $this->mUrlProtocols
= wfUrlProtocols();
137 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
138 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x0a\\x0d]*?)\]/S';
139 $this->mVarCache
= array();
140 if ( isset( $conf['preprocessorClass'] ) ) {
141 $this->mPreprocessorClass
= $conf['preprocessorClass'];
142 } elseif ( extension_loaded( 'domxml' ) ) {
143 // PECL extension that conflicts with the core DOM extension (bug 13770)
144 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
145 $this->mPreprocessorClass
= 'Preprocessor_Hash';
146 } elseif ( extension_loaded( 'dom' ) ) {
147 $this->mPreprocessorClass
= 'Preprocessor_DOM';
149 $this->mPreprocessorClass
= 'Preprocessor_Hash';
151 $this->mMarkerIndex
= 0;
152 $this->mFirstCall
= true;
156 * Reduce memory usage to reduce the impact of circular references
158 function __destruct() {
159 if ( isset( $this->mLinkHolders
) ) {
160 $this->mLinkHolders
->__destruct();
162 foreach ( $this as $name => $value ) {
163 unset( $this->$name );
168 * Do various kinds of initialisation on the first call of the parser
170 function firstCallInit() {
171 if ( !$this->mFirstCall
) {
174 $this->mFirstCall
= false;
176 wfProfileIn( __METHOD__
);
178 CoreParserFunctions
::register( $this );
179 CoreTagHooks
::register( $this );
180 $this->initialiseVariables();
182 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
183 wfProfileOut( __METHOD__
);
191 function clearState() {
192 wfProfileIn( __METHOD__
);
193 if ( $this->mFirstCall
) {
194 $this->firstCallInit();
196 $this->mOutput
= new ParserOutput
;
197 $this->mAutonumber
= 0;
198 $this->mLastSection
= '';
199 $this->mDTopen
= false;
200 $this->mIncludeCount
= array();
201 $this->mStripState
= new StripState
;
202 $this->mArgStack
= false;
203 $this->mInPre
= false;
204 $this->mLinkHolders
= new LinkHolderArray( $this );
206 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
207 $this->mVarCache
= array();
210 * Prefix for temporary replacement strings for the multipass parser.
211 * \x07 should never appear in input as it's disallowed in XML.
212 * Using it at the front also gives us a little extra robustness
213 * since it shouldn't match when butted up against identifier-like
216 * Must not consist of all title characters, or else it will change
217 * the behaviour of <nowiki> in a link.
219 #$this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
220 # Changed to \x7f to allow XML double-parsing -- TS
221 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
224 # Clear these on every parse, bug 4549
225 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
227 $this->mShowToc
= true;
228 $this->mForceTocPosition
= false;
229 $this->mIncludeSizes
= array(
233 $this->mPPNodeCount
= 0;
234 $this->mDefaultSort
= false;
235 $this->mHeadings
= array();
236 $this->mDoubleUnderscores
= array();
237 $this->mExpensiveFunctionCount
= 0;
240 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
241 $this->mPreprocessor
= null;
244 wfRunHooks( 'ParserClearState', array( &$this ) );
245 wfProfileOut( __METHOD__
);
248 function setOutputType( $ot ) {
249 $this->mOutputType
= $ot;
252 'html' => $ot == self
::OT_HTML
,
253 'wiki' => $ot == self
::OT_WIKI
,
254 'pre' => $ot == self
::OT_PREPROCESS
,
259 * Set the context title
261 function setTitle( $t ) {
262 if ( !$t ||
$t instanceof FakeTitle
) {
263 $t = Title
::newFromText( 'NO TITLE' );
266 if ( strval( $t->getFragment() ) !== '' ) {
267 # Strip the fragment to avoid various odd effects
268 $this->mTitle
= clone $t;
269 $this->mTitle
->setFragment( '' );
276 * Accessor for mUniqPrefix.
280 function uniqPrefix() {
281 if( !isset( $this->mUniqPrefix
) ) {
282 // @todo Fixme: this is probably *horribly wrong*
283 // LanguageConverter seems to want $wgParser's uniqPrefix, however
284 // if this is called for a parser cache hit, the parser may not
285 // have ever been initialized in the first place.
286 // Not really sure what the heck is supposed to be going on here.
288 //throw new MWException( "Accessing uninitialized mUniqPrefix" );
290 return $this->mUniqPrefix
;
294 * Convert wikitext to HTML
295 * Do not call this function recursively.
297 * @param $text String: text we want to parse
298 * @param $title A title object
299 * @param $options ParserOptions
300 * @param $linestart boolean
301 * @param $clearState boolean
302 * @param $revid Int: number to pass in {{REVISIONID}}
303 * @return ParserOutput a ParserOutput
305 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
307 * First pass--just handle <nowiki> sections, pass the rest off
308 * to internalParse() which does all the real work.
311 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang, $wgDisableLangConversion;
312 $fname = __METHOD__
.'-' . wfGetCaller();
313 wfProfileIn( __METHOD__
);
314 wfProfileIn( $fname );
320 $this->mOptions
= $options;
321 $this->setTitle( $title ); // Page title has to be set for the pre-processor
323 $oldRevisionId = $this->mRevisionId
;
324 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
325 if( $revid !== null ) {
326 $this->mRevisionId
= $revid;
327 $this->mRevisionTimestamp
= null;
329 $this->setOutputType( self
::OT_HTML
);
330 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
332 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
333 $text = $this->internalParse( $text );
335 $text = $this->mStripState
->unstripGeneral( $text );
337 # Clean up special characters, only run once, next-to-last before doBlockLevels
339 # french spaces, last one Guillemet-left
340 # only if there is something before the space
341 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
342 # french spaces, Guillemet-right
343 '/(\\302\\253) /' => '\\1 ',
344 '/ (!\s*important)/' => ' \\1', #Beware of CSS magic word !important, bug #11874.
346 $text = preg_replace( array_keys($fixtags), array_values($fixtags), $text );
348 $text = $this->doBlockLevels( $text, $linestart );
350 $this->replaceLinkHolders( $text );
352 // The position of the convert() call should not be changed. it
353 // assumes that the links are all replaced and the only thing left
354 // is the <nowiki> mark.
355 if ( !( $wgDisableLangConversion
356 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
357 ||
$this->mTitle
->isTalkPage()
358 ||
$this->mTitle
->isConversionTable() ) ) {
359 $text = $wgContLang->convert( $text );
362 // A title may have been set in a conversion rule.
363 // Note that if a user tries to set a title in a conversion
364 // rule but content conversion was not done, then the parser
365 // won't pick it up. This is probably expected behavior.
366 if ( $wgContLang->getConvRuleTitle() ) {
367 $this->mOutput
->setTitleText( $wgContLang->getConvRuleTitle() );
368 } elseif ( !( $wgDisableLangConversion
369 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] ) ) ) {
370 if ( $title->getNamespace() == NS_SPECIAL
) {
371 $this->setTitle( $wgContLang->convert( $title ) );
373 $this->mOutput
->setTitleText( $wgContLang->convert( $title->getPrefixedText() ) );
377 $text = $this->mStripState
->unstripNoWiki( $text );
379 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
381 if ( $this->mTransparentTagHooks
) {
382 //!JF Move to its own function
383 $uniq_prefix = $this->mUniqPrefix
;
385 $elements = array_keys( $this->mTransparentTagHooks
);
386 $text = self
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
388 foreach( $matches as $marker => $data ) {
389 list( $element, $content, $params, $tag ) = $data;
390 $tagName = strtolower( $element );
391 if( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
392 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName],
393 array( $content, $params, $this ) );
397 $this->mStripState
->general
->setPair( $marker, $output );
401 # This was originally inserted for transparent tag hooks (now deprecated)
402 # but some extensions (notably <poem>) rely on the extra unstripGeneral()
403 # after unstripNoWiki() so they can modify the contents of <nowiki> tags.
404 $text = $this->mStripState
->unstripGeneral( $text );
406 $text = Sanitizer
::normalizeCharReferences( $text );
408 if ( ( $wgUseTidy && $this->mOptions
->mTidy
) ||
$wgAlwaysUseTidy ) {
409 $text = MWTidy
::tidy( $text );
411 # attempt to sanitize at least some nesting problems
412 # (bug #2702 and quite a few others)
414 # ''Something [http://www.cool.com cool''] -->
415 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
416 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
417 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
418 # fix up an anchor inside another anchor, only
419 # at least for a single single nested link (bug 3695)
420 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
421 '\\1\\2</a>\\3</a>\\1\\4</a>',
422 # fix div inside inline elements- doBlockLevels won't wrap a line which
423 # contains a div, so fix it up here; replace
424 # div with escaped text
425 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
426 '\\1\\3<div\\5>\\6</div>\\8\\9',
427 # remove empty italic or bold tag pairs, some
428 # introduced by rules above
429 '/<([bi])><\/\\1>/' => '',
432 $text = preg_replace(
433 array_keys( $tidyregs ),
434 array_values( $tidyregs ),
437 global $wgExpensiveParserFunctionLimit;
438 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
439 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
442 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
444 # Information on include size limits, for the benefit of users who try to skirt them
445 if ( $this->mOptions
->getEnableLimitReport() ) {
446 global $wgExpensiveParserFunctionLimit;
447 $max = $this->mOptions
->getMaxIncludeSize();
448 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
450 "NewPP limit report\n" .
451 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
452 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
453 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
455 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
456 $text .= "\n<!-- \n$limitReport-->\n";
458 $this->mOutput
->setText( $text );
460 $this->mRevisionId
= $oldRevisionId;
461 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
462 wfProfileOut( $fname );
463 wfProfileOut( __METHOD__
);
465 return $this->mOutput
;
469 * Recursive parser entry point that can be called from an extension tag
472 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
474 * @param $text String: text extension wants to have parsed
475 * @param PPFrame $frame: The frame to use for expanding any template variables
477 function recursiveTagParse( $text, $frame=false ) {
478 wfProfileIn( __METHOD__
);
479 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
480 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
481 $text = $this->internalParse( $text, false, $frame );
482 wfProfileOut( __METHOD__
);
487 * Expand templates and variables in the text, producing valid, static wikitext.
488 * Also removes comments.
490 function preprocess( $text, $title, $options, $revid = null ) {
491 wfProfileIn( __METHOD__
);
493 $this->setOutputType( self
::OT_PREPROCESS
);
494 $this->mOptions
= $options;
495 $this->setTitle( $title );
496 if( $revid !== null ) {
497 $this->mRevisionId
= $revid;
499 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
500 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
501 $text = $this->replaceVariables( $text );
502 $text = $this->mStripState
->unstripBoth( $text );
503 wfProfileOut( __METHOD__
);
508 * Get the wikitext of a page as though it was transcluded.
510 * Specifically <includeonly> etc. are parsed, redirects are followed, comments
511 * are removed, but templates arguments and parser functions are untouched.
513 * This is not called by the parser itself, see braceSubstitution for its transclusion.
515 public function getTransclusionText( $title, $options ) {
516 // Must initialize first
518 $this->setOutputType( self
::OT_INCLUDES
);
519 $this->mOptions
= $options;
520 $this->setTitle( new FakeTitle
);
522 list( $text, $title ) = $this->getTemplateDom( $title );
523 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
524 return $this->getPreprocessor()->newFrame()->expand( $text, $flags );
528 * Get a random string
533 function getRandomString() {
534 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
537 function &getTitle() { return $this->mTitle
; }
538 function getOptions() { return $this->mOptions
; }
539 function getRevisionId() { return $this->mRevisionId
; }
540 function getOutput() { return $this->mOutput
; }
541 function nextLinkID() { return $this->mLinkID++
; }
543 function getFunctionLang() {
544 global $wgLang, $wgContLang;
546 $target = $this->mOptions
->getTargetLanguage();
547 if ( $target !== null ) {
550 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
555 * Get a preprocessor object
557 function getPreprocessor() {
558 if ( !isset( $this->mPreprocessor
) ) {
559 $class = $this->mPreprocessorClass
;
560 $this->mPreprocessor
= new $class( $this );
562 return $this->mPreprocessor
;
566 * Replaces all occurrences of HTML-style comments and the given tags
567 * in the text with a random marker and returns the next text. The output
568 * parameter $matches will be an associative array filled with data in
570 * 'UNIQ-xxxxx' => array(
573 * array( 'param' => 'x' ),
574 * '<element param="x">tag content</element>' ) )
576 * @param $elements list of element names. Comments are always extracted.
577 * @param $text Source text string.
578 * @param $uniq_prefix
583 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
588 $taglist = implode( '|', $elements );
589 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
591 while ( $text != '' ) {
592 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
594 if( count( $p ) < 5 ) {
597 if( count( $p ) > 5 ) {
611 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . self
::MARKER_SUFFIX
;
612 $stripped .= $marker;
614 if ( $close === '/>' ) {
615 // Empty element tag, <tag />
620 if( $element === '!--' ) {
623 $end = "/(<\\/$element\\s*>)/i";
625 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
627 if( count( $q ) < 3 ) {
628 # No end tag -- let it run out to the end of the text.
637 $matches[$marker] = array( $element,
639 Sanitizer
::decodeTagAttributes( $attributes ),
640 "<$element$attributes$close$content$tail" );
646 * Get a list of strippable XML-like elements
648 function getStripList() {
649 return $this->mStripList
;
653 * @deprecated use replaceVariables
655 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
660 * Restores pre, math, and other extensions removed by strip()
662 * always call unstripNoWiki() after this one
664 * @deprecated use $this->mStripState->unstrip()
666 function unstrip( $text, $state ) {
667 return $state->unstripGeneral( $text );
671 * Always call this after unstrip() to preserve the order
674 * @deprecated use $this->mStripState->unstrip()
676 function unstripNoWiki( $text, $state ) {
677 return $state->unstripNoWiki( $text );
681 * @deprecated use $this->mStripState->unstripBoth()
683 function unstripForHTML( $text ) {
684 return $this->mStripState
->unstripBoth( $text );
688 * Add an item to the strip state
689 * Returns the unique tag which must be inserted into the stripped text
690 * The tag will be replaced with the original text in unstrip()
694 function insertStripItem( $text ) {
695 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
696 $this->mMarkerIndex++
;
697 $this->mStripState
->general
->setPair( $rnd, $text );
702 * Interface with html tidy
703 * @deprecated Use MWTidy::tidy()
705 public static function tidy( $text ) {
706 wfDeprecated( __METHOD__
);
707 return MWTidy
::tidy( $text );
711 * parse the wiki syntax used to render tables
715 function doTableStuff ( $text ) {
716 wfProfileIn( __METHOD__
);
718 $lines = StringUtils
::explode( "\n", $text );
720 $td_history = array (); // Is currently a td tag open?
721 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
722 $tr_history = array (); // Is currently a tr tag open?
723 $tr_attributes = array (); // history of tr attributes
724 $has_opened_tr = array(); // Did this table open a <tr> element?
725 $indent_level = 0; // indent level of the table
727 foreach ( $lines as $outLine ) {
728 $line = trim( $outLine );
730 if( $line == '' ) { // empty line, go to next line
731 $out .= $outLine."\n";
734 $first_character = $line[0];
737 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
738 // First check if we are starting a new table
739 $indent_level = strlen( $matches[1] );
741 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
742 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
744 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
745 array_push( $td_history , false );
746 array_push( $last_tag_history , '' );
747 array_push( $tr_history , false );
748 array_push( $tr_attributes , '' );
749 array_push( $has_opened_tr , false );
750 } else if ( count ( $td_history ) == 0 ) {
751 // Don't do any of the following
752 $out .= $outLine."\n";
754 } else if ( substr ( $line , 0 , 2 ) === '|}' ) {
755 // We are ending a table
756 $line = '</table>' . substr ( $line , 2 );
757 $last_tag = array_pop ( $last_tag_history );
759 if ( !array_pop ( $has_opened_tr ) ) {
760 $line = "<tr><td></td></tr>{$line}";
763 if ( array_pop ( $tr_history ) ) {
764 $line = "</tr>{$line}";
767 if ( array_pop ( $td_history ) ) {
768 $line = "</{$last_tag}>{$line}";
770 array_pop ( $tr_attributes );
771 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
772 } else if ( substr ( $line , 0 , 2 ) === '|-' ) {
773 // Now we have a table row
774 $line = preg_replace( '#^\|-+#', '', $line );
776 // Whats after the tag is now only attributes
777 $attributes = $this->mStripState
->unstripBoth( $line );
778 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
779 array_pop( $tr_attributes );
780 array_push( $tr_attributes, $attributes );
783 $last_tag = array_pop ( $last_tag_history );
784 array_pop ( $has_opened_tr );
785 array_push ( $has_opened_tr , true );
787 if ( array_pop ( $tr_history ) ) {
791 if ( array_pop ( $td_history ) ) {
792 $line = "</{$last_tag}>{$line}";
796 array_push ( $tr_history , false );
797 array_push ( $td_history , false );
798 array_push ( $last_tag_history , '' );
800 else if ( $first_character === '|' ||
$first_character === '!' ||
substr ( $line , 0 , 2 ) === '|+' ) {
801 // This might be cell elements, td, th or captions
802 if ( substr ( $line , 0 , 2 ) === '|+' ) {
803 $first_character = '+';
804 $line = substr ( $line , 1 );
807 $line = substr ( $line , 1 );
809 if ( $first_character === '!' ) {
810 $line = str_replace ( '!!' , '||' , $line );
813 // Split up multiple cells on the same line.
814 // FIXME : This can result in improper nesting of tags processed
815 // by earlier parser steps, but should avoid splitting up eg
816 // attribute values containing literal "||".
817 $cells = StringUtils
::explodeMarkup( '||' , $line );
821 // Loop through each table cell
822 foreach ( $cells as $cell )
825 if ( $first_character !== '+' )
827 $tr_after = array_pop ( $tr_attributes );
828 if ( !array_pop ( $tr_history ) ) {
829 $previous = "<tr{$tr_after}>\n";
831 array_push ( $tr_history , true );
832 array_push ( $tr_attributes , '' );
833 array_pop ( $has_opened_tr );
834 array_push ( $has_opened_tr , true );
837 $last_tag = array_pop ( $last_tag_history );
839 if ( array_pop ( $td_history ) ) {
840 $previous = "</{$last_tag}>{$previous}";
843 if ( $first_character === '|' ) {
845 } else if ( $first_character === '!' ) {
847 } else if ( $first_character === '+' ) {
848 $last_tag = 'caption';
853 array_push ( $last_tag_history , $last_tag );
855 // A cell could contain both parameters and data
856 $cell_data = explode ( '|' , $cell , 2 );
858 // Bug 553: Note that a '|' inside an invalid link should not
859 // be mistaken as delimiting cell parameters
860 if ( strpos( $cell_data[0], '[[' ) !== false ) {
861 $cell = "{$previous}<{$last_tag}>{$cell}";
862 } else if ( count ( $cell_data ) == 1 )
863 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
865 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
866 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
867 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
871 array_push ( $td_history , true );
874 $out .= $outLine . "\n";
877 // Closing open td, tr && table
878 while ( count ( $td_history ) > 0 )
880 if ( array_pop ( $td_history ) ) {
883 if ( array_pop ( $tr_history ) ) {
886 if ( !array_pop ( $has_opened_tr ) ) {
887 $out .= "<tr><td></td></tr>\n" ;
890 $out .= "</table>\n";
893 // Remove trailing line-ending (b/c)
894 if ( substr( $out, -1 ) === "\n" ) {
895 $out = substr( $out, 0, -1 );
898 // special case: don't return empty table
899 if( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
903 wfProfileOut( __METHOD__
);
909 * Helper function for parse() that transforms wiki markup into
910 * HTML. Only called for $mOutputType == self::OT_HTML.
914 function internalParse( $text, $isMain = true, $frame=false ) {
915 wfProfileIn( __METHOD__
);
919 # Hook to suspend the parser in this state
920 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
921 wfProfileOut( __METHOD__
);
925 // if $frame is provided, then use $frame for replacing any variables
927 // use frame depth to infer how include/noinclude tags should be handled
928 // depth=0 means this is the top-level document; otherwise it's an included document
932 $flag = Parser
::PTD_FOR_INCLUSION
;
933 $dom = $this->preprocessToDom( $text, $flag );
934 $text = $frame->expand( $dom );
936 // if $frame is not provided, then use old-style replaceVariables
938 $text = $this->replaceVariables( $text );
941 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
942 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
944 // Tables need to come after variable replacement for things to work
945 // properly; putting them before other transformations should keep
946 // exciting things like link expansions from showing up in surprising
948 $text = $this->doTableStuff( $text );
950 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
952 $text = $this->doDoubleUnderscore( $text );
954 $text = $this->doHeadings( $text );
955 if( $this->mOptions
->getUseDynamicDates() ) {
956 $df = DateFormatter
::getInstance();
957 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
959 $text = $this->doAllQuotes( $text );
960 $text = $this->replaceInternalLinks( $text );
961 $text = $this->replaceExternalLinks( $text );
963 # replaceInternalLinks may sometimes leave behind
964 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
965 $text = str_replace($this->mUniqPrefix
.'NOPARSE', '', $text);
967 $text = $this->doMagicLinks( $text );
968 $text = $this->formatHeadings( $text, $origText, $isMain );
970 wfProfileOut( __METHOD__
);
975 * Replace special strings like "ISBN xxx" and "RFC xxx" with
976 * magic external links.
981 function doMagicLinks( $text ) {
982 wfProfileIn( __METHOD__
);
983 $prots = $this->mUrlProtocols
;
984 $urlChar = self
::EXT_LINK_URL_CLASS
;
985 $text = preg_replace_callback(
987 (<a.*?</a>) | # m[1]: Skip link text
988 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
989 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
990 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
991 ISBN\s+(\b # m[5]: ISBN, capture number
992 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
993 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
994 [0-9Xx] # check digit
996 )!x', array( &$this, 'magicLinkCallback' ), $text );
997 wfProfileOut( __METHOD__
);
1001 function magicLinkCallback( $m ) {
1002 if ( isset( $m[1] ) && $m[1] !== '' ) {
1005 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1008 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1009 # Free external link
1010 return $this->makeFreeExternalLink( $m[0] );
1011 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1014 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1017 $CssClass = 'mw-magiclink-rfc';
1019 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1021 $urlmsg = 'pubmedurl';
1022 $CssClass = 'mw-magiclink-pmid';
1025 throw new MWException( __METHOD__
.': unrecognised match type "' .
1026 substr($m[0], 0, 20 ) . '"' );
1028 $url = wfMsg( $urlmsg, $id);
1029 $sk = $this->mOptions
->getSkin();
1030 $la = $sk->getExternalLinkAttributes( "external $CssClass" );
1031 return "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1032 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1035 $num = strtr( $isbn, array(
1040 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1042 $titleObj->escapeLocalUrl() .
1043 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1050 * Make a free external link, given a user-supplied URL
1054 function makeFreeExternalLink( $url ) {
1056 wfProfileIn( __METHOD__
);
1058 $sk = $this->mOptions
->getSkin();
1061 # The characters '<' and '>' (which were escaped by
1062 # removeHTMLtags()) should not be included in
1063 # URLs, per RFC 2396.
1065 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1066 $trail = substr($url, $m2[0][1]) . $trail;
1067 $url = substr($url, 0, $m2[0][1]);
1070 # Move trailing punctuation to $trail
1072 # If there is no left bracket, then consider right brackets fair game too
1073 if ( strpos( $url, '(' ) === false ) {
1077 $numSepChars = strspn( strrev( $url ), $sep );
1078 if ( $numSepChars ) {
1079 $trail = substr( $url, -$numSepChars ) . $trail;
1080 $url = substr( $url, 0, -$numSepChars );
1083 $url = Sanitizer
::cleanUrl( $url );
1085 # Is this an external image?
1086 $text = $this->maybeMakeExternalImage( $url );
1087 if ( $text === false ) {
1088 # Not an image, make a link
1089 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1090 $this->getExternalLinkAttribs( $url ) );
1091 # Register it in the output object...
1092 # Replace unnecessary URL escape codes with their equivalent characters
1093 $pasteurized = self
::replaceUnusualEscapes( $url );
1094 $this->mOutput
->addExternalLink( $pasteurized );
1096 wfProfileOut( __METHOD__
);
1097 return $text . $trail;
1102 * Parse headers and return html
1106 function doHeadings( $text ) {
1107 wfProfileIn( __METHOD__
);
1108 for ( $i = 6; $i >= 1; --$i ) {
1109 $h = str_repeat( '=', $i );
1110 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1111 "<h$i>\\1</h$i>", $text );
1113 wfProfileOut( __METHOD__
);
1118 * Replace single quotes with HTML markup
1120 * @return string the altered text
1122 function doAllQuotes( $text ) {
1123 wfProfileIn( __METHOD__
);
1125 $lines = StringUtils
::explode( "\n", $text );
1126 foreach ( $lines as $line ) {
1127 $outtext .= $this->doQuotes( $line ) . "\n";
1129 $outtext = substr($outtext, 0,-1);
1130 wfProfileOut( __METHOD__
);
1135 * Helper function for doAllQuotes()
1137 public function doQuotes( $text ) {
1138 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1139 if ( count( $arr ) == 1 )
1143 # First, do some preliminary work. This may shift some apostrophes from
1144 # being mark-up to being text. It also counts the number of occurrences
1145 # of bold and italics mark-ups.
1149 foreach ( $arr as $r )
1151 if ( ( $i %
2 ) == 1 )
1153 # If there are ever four apostrophes, assume the first is supposed to
1154 # be text, and the remaining three constitute mark-up for bold text.
1155 if ( strlen( $arr[$i] ) == 4 )
1160 # If there are more than 5 apostrophes in a row, assume they're all
1161 # text except for the last 5.
1162 else if ( strlen( $arr[$i] ) > 5 )
1164 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1167 # Count the number of occurrences of bold and italics mark-ups.
1168 # We are not counting sequences of five apostrophes.
1169 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1170 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1171 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1176 # If there is an odd number of both bold and italics, it is likely
1177 # that one of the bold ones was meant to be an apostrophe followed
1178 # by italics. Which one we cannot know for certain, but it is more
1179 # likely to be one that has a single-letter word before it.
1180 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1183 $firstsingleletterword = -1;
1184 $firstmultiletterword = -1;
1186 foreach ( $arr as $r )
1188 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1190 $x1 = substr ($arr[$i-1], -1);
1191 $x2 = substr ($arr[$i-1], -2, 1);
1193 if ($firstspace == -1) $firstspace = $i;
1194 } else if ($x2 === ' ') {
1195 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1197 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1203 # If there is a single-letter word, use it!
1204 if ($firstsingleletterword > -1)
1206 $arr [ $firstsingleletterword ] = "''";
1207 $arr [ $firstsingleletterword-1 ] .= "'";
1209 # If not, but there's a multi-letter word, use that one.
1210 else if ($firstmultiletterword > -1)
1212 $arr [ $firstmultiletterword ] = "''";
1213 $arr [ $firstmultiletterword-1 ] .= "'";
1215 # ... otherwise use the first one that has neither.
1216 # (notice that it is possible for all three to be -1 if, for example,
1217 # there is only one pentuple-apostrophe in the line)
1218 else if ($firstspace > -1)
1220 $arr [ $firstspace ] = "''";
1221 $arr [ $firstspace-1 ] .= "'";
1225 # Now let's actually convert our apostrophic mush to HTML!
1230 foreach ($arr as $r)
1234 if ($state === 'both')
1241 if (strlen ($r) == 2)
1244 { $output .= '</i>'; $state = ''; }
1245 else if ($state === 'bi')
1246 { $output .= '</i>'; $state = 'b'; }
1247 else if ($state === 'ib')
1248 { $output .= '</b></i><b>'; $state = 'b'; }
1249 else if ($state === 'both')
1250 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1251 else # $state can be 'b' or ''
1252 { $output .= '<i>'; $state .= 'i'; }
1254 else if (strlen ($r) == 3)
1257 { $output .= '</b>'; $state = ''; }
1258 else if ($state === 'bi')
1259 { $output .= '</i></b><i>'; $state = 'i'; }
1260 else if ($state === 'ib')
1261 { $output .= '</b>'; $state = 'i'; }
1262 else if ($state === 'both')
1263 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1264 else # $state can be 'i' or ''
1265 { $output .= '<b>'; $state .= 'b'; }
1267 else if (strlen ($r) == 5)
1270 { $output .= '</b><i>'; $state = 'i'; }
1271 else if ($state === 'i')
1272 { $output .= '</i><b>'; $state = 'b'; }
1273 else if ($state === 'bi')
1274 { $output .= '</i></b>'; $state = ''; }
1275 else if ($state === 'ib')
1276 { $output .= '</b></i>'; $state = ''; }
1277 else if ($state === 'both')
1278 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1279 else # ($state == '')
1280 { $buffer = ''; $state = 'both'; }
1285 # Now close all remaining tags. Notice that the order is important.
1286 if ($state === 'b' ||
$state === 'ib')
1288 if ($state === 'i' ||
$state === 'bi' ||
$state === 'ib')
1290 if ($state === 'bi')
1292 # There might be lonely ''''', so make sure we have a buffer
1293 if ($state === 'both' && $buffer)
1294 $output .= '<b><i>'.$buffer.'</i></b>';
1300 * Replace external links (REL)
1302 * Note: this is all very hackish and the order of execution matters a lot.
1303 * Make sure to run maintenance/parserTests.php if you change this code.
1307 function replaceExternalLinks( $text ) {
1309 wfProfileIn( __METHOD__
);
1311 $sk = $this->mOptions
->getSkin();
1313 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1314 $s = array_shift( $bits );
1317 while ( $i<count( $bits ) ) {
1319 $protocol = $bits[$i++
];
1320 $text = $bits[$i++
];
1321 $trail = $bits[$i++
];
1323 # The characters '<' and '>' (which were escaped by
1324 # removeHTMLtags()) should not be included in
1325 # URLs, per RFC 2396.
1327 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1328 $text = substr($url, $m2[0][1]) . ' ' . $text;
1329 $url = substr($url, 0, $m2[0][1]);
1332 # If the link text is an image URL, replace it with an <img> tag
1333 # This happened by accident in the original parser, but some people used it extensively
1334 $img = $this->maybeMakeExternalImage( $text );
1335 if ( $img !== false ) {
1341 # Set linktype for CSS - if URL==text, link is essentially free
1342 $linktype = ($text === $url) ?
'free' : 'text';
1344 # No link text, e.g. [http://domain.tld/some.link]
1345 if ( $text == '' ) {
1346 # Autonumber if allowed. See bug #5918
1347 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1348 $langObj = $this->getFunctionLang();
1349 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1350 $linktype = 'autonumber';
1352 # Otherwise just use the URL
1353 $text = htmlspecialchars( $url );
1357 # Have link text, e.g. [http://domain.tld/some.link text]s
1359 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1362 $text = $wgContLang->markNoConversion($text);
1364 $url = Sanitizer
::cleanUrl( $url );
1366 # Use the encoded URL
1367 # This means that users can paste URLs directly into the text
1368 # Funny characters like ö aren't valid in URLs anyway
1369 # This was changed in August 2004
1370 $s .= $sk->makeExternalLink( $url, $text, false, $linktype,
1371 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1373 # Register link in the output object.
1374 # Replace unnecessary URL escape codes with the referenced character
1375 # This prevents spammers from hiding links from the filters
1376 $pasteurized = self
::replaceUnusualEscapes( $url );
1377 $this->mOutput
->addExternalLink( $pasteurized );
1380 wfProfileOut( __METHOD__
);
1385 * Get an associative array of additional HTML attributes appropriate for a
1386 * particular external link. This currently may include rel => nofollow
1387 * (depending on configuration, namespace, and the URL's domain) and/or a
1388 * target attribute (depending on configuration).
1390 * @param string $url Optional URL, to extract the domain from for rel =>
1391 * nofollow if appropriate
1392 * @return array Associative array of HTML attributes
1394 function getExternalLinkAttribs( $url = false ) {
1396 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1397 $ns = $this->mTitle
->getNamespace();
1398 if( $wgNoFollowLinks && !in_array($ns, $wgNoFollowNsExceptions) ) {
1399 $attribs['rel'] = 'nofollow';
1401 global $wgNoFollowDomainExceptions;
1402 if ( $wgNoFollowDomainExceptions ) {
1403 $bits = wfParseUrl( $url );
1404 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1405 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1406 if( substr( $bits['host'], -strlen( $domain ) )
1408 unset( $attribs['rel'] );
1415 if ( $this->mOptions
->getExternalLinkTarget() ) {
1416 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1423 * Replace unusual URL escape codes with their equivalent characters
1427 * @todo This can merge genuinely required bits in the path or query string,
1428 * breaking legit URLs. A proper fix would treat the various parts of
1429 * the URL differently; as a workaround, just use the output for
1430 * statistical records, not for actual linking/output.
1432 static function replaceUnusualEscapes( $url ) {
1433 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1434 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1438 * Callback function used in replaceUnusualEscapes().
1439 * Replaces unusual URL escape codes with their equivalent character
1443 private static function replaceUnusualEscapesCallback( $matches ) {
1444 $char = urldecode( $matches[0] );
1445 $ord = ord( $char );
1446 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1447 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1448 // No, shouldn't be escaped
1451 // Yes, leave it escaped
1457 * make an image if it's allowed, either through the global
1458 * option, through the exception, or through the on-wiki whitelist
1461 function maybeMakeExternalImage( $url ) {
1462 $sk = $this->mOptions
->getSkin();
1463 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1464 $imagesexception = !empty($imagesfrom);
1466 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1467 if( $imagesexception && is_array( $imagesfrom ) ) {
1468 $imagematch = false;
1469 foreach( $imagesfrom as $match ) {
1470 if( strpos( $url, $match ) === 0 ) {
1475 } elseif( $imagesexception ) {
1476 $imagematch = (strpos( $url, $imagesfrom ) === 0);
1478 $imagematch = false;
1480 if ( $this->mOptions
->getAllowExternalImages()
1481 ||
( $imagesexception && $imagematch ) ) {
1482 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1484 $text = $sk->makeExternalImage( $url );
1487 if( !$text && $this->mOptions
->getEnableImageWhitelist()
1488 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1489 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1490 foreach( $whitelist as $entry ) {
1491 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1492 if( strpos( $entry, '#' ) === 0 ||
$entry === '' )
1494 if( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1495 # Image matches a whitelist entry
1496 $text = $sk->makeExternalImage( $url );
1505 * Process [[ ]] wikilinks
1506 * @return processed text
1510 function replaceInternalLinks( $s ) {
1511 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1516 * Process [[ ]] wikilinks (RIL)
1517 * @return LinkHolderArray
1521 function replaceInternalLinks2( &$s ) {
1524 wfProfileIn( __METHOD__
);
1526 wfProfileIn( __METHOD__
.'-setup' );
1527 static $tc = FALSE, $e1, $e1_img;
1528 # the % is needed to support urlencoded titles as well
1530 $tc = Title
::legalChars() . '#%';
1531 # Match a link having the form [[namespace:link|alternate]]trail
1532 $e1 = "/^([{$tc}]*)(\\|.*?)?]](.*)\$/sD";
1533 # Match cases where there is no "]]", which might still be images
1534 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1537 $sk = $this->mOptions
->getSkin();
1538 $holders = new LinkHolderArray( $this );
1540 #split the entire text string on occurences of [[
1541 $a = StringUtils
::explode( '[[', ' ' . $s );
1542 #get the first element (all text up to first [[), and remove the space we added
1545 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1546 $s = substr( $s, 1 );
1548 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1550 if ( $useLinkPrefixExtension ) {
1551 # Match the end of a line for a word that's not followed by whitespace,
1552 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1553 $e2 = wfMsgForContent( 'linkprefix' );
1556 if( is_null( $this->mTitle
) ) {
1557 wfProfileOut( __METHOD__
.'-setup' );
1558 wfProfileOut( __METHOD__
);
1559 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1561 $nottalk = !$this->mTitle
->isTalkPage();
1563 if ( $useLinkPrefixExtension ) {
1565 if ( preg_match( $e2, $s, $m ) ) {
1566 $first_prefix = $m[2];
1568 $first_prefix = false;
1574 if($wgContLang->hasVariants()) {
1575 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1577 $selflink = array($this->mTitle
->getPrefixedText());
1579 $useSubpages = $this->areSubpagesAllowed();
1580 wfProfileOut( __METHOD__
.'-setup' );
1582 # Loop for each link
1583 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1584 # Check for excessive memory usage
1585 if ( $holders->isBig() ) {
1587 # Do the existence check, replace the link holders and clear the array
1588 $holders->replace( $s );
1592 if ( $useLinkPrefixExtension ) {
1593 wfProfileIn( __METHOD__
.'-prefixhandling' );
1594 if ( preg_match( $e2, $s, $m ) ) {
1602 $prefix = $first_prefix;
1603 $first_prefix = false;
1605 wfProfileOut( __METHOD__
.'-prefixhandling' );
1608 $might_be_img = false;
1610 wfProfileIn( __METHOD__
."-e1" );
1611 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1613 if( $m[2] === '' ) {
1615 } elseif( $m[2] === '|' ) {
1616 $text = $this->getPipeTrickText( $m[1] );
1618 $text = substr( $m[2], 1 );
1621 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1622 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1623 # the real problem is with the $e1 regex
1626 # Still some problems for cases where the ] is meant to be outside punctuation,
1627 # and no image is in sight. See bug 2095.
1630 substr( $m[3], 0, 1 ) === ']' &&
1631 strpos($text, '[') !== false
1634 $text .= ']'; # so that replaceExternalLinks($text) works later
1635 $m[3] = substr( $m[3], 1 );
1638 # Handle pipe-trick for [[|<blah>]]
1639 $lnk = $m[1] === '' ?
$this->getPipeTrickLink( $text ) : $m[1];
1640 # fix up urlencoded title texts
1641 if( strpos( $lnk, '%' ) !== false ) {
1642 # Should anchors '#' also be rejected?
1643 $lnk = str_replace( array('<', '>'), array('<', '>'), urldecode($lnk) );
1647 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1648 $might_be_img = true;
1650 $lnk = strpos( $m[1], '%' ) === false ?
$m[1] : urldecode( $m[1] );
1652 } else { # Invalid form; output directly
1653 $s .= $prefix . '[[' . $line ;
1654 wfProfileOut( __METHOD__
."-e1" );
1657 wfProfileOut( __METHOD__
."-e1" );
1658 wfProfileIn( __METHOD__
."-misc" );
1660 # Don't allow internal links to pages containing
1661 # PROTO: where PROTO is a valid URL protocol; these
1662 # should be external links.
1663 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $lnk ) ) {
1664 $s .= $prefix . '[[' . $line ;
1665 wfProfileOut( __METHOD__
."-misc" );
1669 # Make subpage if necessary
1670 if ( $useSubpages ) {
1671 $link = $this->maybeDoSubpageLink( $lnk, $text );
1676 $noforce = (substr( $lnk, 0, 1 ) !== ':');
1678 # Strip off leading ':'
1679 $link = substr( $link, 1 );
1682 wfProfileOut( __METHOD__
."-misc" );
1683 wfProfileIn( __METHOD__
."-title" );
1684 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1685 if ( $nt === null ) {
1686 $s .= $prefix . '[[' . $line;
1687 wfProfileOut( __METHOD__
."-title" );
1691 $ns = $nt->getNamespace();
1692 $iw = $nt->getInterWiki();
1693 wfProfileOut( __METHOD__
."-title" );
1695 if ( $might_be_img ) { # if this is actually an invalid link
1696 wfProfileIn( __METHOD__
."-might_be_img" );
1697 if ( $ns == NS_FILE
&& $noforce ) { #but might be an image
1700 #look at the next 'line' to see if we can close it there
1702 $next_line = $a->current();
1703 if ( $next_line === false ||
$next_line === null ) {
1706 $m = explode( ']]', $next_line, 3 );
1707 if ( count( $m ) == 3 ) {
1708 # the first ]] closes the inner link, the second the image
1710 $text .= "[[{$m[0]}]]{$m[1]}";
1713 } elseif ( count( $m ) == 2 ) {
1714 #if there's exactly one ]] that's fine, we'll keep looking
1715 $text .= "[[{$m[0]}]]{$m[1]}";
1717 #if $next_line is invalid too, we need look no further
1718 $text .= '[[' . $next_line;
1723 # we couldn't find the end of this imageLink, so output it raw
1724 #but don't ignore what might be perfectly normal links in the text we've examined
1725 $holders->merge( $this->replaceInternalLinks2( $text ) );
1726 $s .= "{$prefix}[[$link|$text";
1727 # note: no $trail, because without an end, there *is* no trail
1728 wfProfileOut( __METHOD__
."-might_be_img" );
1731 } else { #it's not an image, so output it raw
1732 $s .= "{$prefix}[[$link|$text";
1733 # note: no $trail, because without an end, there *is* no trail
1734 wfProfileOut( __METHOD__
."-might_be_img" );
1737 wfProfileOut( __METHOD__
."-might_be_img" );
1740 $wasblank = ( $text == '' );
1741 if ( $wasblank ) $text = $link;
1743 # Link not escaped by : , create the various objects
1747 wfProfileIn( __METHOD__
."-interwiki" );
1748 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1749 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1750 $s = rtrim($s . $prefix);
1751 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1752 wfProfileOut( __METHOD__
."-interwiki" );
1755 wfProfileOut( __METHOD__
."-interwiki" );
1757 if ( $ns == NS_FILE
) {
1758 wfProfileIn( __METHOD__
."-image" );
1759 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1761 # if no parameters were passed, $text
1762 # becomes something like "File:Foo.png",
1763 # which we don't want to pass on to the
1767 # recursively parse links inside the image caption
1768 # actually, this will parse them in any other parameters, too,
1769 # but it might be hard to fix that, and it doesn't matter ATM
1770 $text = $this->replaceExternalLinks($text);
1771 $holders->merge( $this->replaceInternalLinks2( $text ) );
1773 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1774 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1776 $s .= $prefix . $trail;
1778 $this->mOutput
->addImage( $nt->getDBkey() );
1779 wfProfileOut( __METHOD__
."-image" );
1784 if ( $ns == NS_CATEGORY
) {
1785 wfProfileIn( __METHOD__
."-category" );
1786 $s = rtrim($s . "\n"); # bug 87
1789 $sortkey = $this->getDefaultSort();
1793 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1794 $sortkey = str_replace( "\n", '', $sortkey );
1795 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1796 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1799 * Strip the whitespace Category links produce, see bug 87
1800 * @todo We might want to use trim($tmp, "\n") here.
1802 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1804 wfProfileOut( __METHOD__
."-category" );
1809 # Self-link checking
1810 if( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1811 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1812 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1817 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1818 # FIXME: Should do batch file existence checks, see comment below
1819 if( $ns == NS_MEDIA
) {
1820 wfProfileIn( __METHOD__
."-media" );
1821 # Give extensions a chance to select the file revision for us
1822 $skip = $time = false;
1823 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1825 $link = $sk->link( $nt );
1827 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1829 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1830 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1831 $this->mOutput
->addImage( $nt->getDBkey() );
1832 wfProfileOut( __METHOD__
."-media" );
1836 wfProfileIn( __METHOD__
."-always_known" );
1837 # Some titles, such as valid special pages or files in foreign repos, should
1838 # be shown as bluelinks even though they're not included in the page table
1840 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1841 # batch file existence checks for NS_FILE and NS_MEDIA
1842 if( $iw == '' && $nt->isAlwaysKnown() ) {
1843 $this->mOutput
->addLink( $nt );
1844 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1846 # Links will be added to the output link list after checking
1847 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1849 wfProfileOut( __METHOD__
."-always_known" );
1851 wfProfileOut( __METHOD__
);
1856 * Make a link placeholder. The text returned can be later resolved to a real link with
1857 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1858 * parsing of interwiki links, and secondly to allow all existence checks and
1859 * article length checks (for stub links) to be bundled into a single query.
1863 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1864 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1868 * Render a forced-blue link inline; protect against double expansion of
1869 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1870 * Since this little disaster has to split off the trail text to avoid
1871 * breaking URLs in the following text without breaking trails on the
1872 * wiki links, it's been made into a horrible function.
1875 * @param string $text
1876 * @param string $query
1877 * @param string $trail
1878 * @param string $prefix
1879 * @return string HTML-wikitext mix oh yuck
1881 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1882 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1883 $sk = $this->mOptions
->getSkin();
1884 // FIXME: use link() instead of deprecated makeKnownLinkObj()
1885 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1886 return $this->armorLinks( $link ) . $trail;
1890 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1891 * going to go through further parsing steps before inline URL expansion.
1893 * Not needed quite as much as it used to be since free links are a bit
1894 * more sensible these days. But bracketed links are still an issue.
1896 * @param string more-or-less HTML
1897 * @return string less-or-more HTML with NOPARSE bits
1899 function armorLinks( $text ) {
1900 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1901 "{$this->mUniqPrefix}NOPARSE$1", $text );
1905 * Return true if subpage links should be expanded on this page.
1908 function areSubpagesAllowed() {
1909 # Some namespaces don't allow subpages
1910 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
1914 * Handle link to subpage if necessary
1915 * @param string $target the source of the link
1916 * @param string &$text the link text, modified as necessary
1917 * @return string the full name of the link
1920 function maybeDoSubpageLink($target, &$text) {
1921 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
1925 * From the [[title|]] return link-text as though the used typed [[title|link-text]]
1926 * @param string $link from [[$link|]]
1927 * @return string $text for [[$link|$text]]
1929 function getPipeTrickText( $link ) {
1930 return Linker
::getPipeTrickText( $link );
1934 * From the [[|link-text]] return the title as though the user typed [[title|link-text]]
1935 * @param string $text from [[|$text]]
1936 * @param Title $title to resolve the link against
1937 * @return string $link for [[$link|$text]]
1939 function getPipeTrickLink( $text ) {
1940 return Linker
::getPipeTrickLink( $text, $this->mTitle
);
1944 * Used by doBlockLevels()
1947 /* private */ function closeParagraph() {
1949 if ( $this->mLastSection
!= '' ) {
1950 $result = '</' . $this->mLastSection
. ">\n";
1952 $this->mInPre
= false;
1953 $this->mLastSection
= '';
1956 # getCommon() returns the length of the longest common substring
1957 # of both arguments, starting at the beginning of both.
1959 /* private */ function getCommon( $st1, $st2 ) {
1960 $fl = strlen( $st1 );
1961 $shorter = strlen( $st2 );
1962 if ( $fl < $shorter ) { $shorter = $fl; }
1964 for ( $i = 0; $i < $shorter; ++
$i ) {
1965 if ( $st1{$i} != $st2{$i} ) { break; }
1969 # These next three functions open, continue, and close the list
1970 # element appropriate to the prefix character passed into them.
1972 /* private */ function openList( $char ) {
1973 $result = $this->closeParagraph();
1975 if ( '*' === $char ) { $result .= '<ul><li>'; }
1976 elseif ( '#' === $char ) { $result .= '<ol><li>'; }
1977 elseif ( ':' === $char ) { $result .= '<dl><dd>'; }
1978 elseif ( ';' === $char ) {
1979 $result .= '<dl><dt>';
1980 $this->mDTopen
= true;
1982 else { $result = '<!-- ERR 1 -->'; }
1987 /* private */ function nextItem( $char ) {
1988 if ( '*' === $char ||
'#' === $char ) { return '</li><li>'; }
1989 elseif ( ':' === $char ||
';' === $char ) {
1991 if ( $this->mDTopen
) { $close = '</dt>'; }
1992 if ( ';' === $char ) {
1993 $this->mDTopen
= true;
1994 return $close . '<dt>';
1996 $this->mDTopen
= false;
1997 return $close . '<dd>';
2000 return '<!-- ERR 2 -->';
2003 /* private */ function closeList( $char ) {
2004 if ( '*' === $char ) { $text = '</li></ul>'; }
2005 elseif ( '#' === $char ) { $text = '</li></ol>'; }
2006 elseif ( ':' === $char ) {
2007 if ( $this->mDTopen
) {
2008 $this->mDTopen
= false;
2009 $text = '</dt></dl>';
2011 $text = '</dd></dl>';
2014 else { return '<!-- ERR 3 -->'; }
2020 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2022 * @param $linestart bool whether or not this is at the start of a line.
2024 * @return string the lists rendered as HTML
2026 function doBlockLevels( $text, $linestart ) {
2027 wfProfileIn( __METHOD__
);
2029 # Parsing through the text line by line. The main thing
2030 # happening here is handling of block-level elements p, pre,
2031 # and making lists from lines starting with * # : etc.
2033 $textLines = StringUtils
::explode( "\n", $text );
2035 $lastPrefix = $output = '';
2036 $this->mDTopen
= $inBlockElem = false;
2038 $paragraphStack = false;
2040 foreach ( $textLines as $oLine ) {
2042 if ( !$linestart ) {
2052 $lastPrefixLength = strlen( $lastPrefix );
2053 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2054 $preOpenMatch = preg_match('/<pre/i', $oLine );
2055 // If not in a <pre> element, scan for and figure out what prefixes are there.
2056 if ( !$this->mInPre
) {
2057 # Multiple prefixes may abut each other for nested lists.
2058 $prefixLength = strspn( $oLine, '*#:;' );
2059 $prefix = substr( $oLine, 0, $prefixLength );
2062 // ; and : are both from definition-lists, so they're equivalent
2063 // for the purposes of determining whether or not we need to open/close
2065 $prefix2 = str_replace( ';', ':', $prefix );
2066 $t = substr( $oLine, $prefixLength );
2067 $this->mInPre
= (bool)$preOpenMatch;
2069 # Don't interpret any other prefixes in preformatted text
2071 $prefix = $prefix2 = '';
2076 if( $prefixLength && $lastPrefix === $prefix2 ) {
2077 # Same as the last item, so no need to deal with nesting or opening stuff
2078 $output .= $this->nextItem( substr( $prefix, -1 ) );
2079 $paragraphStack = false;
2081 if ( substr( $prefix, -1 ) === ';') {
2082 # The one nasty exception: definition lists work like this:
2083 # ; title : definition text
2084 # So we check for : in the remainder text to split up the
2085 # title and definition, without b0rking links.
2087 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2089 $output .= $term . $this->nextItem( ':' );
2092 } elseif( $prefixLength ||
$lastPrefixLength ) {
2093 // We need to open or close prefixes, or both.
2095 # Either open or close a level...
2096 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2097 $paragraphStack = false;
2099 // Close all the prefixes which aren't shared.
2100 while( $commonPrefixLength < $lastPrefixLength ) {
2101 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2102 --$lastPrefixLength;
2105 // Continue the current prefix if appropriate.
2106 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2107 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2110 // Open prefixes where appropriate.
2111 while ( $prefixLength > $commonPrefixLength ) {
2112 $char = substr( $prefix, $commonPrefixLength, 1 );
2113 $output .= $this->openList( $char );
2115 if ( ';' === $char ) {
2116 # FIXME: This is dupe of code above
2117 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2119 $output .= $term . $this->nextItem( ':' );
2122 ++
$commonPrefixLength;
2124 $lastPrefix = $prefix2;
2127 // If we have no prefixes, go to paragraph mode.
2128 if( 0 == $prefixLength ) {
2129 wfProfileIn( __METHOD__
."-paragraph" );
2130 # No prefix (not in list)--go to paragraph mode
2131 // XXX: use a stack for nestable elements like span, table and div
2132 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2133 $closematch = preg_match(
2134 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2135 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2136 if ( $openmatch or $closematch ) {
2137 $paragraphStack = false;
2138 #Â TODO bug 5718: paragraph closed
2139 $output .= $this->closeParagraph();
2140 if ( $preOpenMatch and !$preCloseMatch ) {
2141 $this->mInPre
= true;
2143 if ( $closematch ) {
2144 $inBlockElem = false;
2146 $inBlockElem = true;
2148 } else if ( !$inBlockElem && !$this->mInPre
) {
2149 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' or trim($t) != '' ) ) {
2151 if ($this->mLastSection
!== 'pre') {
2152 $paragraphStack = false;
2153 $output .= $this->closeParagraph().'<pre>';
2154 $this->mLastSection
= 'pre';
2156 $t = substr( $t, 1 );
2159 if ( trim($t) == '' ) {
2160 if ( $paragraphStack ) {
2161 $output .= $paragraphStack.'<br />';
2162 $paragraphStack = false;
2163 $this->mLastSection
= 'p';
2165 if ($this->mLastSection
!== 'p' ) {
2166 $output .= $this->closeParagraph();
2167 $this->mLastSection
= '';
2168 $paragraphStack = '<p>';
2170 $paragraphStack = '</p><p>';
2174 if ( $paragraphStack ) {
2175 $output .= $paragraphStack;
2176 $paragraphStack = false;
2177 $this->mLastSection
= 'p';
2178 } else if ($this->mLastSection
!== 'p') {
2179 $output .= $this->closeParagraph().'<p>';
2180 $this->mLastSection
= 'p';
2185 wfProfileOut( __METHOD__
."-paragraph" );
2187 // somewhere above we forget to get out of pre block (bug 785)
2188 if($preCloseMatch && $this->mInPre
) {
2189 $this->mInPre
= false;
2191 if ($paragraphStack === false) {
2195 while ( $prefixLength ) {
2196 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2199 if ( $this->mLastSection
!= '' ) {
2200 $output .= '</' . $this->mLastSection
. '>';
2201 $this->mLastSection
= '';
2204 wfProfileOut( __METHOD__
);
2209 * Split up a string on ':', ignoring any occurences inside tags
2210 * to prevent illegal overlapping.
2211 * @param string $str the string to split
2212 * @param string &$before set to everything before the ':'
2213 * @param string &$after set to everything after the ':'
2214 * return string the position of the ':', or false if none found
2216 function findColonNoLinks($str, &$before, &$after) {
2217 wfProfileIn( __METHOD__
);
2219 $pos = strpos( $str, ':' );
2220 if( $pos === false ) {
2222 wfProfileOut( __METHOD__
);
2226 $lt = strpos( $str, '<' );
2227 if( $lt === false ||
$lt > $pos ) {
2228 // Easy; no tag nesting to worry about
2229 $before = substr( $str, 0, $pos );
2230 $after = substr( $str, $pos+
1 );
2231 wfProfileOut( __METHOD__
);
2235 // Ugly state machine to walk through avoiding tags.
2236 $state = self
::COLON_STATE_TEXT
;
2238 $len = strlen( $str );
2239 for( $i = 0; $i < $len; $i++
) {
2243 // (Using the number is a performance hack for common cases)
2244 case 0: // self::COLON_STATE_TEXT:
2247 // Could be either a <start> tag or an </end> tag
2248 $state = self
::COLON_STATE_TAGSTART
;
2253 $before = substr( $str, 0, $i );
2254 $after = substr( $str, $i +
1 );
2255 wfProfileOut( __METHOD__
);
2258 // Embedded in a tag; don't break it.
2261 // Skip ahead looking for something interesting
2262 $colon = strpos( $str, ':', $i );
2263 if( $colon === false ) {
2264 // Nothing else interesting
2265 wfProfileOut( __METHOD__
);
2268 $lt = strpos( $str, '<', $i );
2269 if( $stack === 0 ) {
2270 if( $lt === false ||
$colon < $lt ) {
2272 $before = substr( $str, 0, $colon );
2273 $after = substr( $str, $colon +
1 );
2274 wfProfileOut( __METHOD__
);
2278 if( $lt === false ) {
2279 // Nothing else interesting to find; abort!
2280 // We're nested, but there's no close tags left. Abort!
2283 // Skip ahead to next tag start
2285 $state = self
::COLON_STATE_TAGSTART
;
2288 case 1: // self::COLON_STATE_TAG:
2293 $state = self
::COLON_STATE_TEXT
;
2296 // Slash may be followed by >?
2297 $state = self
::COLON_STATE_TAGSLASH
;
2303 case 2: // self::COLON_STATE_TAGSTART:
2306 $state = self
::COLON_STATE_CLOSETAG
;
2309 $state = self
::COLON_STATE_COMMENT
;
2312 // Illegal early close? This shouldn't happen D:
2313 $state = self
::COLON_STATE_TEXT
;
2316 $state = self
::COLON_STATE_TAG
;
2319 case 3: // self::COLON_STATE_CLOSETAG:
2324 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2325 wfProfileOut( __METHOD__
);
2328 $state = self
::COLON_STATE_TEXT
;
2331 case self
::COLON_STATE_TAGSLASH
:
2333 // Yes, a self-closed tag <blah/>
2334 $state = self
::COLON_STATE_TEXT
;
2336 // Probably we're jumping the gun, and this is an attribute
2337 $state = self
::COLON_STATE_TAG
;
2340 case 5: // self::COLON_STATE_COMMENT:
2342 $state = self
::COLON_STATE_COMMENTDASH
;
2345 case self
::COLON_STATE_COMMENTDASH
:
2347 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2349 $state = self
::COLON_STATE_COMMENT
;
2352 case self
::COLON_STATE_COMMENTDASHDASH
:
2354 $state = self
::COLON_STATE_TEXT
;
2356 $state = self
::COLON_STATE_COMMENT
;
2360 throw new MWException( "State machine error in " . __METHOD__
);
2364 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2367 wfProfileOut( __METHOD__
);
2372 * Return value of a magic variable (like PAGENAME)
2376 function getVariableValue( $index, $frame=false ) {
2377 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2378 global $wgScriptPath, $wgStylePath;
2381 * Some of these require message or data lookups and can be
2382 * expensive to check many times.
2384 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2385 if ( isset( $this->mVarCache
[$index] ) ) {
2386 return $this->mVarCache
[$index];
2390 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2391 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2394 global $wgLocaltimezone;
2395 if ( isset( $wgLocaltimezone ) ) {
2396 $oldtz = date_default_timezone_get();
2397 date_default_timezone_set( $wgLocaltimezone );
2400 $localTimestamp = date( 'YmdHis', $ts );
2401 $localMonth = date( 'm', $ts );
2402 $localMonth1 = date( 'n', $ts );
2403 $localMonthName = date( 'n', $ts );
2404 $localDay = date( 'j', $ts );
2405 $localDay2 = date( 'd', $ts );
2406 $localDayOfWeek = date( 'w', $ts );
2407 $localWeek = date( 'W', $ts );
2408 $localYear = date( 'Y', $ts );
2409 $localHour = date( 'H', $ts );
2410 if ( isset( $wgLocaltimezone ) ) {
2411 date_default_timezone_set( $oldtz );
2415 case 'currentmonth':
2416 $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2418 case 'currentmonth1':
2419 $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2421 case 'currentmonthname':
2422 $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2424 case 'currentmonthnamegen':
2425 $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2427 case 'currentmonthabbrev':
2428 $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2431 $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2434 $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2437 $value = $wgContLang->formatNum( $localMonth );
2440 $value = $wgContLang->formatNum( $localMonth1 );
2442 case 'localmonthname':
2443 $value = $wgContLang->getMonthName( $localMonthName );
2445 case 'localmonthnamegen':
2446 $value = $wgContLang->getMonthNameGen( $localMonthName );
2448 case 'localmonthabbrev':
2449 $value = $wgContLang->getMonthAbbreviation( $localMonthName );
2452 $value = $wgContLang->formatNum( $localDay );
2455 $value = $wgContLang->formatNum( $localDay2 );
2458 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2461 $value = $this->mTitle
->getPartialURL();
2463 case 'fullpagename':
2464 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2466 case 'fullpagenamee':
2467 $value = $this->mTitle
->getPrefixedURL();
2470 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2472 case 'subpagenamee':
2473 $value = $this->mTitle
->getSubpageUrlForm();
2475 case 'basepagename':
2476 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2478 case 'basepagenamee':
2479 $value = wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2481 case 'talkpagename':
2482 if( $this->mTitle
->canTalk() ) {
2483 $talkPage = $this->mTitle
->getTalkPage();
2484 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2489 case 'talkpagenamee':
2490 if( $this->mTitle
->canTalk() ) {
2491 $talkPage = $this->mTitle
->getTalkPage();
2492 $value = $talkPage->getPrefixedUrl();
2497 case 'subjectpagename':
2498 $subjPage = $this->mTitle
->getSubjectPage();
2499 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2501 case 'subjectpagenamee':
2502 $subjPage = $this->mTitle
->getSubjectPage();
2503 $value = $subjPage->getPrefixedUrl();
2506 $text = $this->mTitle
->getText();
2507 $value = $this->getPipeTrickText( $text );
2510 $text = $this->mTitle
->getText();
2511 $value = wfUrlEncode( str_replace( ' ', '_', $this->getPipeTrickText( $text ) ) );
2514 // Let the edit saving system know we should parse the page
2515 // *after* a revision ID has been assigned.
2516 $this->mOutput
->setFlag( 'vary-revision' );
2517 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2518 $value = $this->mRevisionId
;
2521 // Let the edit saving system know we should parse the page
2522 // *after* a revision ID has been assigned. This is for null edits.
2523 $this->mOutput
->setFlag( 'vary-revision' );
2524 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2525 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2527 case 'revisionday2':
2528 // Let the edit saving system know we should parse the page
2529 // *after* a revision ID has been assigned. This is for null edits.
2530 $this->mOutput
->setFlag( 'vary-revision' );
2531 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2532 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2534 case 'revisionmonth':
2535 // Let the edit saving system know we should parse the page
2536 // *after* a revision ID has been assigned. This is for null edits.
2537 $this->mOutput
->setFlag( 'vary-revision' );
2538 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2539 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2541 case 'revisionyear':
2542 // Let the edit saving system know we should parse the page
2543 // *after* a revision ID has been assigned. This is for null edits.
2544 $this->mOutput
->setFlag( 'vary-revision' );
2545 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2546 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2548 case 'revisiontimestamp':
2549 // Let the edit saving system know we should parse the page
2550 // *after* a revision ID has been assigned. This is for null edits.
2551 $this->mOutput
->setFlag( 'vary-revision' );
2552 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2553 $value = $this->getRevisionTimestamp();
2555 case 'revisionuser':
2556 // Let the edit saving system know we should parse the page
2557 // *after* a revision ID has been assigned. This is for null edits.
2558 $this->mOutput
->setFlag( 'vary-revision' );
2559 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2560 $value = $this->getRevisionUser();
2563 $value = str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2566 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2569 $value = $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2572 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2574 case 'subjectspace':
2575 $value = $this->mTitle
->getSubjectNsText();
2577 case 'subjectspacee':
2578 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2580 case 'currentdayname':
2581 $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2584 $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2587 $value = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2590 $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2593 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2594 // int to remove the padding
2595 $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2598 $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2600 case 'localdayname':
2601 $value = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2604 $value = $wgContLang->formatNum( $localYear, true );
2607 $value = $wgContLang->time( $localTimestamp, false, false );
2610 $value = $wgContLang->formatNum( $localHour, true );
2613 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2614 // int to remove the padding
2615 $value = $wgContLang->formatNum( (int)$localWeek );
2618 $value = $wgContLang->formatNum( $localDayOfWeek );
2620 case 'numberofarticles':
2621 $value = $wgContLang->formatNum( SiteStats
::articles() );
2623 case 'numberoffiles':
2624 $value = $wgContLang->formatNum( SiteStats
::images() );
2626 case 'numberofusers':
2627 $value = $wgContLang->formatNum( SiteStats
::users() );
2629 case 'numberofactiveusers':
2630 $value = $wgContLang->formatNum( SiteStats
::activeUsers() );
2632 case 'numberofpages':
2633 $value = $wgContLang->formatNum( SiteStats
::pages() );
2635 case 'numberofadmins':
2636 $value = $wgContLang->formatNum( SiteStats
::numberingroup('sysop') );
2638 case 'numberofedits':
2639 $value = $wgContLang->formatNum( SiteStats
::edits() );
2641 case 'numberofviews':
2642 $value = $wgContLang->formatNum( SiteStats
::views() );
2644 case 'currenttimestamp':
2645 $value = wfTimestamp( TS_MW
, $ts );
2647 case 'localtimestamp':
2648 $value = $localTimestamp;
2650 case 'currentversion':
2651 $value = SpecialVersion
::getVersion();
2658 return $wgServerName;
2660 return $wgScriptPath;
2662 return $wgStylePath;
2663 case 'directionmark':
2664 return $wgContLang->getDirMark();
2665 case 'contentlanguage':
2666 global $wgContLanguageCode;
2667 return $wgContLanguageCode;
2670 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) )
2677 $this->mVarCache
[$index] = $value;
2683 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2687 function initialiseVariables() {
2688 wfProfileIn( __METHOD__
);
2689 $variableIDs = MagicWord
::getVariableIDs();
2690 $substIDs = MagicWord
::getSubstIDs();
2692 $this->mVariables
= new MagicWordArray( $variableIDs );
2693 $this->mSubsts
= new MagicWordArray( $substIDs );
2694 wfProfileOut( __METHOD__
);
2698 * Preprocess some wikitext and return the document tree.
2699 * This is the ghost of replace_variables().
2701 * @param string $text The text to parse
2702 * @param integer flags Bitwise combination of:
2703 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2704 * included. Default is to assume a direct page view.
2706 * The generated DOM tree must depend only on the input text and the flags.
2707 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2709 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2710 * change in the DOM tree for a given text, must be passed through the section identifier
2711 * in the section edit link and thus back to extractSections().
2713 * The output of this function is currently only cached in process memory, but a persistent
2714 * cache may be implemented at a later date which takes further advantage of these strict
2715 * dependency requirements.
2719 function preprocessToDom ( $text, $flags = 0 ) {
2720 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2725 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2727 public static function splitWhitespace( $s ) {
2728 $ltrimmed = ltrim( $s );
2729 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2730 $trimmed = rtrim( $ltrimmed );
2731 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2733 $w2 = substr( $ltrimmed, -$diff );
2737 return array( $w1, $trimmed, $w2 );
2741 * Replace magic variables, templates, and template arguments
2742 * with the appropriate text. Templates are substituted recursively,
2743 * taking care to avoid infinite loops.
2745 * Note that the substitution depends on value of $mOutputType:
2746 * self::OT_WIKI: only {{subst:}} templates
2747 * self::OT_PREPROCESS: templates but not extension tags
2748 * self::OT_HTML: all templates and extension tags
2750 * @param string $tex The text to transform
2751 * @param PPFrame $frame Object describing the arguments passed to the template.
2752 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2753 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2754 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2757 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2758 # Is there any text? Also, Prevent too big inclusions!
2759 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2762 wfProfileIn( __METHOD__
);
2764 if ( $frame === false ) {
2765 $frame = $this->getPreprocessor()->newFrame();
2766 } elseif ( !( $frame instanceof PPFrame
) ) {
2767 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2768 $frame = $this->getPreprocessor()->newCustomFrame($frame);
2771 $dom = $this->preprocessToDom( $text );
2772 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2773 $text = $frame->expand( $dom, $flags );
2775 wfProfileOut( __METHOD__
);
2779 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2780 static function createAssocArgs( $args ) {
2781 $assocArgs = array();
2783 foreach( $args as $arg ) {
2784 $eqpos = strpos( $arg, '=' );
2785 if ( $eqpos === false ) {
2786 $assocArgs[$index++
] = $arg;
2788 $name = trim( substr( $arg, 0, $eqpos ) );
2789 $value = trim( substr( $arg, $eqpos+
1 ) );
2790 if ( $value === false ) {
2793 if ( $name !== false ) {
2794 $assocArgs[$name] = $value;
2803 * Warn the user when a parser limitation is reached
2804 * Will warn at most once the user per limitation type
2806 * @param string $limitationType, should be one of:
2807 * 'expensive-parserfunction' (corresponding messages: 'expensive-parserfunction-warning', 'expensive-parserfunction-category')
2808 * 'post-expand-template-argument' (corresponding messages: 'post-expand-template-argument-warning', 'post-expand-template-argument-category')
2809 * 'post-expand-template-inclusion' (corresponding messages: 'post-expand-template-inclusion-warning', 'post-expand-template-inclusion-category')
2810 * @params int $current, $max When an explicit limit has been
2811 * exceeded, provide the values (optional)
2813 function limitationWarn( $limitationType, $current=null, $max=null) {
2814 //does no harm if $current and $max are present but are unnecessary for the message
2815 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
2816 $this->mOutput
->addWarning( $warning );
2817 $this->addTrackingCategory( "$limitationType-category" );
2821 * Return the text of a template, after recursively
2822 * replacing any variables or templates within the template.
2824 * @param array $piece The parts of the template
2825 * $piece['title']: the title, i.e. the part before the |
2826 * $piece['parts']: the parameter array
2827 * $piece['lineStart']: whether the brace was at the start of a line
2828 * @param PPFrame The current frame, contains template arguments
2829 * @return string the text of the template
2832 function braceSubstitution( $piece, $frame ) {
2833 global $wgContLang, $wgNonincludableNamespaces;
2834 wfProfileIn( __METHOD__
);
2835 wfProfileIn( __METHOD__
.'-setup' );
2838 $found = false; # $text has been filled
2839 $nowiki = false; # wiki markup in $text should be escaped
2840 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2841 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2842 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2843 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2845 # Title object, where $text came from
2848 # $part1 is the bit before the first |, and must contain only title characters.
2849 # Various prefixes will be stripped from it later.
2850 $titleWithSpaces = $frame->expand( $piece['title'] );
2851 $part1 = trim( $titleWithSpaces );
2854 # Original title text preserved for various purposes
2855 $originalTitle = $part1;
2857 # $args is a list of argument nodes, starting from index 0, not including $part1
2858 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2859 wfProfileOut( __METHOD__
.'-setup' );
2862 wfProfileIn( __METHOD__
.'-modifiers' );
2865 $substMatch = $this->mSubsts
->matchStartAndRemove( $part1 );
2867 # Possibilities for substMatch: "subst", "safesubst" or FALSE
2868 # Whether to include depends also on whether we are in the pre-save-transform
2870 # safesubst || (subst && PST) || (false && !PST) => transclude (skip the if)
2871 # (false && PST) || (subst && !PST) => return input (handled by if)
2872 if ( $substMatch != 'safesubst' && ($substMatch == 'subst' xor $this->ot
['wiki']) ) {
2873 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2880 if ( !$found && $args->getLength() == 0 ) {
2881 $id = $this->mVariables
->matchStartToEnd( $part1 );
2882 if ( $id !== false ) {
2883 $text = $this->getVariableValue( $id, $frame );
2884 if (MagicWord
::getCacheTTL($id)>-1)
2885 $this->mOutput
->mContainsOldMagic
= true;
2890 # MSG, MSGNW and RAW
2893 $mwMsgnw = MagicWord
::get( 'msgnw' );
2894 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2897 # Remove obsolete MSG:
2898 $mwMsg = MagicWord
::get( 'msg' );
2899 $mwMsg->matchStartAndRemove( $part1 );
2903 $mwRaw = MagicWord
::get( 'raw' );
2904 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2905 $forceRawInterwiki = true;
2908 wfProfileOut( __METHOD__
.'-modifiers' );
2912 wfProfileIn( __METHOD__
. '-pfunc' );
2914 $colonPos = strpos( $part1, ':' );
2915 if ( $colonPos !== false ) {
2916 # Case sensitive functions
2917 $function = substr( $part1, 0, $colonPos );
2918 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2919 $function = $this->mFunctionSynonyms
[1][$function];
2921 # Case insensitive functions
2922 $function = $wgContLang->lc( $function );
2923 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2924 $function = $this->mFunctionSynonyms
[0][$function];
2930 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2931 $initialArgs = array( &$this );
2932 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2933 if ( $flags & SFH_OBJECT_ARGS
) {
2934 # Add a frame parameter, and pass the arguments as an array
2935 $allArgs = $initialArgs;
2936 $allArgs[] = $frame;
2937 for ( $i = 0; $i < $args->getLength(); $i++
) {
2938 $funcArgs[] = $args->item( $i );
2940 $allArgs[] = $funcArgs;
2942 # Convert arguments to plain text
2943 for ( $i = 0; $i < $args->getLength(); $i++
) {
2944 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2946 $allArgs = array_merge( $initialArgs, $funcArgs );
2949 # Workaround for PHP bug 35229 and similar
2950 if ( !is_callable( $callback ) ) {
2951 wfProfileOut( __METHOD__
. '-pfunc' );
2952 wfProfileOut( __METHOD__
);
2953 throw new MWException( "Tag hook for $function is not callable\n" );
2955 $result = call_user_func_array( $callback, $allArgs );
2958 $preprocessFlags = 0;
2960 if ( is_array( $result ) ) {
2961 if ( isset( $result[0] ) ) {
2963 unset( $result[0] );
2966 // Extract flags into the local scope
2967 // This allows callers to set flags such as nowiki, found, etc.
2973 $text = $this->preprocessToDom( $text, $preprocessFlags );
2978 wfProfileOut( __METHOD__
. '-pfunc' );
2981 # Finish mangling title and then check for loops.
2982 # Set $title to a Title object and $titleText to the PDBK
2985 # Split the title into page and subpage
2987 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2988 if ($subpage !== '') {
2989 $ns = $this->mTitle
->getNamespace();
2991 $title = Title
::newFromText( $part1, $ns );
2993 $titleText = $title->getPrefixedText();
2994 # Check for language variants if the template is not found
2995 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2996 $wgContLang->findVariantLink( $part1, $title, true );
2998 # Do recursion depth check
2999 $limit = $this->mOptions
->getMaxTemplateDepth();
3000 if ( $frame->depth
>= $limit ) {
3002 $text = '<span class="error">' . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit ) . '</span>';
3007 # Load from database
3008 if ( !$found && $title ) {
3009 wfProfileIn( __METHOD__
. '-loadtpl' );
3010 if ( !$title->isExternal() ) {
3011 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
3012 $text = SpecialPage
::capturePath( $title );
3013 if ( is_string( $text ) ) {
3016 $this->disableCache();
3018 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3019 $found = false; //access denied
3020 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3022 list( $text, $title ) = $this->getTemplateDom( $title );
3023 if ( $text !== false ) {
3029 # If the title is valid but undisplayable, make a link to it
3030 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3031 $text = "[[:$titleText]]";
3034 } elseif ( $title->isTrans() ) {
3035 // Interwiki transclusion
3036 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3037 $text = $this->interwikiTransclude( $title, 'render' );
3040 $text = $this->interwikiTransclude( $title, 'raw' );
3041 // Preprocess it like a template
3042 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3048 # Do infinite loop check
3049 # This has to be done after redirect resolution to avoid infinite loops via redirects
3050 if ( !$frame->loopCheck( $title ) ) {
3052 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3053 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3055 wfProfileOut( __METHOD__
. '-loadtpl' );
3058 # If we haven't found text to substitute by now, we're done
3059 # Recover the source wikitext and return it
3061 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3062 wfProfileOut( __METHOD__
);
3063 return array( 'object' => $text );
3066 # Expand DOM-style return values in a child frame
3067 if ( $isChildObj ) {
3068 # Clean up argument array
3069 $newFrame = $frame->newChild( $args, $title );
3072 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3073 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3074 # Expansion is eligible for the empty-frame cache
3075 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3076 $text = $this->mTplExpandCache
[$titleText];
3078 $text = $newFrame->expand( $text );
3079 $this->mTplExpandCache
[$titleText] = $text;
3082 # Uncached expansion
3083 $text = $newFrame->expand( $text );
3086 if ( $isLocalObj && $nowiki ) {
3087 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3088 $isLocalObj = false;
3091 # Replace raw HTML by a placeholder
3092 # Add a blank line preceding, to prevent it from mucking up
3093 # immediately preceding headings
3095 $text = "\n\n" . $this->insertStripItem( $text );
3097 # Escape nowiki-style return values
3098 elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3099 $text = wfEscapeWikiText( $text );
3101 # Bug 529: if the template begins with a table or block-level
3102 # element, it should be treated as beginning a new line.
3103 # This behaviour is somewhat controversial.
3104 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3105 $text = "\n" . $text;
3108 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3109 # Error, oversize inclusion
3110 $text = "[[$originalTitle]]" .
3111 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3112 $this->limitationWarn( 'post-expand-template-inclusion' );
3115 if ( $isLocalObj ) {
3116 $ret = array( 'object' => $text );
3118 $ret = array( 'text' => $text );
3121 wfProfileOut( __METHOD__
);
3126 * Get the semi-parsed DOM representation of a template with a given title,
3127 * and its redirect destination title. Cached.
3129 function getTemplateDom( $title ) {
3130 $cacheTitle = $title;
3131 $titleText = $title->getPrefixedDBkey();
3133 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3134 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3135 $title = Title
::makeTitle( $ns, $dbk );
3136 $titleText = $title->getPrefixedDBkey();
3138 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3139 return array( $this->mTplDomCache
[$titleText], $title );
3142 // Cache miss, go to the database
3143 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3145 if ( $text === false ) {
3146 $this->mTplDomCache
[$titleText] = false;
3147 return array( false, $title );
3150 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3151 $this->mTplDomCache
[ $titleText ] = $dom;
3153 if (! $title->equals($cacheTitle)) {
3154 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3155 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3158 return array( $dom, $title );
3162 * Fetch the unparsed text of a template and register a reference to it.
3164 function fetchTemplateAndTitle( $title ) {
3165 $templateCb = $this->mOptions
->getTemplateCallback();
3166 $stuff = call_user_func( $templateCb, $title, $this );
3167 $text = $stuff['text'];
3168 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3169 if ( isset( $stuff['deps'] ) ) {
3170 foreach ( $stuff['deps'] as $dep ) {
3171 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3174 return array($text,$finalTitle);
3177 function fetchTemplate( $title ) {
3178 $rv = $this->fetchTemplateAndTitle($title);
3183 * Static function to get a template
3184 * Can be overridden via ParserOptions::setTemplateCallback().
3186 static function statelessFetchTemplate( $title, $parser=false ) {
3187 $text = $skip = false;
3188 $finalTitle = $title;
3191 // Loop to fetch the article, with up to 1 redirect
3192 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3193 # Give extensions a chance to select the revision instead
3194 $id = false; // Assume current
3195 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3201 'page_id' => $title->getArticleID(),
3205 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3206 $rev_id = $rev ?
$rev->getId() : 0;
3207 // If there is no current revision, there is no page
3208 if( $id === false && !$rev ) {
3209 $linkCache = LinkCache
::singleton();
3210 $linkCache->addBadLinkObj( $title );
3215 'page_id' => $title->getArticleID(),
3216 'rev_id' => $rev_id );
3219 $text = $rev->getText();
3220 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3222 $message = $wgContLang->lcfirst( $title->getText() );
3223 $text = wfMsgForContentNoTrans( $message );
3224 if( wfEmptyMsg( $message, $text ) ) {
3231 if ( $text === false ) {
3235 $finalTitle = $title;
3236 $title = Title
::newFromRedirect( $text );
3240 'finalTitle' => $finalTitle,
3245 * Transclude an interwiki link.
3247 function interwikiTransclude( $title, $action ) {
3248 global $wgEnableScaryTranscluding;
3250 if (!$wgEnableScaryTranscluding)
3251 return wfMsg('scarytranscludedisabled');
3253 $url = $title->getFullUrl( "action=$action" );
3255 if (strlen($url) > 255)
3256 return wfMsg('scarytranscludetoolong');
3257 return $this->fetchScaryTemplateMaybeFromCache($url);
3260 function fetchScaryTemplateMaybeFromCache($url) {
3261 global $wgTranscludeCacheExpiry;
3262 $dbr = wfGetDB(DB_SLAVE
);
3263 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3264 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3265 array('tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3267 return $obj->tc_contents
;
3270 $text = Http
::get($url);
3272 return wfMsg('scarytranscludefailed', $url);
3274 $dbw = wfGetDB(DB_MASTER
);
3275 $dbw->replace('transcache', array('tc_url'), array(
3277 'tc_time' => $dbw->timestamp( time() ),
3278 'tc_contents' => $text));
3284 * Triple brace replacement -- used for template arguments
3287 function argSubstitution( $piece, $frame ) {
3288 wfProfileIn( __METHOD__
);
3291 $parts = $piece['parts'];
3292 $nameWithSpaces = $frame->expand( $piece['title'] );
3293 $argName = trim( $nameWithSpaces );
3295 $text = $frame->getArgument( $argName );
3296 if ( $text === false && $parts->getLength() > 0
3300 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3303 # No match in frame, use the supplied default
3304 $object = $parts->item( 0 )->getChildren();
3306 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3307 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3308 $this->limitationWarn( 'post-expand-template-argument' );
3311 if ( $text === false && $object === false ) {
3313 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3315 if ( $error !== false ) {
3318 if ( $object !== false ) {
3319 $ret = array( 'object' => $object );
3321 $ret = array( 'text' => $text );
3324 wfProfileOut( __METHOD__
);
3329 * Return the text to be used for a given extension tag.
3330 * This is the ghost of strip().
3332 * @param array $params Associative array of parameters:
3333 * name PPNode for the tag name
3334 * attr PPNode for unparsed text where tag attributes are thought to be
3335 * attributes Optional associative array of parsed attributes
3336 * inner Contents of extension element
3337 * noClose Original text did not have a close tag
3338 * @param PPFrame $frame
3340 function extensionSubstitution( $params, $frame ) {
3341 global $wgRawHtml, $wgContLang;
3343 $name = $frame->expand( $params['name'] );
3344 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3345 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3346 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3348 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3349 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3350 if ( $isFunctionTag ) {
3351 $markerType = 'none';
3353 $markerType = 'general';
3355 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3356 $name = strtolower( $name );
3357 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3358 if ( isset( $params['attributes'] ) ) {
3359 $attributes = $attributes +
$params['attributes'];
3362 if( isset( $this->mTagHooks
[$name] ) ) {
3363 # Workaround for PHP bug 35229 and similar
3364 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3365 throw new MWException( "Tag hook for $name is not callable\n" );
3367 $output = call_user_func_array( $this->mTagHooks
[$name],
3368 array( $content, $attributes, $this, $frame ) );
3369 } elseif( isset( $this->mFunctionTagHooks
[$name] ) ) {
3370 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3371 if( !is_callable( $callback ) )
3372 throw new MWException( "Tag hook for $name is not callable\n" );
3374 $output = call_user_func_array( $callback,
3375 array( &$this, $frame, $content, $attributes ) );
3377 $output = '<span class="error">Invalid tag extension name: ' .
3378 htmlspecialchars( $name ) . '</span>';
3381 if ( is_array( $output ) ) {
3382 // Extract flags to local scope (to override $markerType)
3384 $output = $flags[0];
3389 if ( is_null( $attrText ) ) {
3392 if ( isset( $params['attributes'] ) ) {
3393 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3394 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3395 htmlspecialchars( $attrValue ) . '"';
3398 if ( $content === null ) {
3399 $output = "<$name$attrText/>";
3401 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3402 $output = "<$name$attrText>$content$close";
3406 if( $markerType === 'none' ) {
3408 } elseif ( $markerType === 'nowiki' ) {
3409 $this->mStripState
->nowiki
->setPair( $marker, $output );
3410 } elseif ( $markerType === 'general' ) {
3411 $this->mStripState
->general
->setPair( $marker, $output );
3413 throw new MWException( __METHOD__
.': invalid marker type' );
3419 * Increment an include size counter
3421 * @param string $type The type of expansion
3422 * @param integer $size The size of the text
3423 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3425 function incrementIncludeSize( $type, $size ) {
3426 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3429 $this->mIncludeSizes
[$type] +
= $size;
3435 * Increment the expensive function count
3437 * @return boolean False if the limit has been exceeded
3439 function incrementExpensiveFunctionCount() {
3440 global $wgExpensiveParserFunctionLimit;
3441 $this->mExpensiveFunctionCount++
;
3442 if($this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit) {
3449 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3450 * Fills $this->mDoubleUnderscores, returns the modified text
3452 function doDoubleUnderscore( $text ) {
3453 wfProfileIn( __METHOD__
);
3455 // The position of __TOC__ needs to be recorded
3456 $mw = MagicWord
::get( 'toc' );
3457 if( $mw->match( $text ) ) {
3458 $this->mShowToc
= true;
3459 $this->mForceTocPosition
= true;
3461 // Set a placeholder. At the end we'll fill it in with the TOC.
3462 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3464 // Only keep the first one.
3465 $text = $mw->replace( '', $text );
3468 // Now match and remove the rest of them
3469 $mwa = MagicWord
::getDoubleUnderscoreArray();
3470 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3472 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3473 $this->mOutput
->mNoGallery
= true;
3475 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3476 $this->mShowToc
= false;
3478 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3479 $this->mOutput
->setProperty( 'hiddencat', 'y' );
3480 $this->addTrackingCategory( 'hidden-category-category' );
3482 # (bug 8068) Allow control over whether robots index a page.
3484 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3485 # is not desirable, the last one on the page should win.
3486 if( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3487 $this->mOutput
->setIndexPolicy( 'noindex' );
3488 $this->addTrackingCategory( 'noindex-category' );
3490 if( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ){
3491 $this->mOutput
->setIndexPolicy( 'index' );
3492 $this->addTrackingCategory( 'index-category' );
3495 wfProfileOut( __METHOD__
);
3500 * Add a tracking category, getting the title from a system message,
3501 * or print a debug message if the title is invalid.
3502 * @param $msg String message key
3503 * @return Bool whether the addition was successful
3505 protected function addTrackingCategory( $msg ){
3506 $cat = wfMsgForContent( $msg );
3508 # Allow tracking categories to be disabled by setting them to "-"
3509 if( $cat === '-' ) return false;
3511 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3512 if ( $containerCategory ) {
3513 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3516 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3522 * This function accomplishes several tasks:
3523 * 1) Auto-number headings if that option is enabled
3524 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3525 * 3) Add a Table of contents on the top for users who have enabled the option
3526 * 4) Auto-anchor headings
3528 * It loops through all headlines, collects the necessary data, then splits up the
3529 * string and re-inserts the newly formatted headlines.
3531 * @param string $text
3532 * @param string $origText Original, untouched wikitext
3533 * @param boolean $isMain
3536 function formatHeadings( $text, $origText, $isMain=true ) {
3537 global $wgMaxTocLevel, $wgContLang, $wgHtml5, $wgExperimentalHtmlIds;
3539 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3540 $showEditLink = $this->mOptions
->getEditSection();
3542 // Do not call quickUserCan unless necessary
3543 if( $showEditLink && !$this->mTitle
->quickUserCan( 'edit' ) ) {
3547 # Inhibit editsection links if requested in the page
3548 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ||
$this->mOptions
->getIsPrintable() ) {
3552 # Get all headlines for numbering them and adding funky stuff like [edit]
3553 # links - this is for later, but we need the number of headlines right now
3555 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3557 # if there are fewer than 4 headlines in the article, do not show TOC
3558 # unless it's been explicitly enabled.
3559 $enoughToc = $this->mShowToc
&&
3560 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3562 # Allow user to stipulate that a page should have a "new section"
3563 # link added via __NEWSECTIONLINK__
3564 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3565 $this->mOutput
->setNewSection( true );
3568 # Allow user to remove the "new section"
3569 # link via __NONEWSECTIONLINK__
3570 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3571 $this->mOutput
->hideNewSection( true );
3574 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3575 # override above conditions and always show TOC above first header
3576 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3577 $this->mShowToc
= true;
3581 # We need this to perform operations on the HTML
3582 $sk = $this->mOptions
->getSkin();
3588 # Ugh .. the TOC should have neat indentation levels which can be
3589 # passed to the skin functions. These are determined here
3593 $sublevelCount = array();
3594 $levelCount = array();
3600 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3601 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3602 $oldType = $this->mOutputType
;
3603 $this->setOutputType( self
::OT_WIKI
);
3604 $frame = $this->getPreprocessor()->newFrame();
3605 $root = $this->preprocessToDom( $origText );
3606 $node = $root->getFirstChild();
3610 foreach( $matches[3] as $headline ) {
3611 $isTemplate = false;
3613 $sectionIndex = false;
3615 $markerMatches = array();
3616 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3617 $serial = $markerMatches[1];
3618 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3619 $isTemplate = ($titleText != $baseTitleText);
3620 $headline = preg_replace("/^$markerRegex/", "", $headline);
3624 $prevlevel = $level;
3625 $prevtoclevel = $toclevel;
3627 $level = $matches[1][$headlineCount];
3629 if ( $level > $prevlevel ) {
3630 # Increase TOC level
3632 $sublevelCount[$toclevel] = 0;
3633 if( $toclevel<$wgMaxTocLevel ) {
3634 $prevtoclevel = $toclevel;
3635 $toc .= $sk->tocIndent();
3639 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3640 # Decrease TOC level, find level to jump to
3642 for ($i = $toclevel; $i > 0; $i--) {
3643 if ( $levelCount[$i] == $level ) {
3644 # Found last matching level
3648 elseif ( $levelCount[$i] < $level ) {
3649 # Found first matching level below current level
3654 if( $i == 0 ) $toclevel = 1;
3655 if( $toclevel<$wgMaxTocLevel ) {
3656 if($prevtoclevel < $wgMaxTocLevel) {
3657 # Unindent only if the previous toc level was shown :p
3658 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3659 $prevtoclevel = $toclevel;
3661 $toc .= $sk->tocLineEnd();
3666 # No change in level, end TOC line
3667 if( $toclevel<$wgMaxTocLevel ) {
3668 $toc .= $sk->tocLineEnd();
3672 $levelCount[$toclevel] = $level;
3674 # count number of headlines for each level
3675 @$sublevelCount[$toclevel]++
;
3677 for( $i = 1; $i <= $toclevel; $i++
) {
3678 if( !empty( $sublevelCount[$i] ) ) {
3682 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3687 # The safe header is a version of the header text safe to use for links
3688 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3689 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3691 # Remove link placeholders by the link text.
3692 # <!--LINK number-->
3694 # link text with suffix
3695 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3697 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3698 $tocline = preg_replace(
3699 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3703 $tocline = trim( $tocline );
3705 # For the anchor, strip out HTML-y stuff period
3706 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3707 $safeHeadline = preg_replace( '/[ _]+/', ' ', $safeHeadline );
3708 $safeHeadline = trim( $safeHeadline );
3710 # Save headline for section edit hint before it's escaped
3711 $headlineHint = $safeHeadline;
3713 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
3714 # For reverse compatibility, provide an id that's
3715 # HTML4-compatible, like we used to.
3717 # It may be worth noting, academically, that it's possible for
3718 # the legacy anchor to conflict with a non-legacy headline
3719 # anchor on the page. In this case likely the "correct" thing
3720 # would be to either drop the legacy anchors or make sure
3721 # they're numbered first. However, this would require people
3722 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3723 # manually, so let's not bother worrying about it.
3724 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
3725 array( 'noninitial', 'legacy' ) );
3726 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3728 if ( $legacyHeadline == $safeHeadline ) {
3729 # No reason to have both (in fact, we can't)
3730 $legacyHeadline = false;
3733 $legacyHeadline = false;
3734 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
3738 # HTML names must be case-insensitively unique (bug 10721). FIXME:
3739 # Does this apply to Unicode characters? Because we aren't
3740 # handling those here.
3741 $arrayKey = strtolower( $safeHeadline );
3742 if ( $legacyHeadline === false ) {
3743 $legacyArrayKey = false;
3745 $legacyArrayKey = strtolower( $legacyHeadline );
3748 # count how many in assoc. array so we can track dupes in anchors
3749 if ( isset( $refers[$arrayKey] ) ) {
3750 $refers[$arrayKey]++
;
3752 $refers[$arrayKey] = 1;
3754 if ( isset( $refers[$legacyArrayKey] ) ) {
3755 $refers[$legacyArrayKey]++
;
3757 $refers[$legacyArrayKey] = 1;
3760 # Don't number the heading if it is the only one (looks silly)
3761 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3762 # the two are different if the line contains a link
3763 $headline = $numbering . ' ' . $headline;
3766 # Create the anchor for linking from the TOC to the section
3767 $anchor = $safeHeadline;
3768 $legacyAnchor = $legacyHeadline;
3769 if ( $refers[$arrayKey] > 1 ) {
3770 $anchor .= '_' . $refers[$arrayKey];
3772 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3773 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3775 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3776 $toc .= $sk->tocLine($anchor, $tocline,
3777 $numbering, $toclevel, ($isTemplate ?
false : $sectionIndex));
3780 # Add the section to the section tree
3781 # Find the DOM node for this header
3782 while ( $node && !$isTemplate ) {
3783 if ( $node->getName() === 'h' ) {
3784 $bits = $node->splitHeading();
3785 if ( $bits['i'] == $sectionIndex )
3788 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
3789 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
3790 $node = $node->getNextSibling();
3793 'toclevel' => $toclevel,
3796 'number' => $numbering,
3797 'index' => ($isTemplate ?
'T-' : '' ) . $sectionIndex,
3798 'fromtitle' => $titleText,
3799 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
3800 'anchor' => $anchor,
3803 # give headline the correct <h#> tag
3804 if( $showEditLink && $sectionIndex !== false ) {
3806 # Put a T flag in the section identifier, to indicate to extractSections()
3807 # that sections inside <includeonly> should be counted.
3808 $editlink = $sk->doEditSectionLink(Title
::newFromText( $titleText ), "T-$sectionIndex");
3810 $editlink = $sk->doEditSectionLink($this->mTitle
, $sectionIndex, $headlineHint);
3815 $head[$headlineCount] = $sk->makeHeadline( $level,
3816 $matches['attrib'][$headlineCount], $anchor, $headline,
3817 $editlink, $legacyAnchor );
3822 $this->setOutputType( $oldType );
3824 # Never ever show TOC if no headers
3825 if( $numVisible < 1 ) {
3830 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3831 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3833 $toc = $sk->tocList( $toc );
3834 $this->mOutput
->setTOCHTML( $toc );
3838 $this->mOutput
->setSections( $tocraw );
3841 # split up and insert constructed headlines
3843 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3846 foreach( $blocks as $block ) {
3847 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3848 # This is the [edit] link that appears for the top block of text when
3849 # section editing is enabled
3851 # Disabled because it broke block formatting
3852 # For example, a bullet point in the top line
3853 # $full .= $sk->editSectionLink(0);
3856 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3857 # Top anchor now in skin
3861 if( !empty( $head[$i] ) ) {
3866 if( $this->mForceTocPosition
) {
3867 return str_replace( '<!--MWTOC-->', $toc, $full );
3874 * Merge $tree2 into $tree1 by replacing the section with index
3875 * $section in $tree1 and its descendants with the sections in $tree2.
3876 * Note that in the returned section tree, only the 'index' and
3877 * 'byteoffset' fields are guaranteed to be correct.
3878 * @param $tree1 array Section tree from ParserOutput::getSectons()
3879 * @param $tree2 array Section tree
3880 * @param $section int Section index
3881 * @param $title Title Title both section trees come from
3882 * @param $len2 int Length of the original wikitext for $tree2
3883 * @return array Merged section tree
3885 public static function mergeSectionTrees( $tree1, $tree2, $section, $title, $len2 ) {
3888 $targetLevel = false;
3892 $numbering = array( 0 );
3893 $titletext = $title->getPrefixedDBkey();
3894 foreach ( $tree1 as $s ) {
3895 if ( $targetLevel !== false ) {
3896 if ( $s['level'] <= $targetLevel )
3897 // We've skipped enough
3898 $targetLevel = false;
3902 if ( $s['index'] != $section ||
3903 $s['fromtitle'] != $titletext ) {
3904 self
::incrementNumbering( $numbering,
3905 $s['toclevel'], $lastLevel );
3907 // Rewrite index, byteoffset and number
3908 if ( $s['fromtitle'] == $titletext ) {
3909 $s['index'] = $nextIndex++
;
3911 $s['byteoffset'] +
= $len2;
3913 $s['number'] = implode( '.', array_map(
3914 array( $wgContLang, 'formatnum' ),
3916 $lastLevel = $s['toclevel'];
3919 // We're at $section
3920 // Insert sections from $tree2 here
3921 foreach ( $tree2 as $s2 ) {
3922 // Rewrite the fields in $s2
3923 // before inserting it
3924 $s2['toclevel'] +
= $s['toclevel'] - 1;
3925 $s2['level'] +
= $s['level'] - 1;
3926 $s2['index'] = $nextIndex++
;
3927 $s2['byteoffset'] +
= $s['byteoffset'];
3929 self
::incrementNumbering( $numbering,
3930 $s2['toclevel'], $lastLevel );
3931 $s2['number'] = implode( '.', array_map(
3932 array( $wgContLang, 'formatnum' ),
3934 $lastLevel = $s2['toclevel'];
3937 // Skip all descendants of $section in $tree1
3938 $targetLevel = $s['level'];
3946 * Increment a section number. Helper function for mergeSectionTrees()
3947 * @param $number array Array representing a section number
3948 * @param $level int Current TOC level (depth)
3949 * @param $lastLevel int Level of previous TOC entry
3951 private static function incrementNumbering( &$number, $level, $lastLevel ) {
3952 if ( $level > $lastLevel )
3953 $number[$level - 1] = 1;
3954 else if ( $level < $lastLevel ) {
3955 foreach ( $number as $key => $unused )
3956 if ( $key >= $level )
3957 unset( $number[$key] );
3958 $number[$level - 1]++
;
3960 $number[$level - 1]++
;
3964 * Transform wiki markup when saving a page by doing \r\n -> \n
3965 * conversion, substitting signatures, {{subst:}} templates, etc.
3967 * @param string $text the text to transform
3968 * @param Title &$title the Title object for the current article
3969 * @param User $user the User object describing the current user
3970 * @param ParserOptions $options parsing options
3971 * @param bool $clearState whether to clear the parser state first
3972 * @return string the altered wiki markup
3975 function preSaveTransform( $text, Title
$title, $user, $options, $clearState = true ) {
3976 $this->mOptions
= $options;
3977 $this->setTitle( $title );
3978 $this->setOutputType( self
::OT_WIKI
);
3980 if ( $clearState ) {
3981 $this->clearState();
3987 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3988 $text = $this->pstPass2( $text, $user );
3989 $text = $this->mStripState
->unstripBoth( $text );
3994 * Pre-save transform helper function
3997 function pstPass2( $text, $user ) {
3998 global $wgContLang, $wgLocaltimezone;
4000 /* Note: This is the timestamp saved as hardcoded wikitext to
4001 * the database, we use $wgContLang here in order to give
4002 * everyone the same signature and use the default one rather
4003 * than the one selected in each user's preferences.
4005 * (see also bug 12815)
4007 $ts = $this->mOptions
->getTimestamp();
4008 if ( isset( $wgLocaltimezone ) ) {
4009 $tz = $wgLocaltimezone;
4011 $tz = date_default_timezone_get();
4014 $unixts = wfTimestamp( TS_UNIX
, $ts );
4015 $oldtz = date_default_timezone_get();
4016 date_default_timezone_set( $tz );
4017 $ts = date( 'YmdHis', $unixts );
4018 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4020 /* Allow translation of timezones trough wiki. date() can return
4021 * whatever crap the system uses, localised or not, so we cannot
4022 * ship premade translations.
4024 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4025 $value = wfMsgForContent( $key );
4026 if ( !wfEmptyMsg( $key, $value ) ) $tzMsg = $value;
4028 date_default_timezone_set( $oldtz );
4030 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4032 # Variable replacement
4033 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4034 $text = $this->replaceVariables( $text );
4037 $sigText = $this->getUserSig( $user );
4038 $text = strtr( $text, array(
4040 '~~~~' => "$sigText $d",
4044 # Links of the form [[|<blah>]] or [[<blah>|]] perform pipe tricks
4045 # Note this only allows the # in the position it works.
4046 global $wgLegalTitleChars;
4047 $pipeTrickRe = "/\[\[(?:(\\|)([$wgLegalTitleChars]+)|([#$wgLegalTitleChars]+)\\|)\]\]/";
4048 $text = preg_replace_callback( $pipeTrickRe, array( $this, 'pstPipeTrickCallback' ), $text );
4050 # Trim trailing whitespace
4051 $text = rtrim( $text );
4057 * Called from pstPass2 to perform the pipe trick on links.
4058 * Original was either [[|text]] or [[link|]]
4060 * @param Array ("|" or "", text, link) $m
4062 function pstPipeTrickCallback( $m )
4064 if( $m[1] ) { # [[|<blah>]]
4066 $link = $this->getPipeTrickLink( $text );
4067 } else { # [[<blah>|]]
4069 $text = $this->getPipeTrickText( $link );
4072 return $link === $text ?
"[[$link]]" : "[[$link|$text]]";
4076 * Fetch the user's signature text, if any, and normalize to
4077 * validated, ready-to-insert wikitext.
4078 * If you have pre-fetched the nickname or the fancySig option, you can
4079 * specify them here to save a database query.
4084 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4085 global $wgMaxSigChars;
4087 $username = $user->getName();
4089 // If not given, retrieve from the user object.
4090 if ( $nickname === false )
4091 $nickname = $user->getOption( 'nickname' );
4093 if ( is_null( $fancySig ) )
4094 $fancySig = $user->getBoolOption( 'fancysig' );
4096 $nickname = $nickname == null ?
$username : $nickname;
4098 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4099 $nickname = $username;
4100 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4101 } elseif( $fancySig !== false ) {
4102 # Sig. might contain markup; validate this
4103 if( $this->validateSig( $nickname ) !== false ) {
4104 # Validated; clean up (if needed) and return it
4105 return $this->cleanSig( $nickname, true );
4107 # Failed to validate; fall back to the default
4108 $nickname = $username;
4109 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4113 // Make sure nickname doesnt get a sig in a sig
4114 $nickname = $this->cleanSigInSig( $nickname );
4116 # If we're still here, make it a link to the user page
4117 $userText = wfEscapeWikiText( $username );
4118 $nickText = wfEscapeWikiText( $nickname );
4119 if ( $user->isAnon() ) {
4120 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4122 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4127 * Check that the user's signature contains no bad XML
4129 * @param string $text
4130 * @return mixed An expanded string, or false if invalid.
4132 function validateSig( $text ) {
4133 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4137 * Clean up signature text
4139 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4140 * 2) Substitute all transclusions
4142 * @param string $text
4143 * @param $parsing Whether we're cleaning (preferences save) or parsing
4144 * @return string Signature text
4146 function cleanSig( $text, $parsing = false ) {
4149 $this->clearState();
4150 $this->setTitle( $wgTitle );
4151 $this->mOptions
= new ParserOptions
;
4152 $this->setOutputType
= self
::OT_PREPROCESS
;
4155 # Option to disable this feature
4156 if ( !$this->mOptions
->getCleanSignatures() ) {
4160 # FIXME: regex doesn't respect extension tags or nowiki
4161 # => Move this logic to braceSubstitution()
4162 $substWord = MagicWord
::get( 'subst' );
4163 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4164 $substText = '{{' . $substWord->getSynonym( 0 );
4166 $text = preg_replace( $substRegex, $substText, $text );
4167 $text = $this->cleanSigInSig( $text );
4168 $dom = $this->preprocessToDom( $text );
4169 $frame = $this->getPreprocessor()->newFrame();
4170 $text = $frame->expand( $dom );
4173 $text = $this->mStripState
->unstripBoth( $text );
4180 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4181 * @param string $text
4182 * @return string Signature text with /~{3,5}/ removed
4184 function cleanSigInSig( $text ) {
4185 $text = preg_replace( '/~{3,5}/', '', $text );
4190 * Set up some variables which are usually set up in parse()
4191 * so that an external function can call some class members with confidence
4194 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
4195 $this->setTitle( $title );
4196 $this->mOptions
= $options;
4197 $this->setOutputType( $outputType );
4198 if ( $clearState ) {
4199 $this->clearState();
4204 * Wrapper for preprocess()
4206 * @param string $text the text to preprocess
4207 * @param ParserOptions $options options
4211 function transformMsg( $text, $options ) {
4213 static $executing = false;
4215 # Guard against infinite recursion
4221 wfProfileIn(__METHOD__
);
4222 $text = $this->preprocess( $text, $wgTitle, $options );
4225 wfProfileOut(__METHOD__
);
4230 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4231 * The callback should have the following form:
4232 * function myParserHook( $text, $params, &$parser ) { ... }
4234 * Transform and return $text. Use $parser for any required context, e.g. use
4235 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4239 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
4240 * @param mixed $callback The callback function (and object) to use for the tag
4242 * @return The old value of the mTagHooks array associated with the hook
4244 function setHook( $tag, $callback ) {
4245 $tag = strtolower( $tag );
4246 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4247 $this->mTagHooks
[$tag] = $callback;
4248 if( !in_array( $tag, $this->mStripList
) ) {
4249 $this->mStripList
[] = $tag;
4255 /* An old work-around for bug 2257 - deprecated 2010-02-13 */
4256 function setTransparentTagHook( $tag, $callback ) {
4257 wfDeprecated( __METHOD__
);
4258 $tag = strtolower( $tag );
4259 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4260 $this->mTransparentTagHooks
[$tag] = $callback;
4266 * Remove all tag hooks
4268 function clearTagHooks() {
4269 $this->mTagHooks
= array();
4270 $this->mStripList
= $this->mDefaultStripList
;
4274 * Create a function, e.g. {{sum:1|2|3}}
4275 * The callback function should have the form:
4276 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4278 * Or with SFH_OBJECT_ARGS:
4279 * function myParserFunction( $parser, $frame, $args ) { ... }
4281 * The callback may either return the text result of the function, or an array with the text
4282 * in element 0, and a number of flags in the other elements. The names of the flags are
4283 * specified in the keys. Valid flags are:
4284 * found The text returned is valid, stop processing the template. This
4286 * nowiki Wiki markup in the return value should be escaped
4287 * isHTML The returned text is HTML, armour it against wikitext transformation
4291 * @param string $id The magic word ID
4292 * @param mixed $callback The callback function (and object) to use
4293 * @param integer $flags a combination of the following flags:
4294 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4296 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4297 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4298 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4299 * the arguments, and to control the way they are expanded.
4301 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4302 * arguments, for instance:
4303 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4305 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4306 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4307 * working if/when this is changed.
4309 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4312 * Please read the documentation in includes/parser/Preprocessor.php for more information
4313 * about the methods available in PPFrame and PPNode.
4315 * @return The old callback function for this name, if any
4317 function setFunctionHook( $id, $callback, $flags = 0 ) {
4320 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4321 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4323 # Add to function cache
4324 $mw = MagicWord
::get( $id );
4326 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4328 $synonyms = $mw->getSynonyms();
4329 $sensitive = intval( $mw->isCaseSensitive() );
4331 foreach ( $synonyms as $syn ) {
4333 if ( !$sensitive ) {
4334 $syn = $wgContLang->lc( $syn );
4337 if ( !( $flags & SFH_NO_HASH
) ) {
4340 # Remove trailing colon
4341 if ( substr( $syn, -1, 1 ) === ':' ) {
4342 $syn = substr( $syn, 0, -1 );
4344 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4350 * Get all registered function hook identifiers
4354 function getFunctionHooks() {
4355 return array_keys( $this->mFunctionHooks
);
4359 * Create a tag function, e.g. <test>some stuff</test>.
4360 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4361 * Unlike parser functions, their content is not preprocessed.
4363 function setFunctionTagHook( $tag, $callback, $flags ) {
4364 $tag = strtolower( $tag );
4365 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4366 $this->mFunctionTagHooks
[$tag] : null;
4367 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4369 if( !in_array( $tag, $this->mStripList
) ) {
4370 $this->mStripList
[] = $tag;
4377 * FIXME: update documentation. makeLinkObj() is deprecated.
4378 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4379 * Placeholders created in Skin::makeLinkObj()
4380 * Returns an array of link CSS classes, indexed by PDBK.
4382 function replaceLinkHolders( &$text, $options = 0 ) {
4383 return $this->mLinkHolders
->replace( $text );
4387 * Replace <!--LINK--> link placeholders with plain text of links
4388 * (not HTML-formatted).
4389 * @param string $text
4392 function replaceLinkHoldersText( $text ) {
4393 return $this->mLinkHolders
->replaceText( $text );
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];