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 $this->mOutput
->setTitleText( $wgContLang->convert( $title->getPrefixedText() ) );
373 $text = $this->mStripState
->unstripNoWiki( $text );
375 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
377 if ( $this->mTransparentTagHooks
) {
378 //!JF Move to its own function
379 $uniq_prefix = $this->mUniqPrefix
;
381 $elements = array_keys( $this->mTransparentTagHooks
);
382 $text = self
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
384 foreach( $matches as $marker => $data ) {
385 list( $element, $content, $params, $tag ) = $data;
386 $tagName = strtolower( $element );
387 if( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
388 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName],
389 array( $content, $params, $this ) );
393 $this->mStripState
->general
->setPair( $marker, $output );
395 $text = $this->mStripState
->unstripGeneral( $text );
398 $text = Sanitizer
::normalizeCharReferences( $text );
400 if ( ( $wgUseTidy && $this->mOptions
->mTidy
) ||
$wgAlwaysUseTidy ) {
401 $text = MWTidy
::tidy( $text );
403 # attempt to sanitize at least some nesting problems
404 # (bug #2702 and quite a few others)
406 # ''Something [http://www.cool.com cool''] -->
407 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
408 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
409 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
410 # fix up an anchor inside another anchor, only
411 # at least for a single single nested link (bug 3695)
412 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
413 '\\1\\2</a>\\3</a>\\1\\4</a>',
414 # fix div inside inline elements- doBlockLevels won't wrap a line which
415 # contains a div, so fix it up here; replace
416 # div with escaped text
417 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
418 '\\1\\3<div\\5>\\6</div>\\8\\9',
419 # remove empty italic or bold tag pairs, some
420 # introduced by rules above
421 '/<([bi])><\/\\1>/' => '',
424 $text = preg_replace(
425 array_keys( $tidyregs ),
426 array_values( $tidyregs ),
429 global $wgExpensiveParserFunctionLimit;
430 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
431 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
434 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
436 # Information on include size limits, for the benefit of users who try to skirt them
437 if ( $this->mOptions
->getEnableLimitReport() ) {
438 global $wgExpensiveParserFunctionLimit;
439 $max = $this->mOptions
->getMaxIncludeSize();
440 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
442 "NewPP limit report\n" .
443 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
444 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
445 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
447 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
448 $text .= "\n<!-- \n$limitReport-->\n";
450 $this->mOutput
->setText( $text );
452 $this->mRevisionId
= $oldRevisionId;
453 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
454 wfProfileOut( $fname );
455 wfProfileOut( __METHOD__
);
457 return $this->mOutput
;
461 * Recursive parser entry point that can be called from an extension tag
464 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
466 * @param $text String: text extension wants to have parsed
467 * @param PPFrame $frame: The frame to use for expanding any template variables
469 function recursiveTagParse( $text, $frame=false ) {
470 wfProfileIn( __METHOD__
);
471 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
472 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
473 $text = $this->internalParse( $text, false, $frame );
474 wfProfileOut( __METHOD__
);
479 * Expand templates and variables in the text, producing valid, static wikitext.
480 * Also removes comments.
482 function preprocess( $text, $title, $options, $revid = null ) {
483 wfProfileIn( __METHOD__
);
485 $this->setOutputType( self
::OT_PREPROCESS
);
486 $this->mOptions
= $options;
487 $this->setTitle( $title );
488 if( $revid !== null ) {
489 $this->mRevisionId
= $revid;
491 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
492 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
493 $text = $this->replaceVariables( $text );
494 $text = $this->mStripState
->unstripBoth( $text );
495 wfProfileOut( __METHOD__
);
500 * Get the wikitext of a page as though it was transcluded.
502 * Specifically <includeonly> etc. are parsed, redirects are followed, comments
503 * are removed, but templates arguments and parser functions are untouched.
505 * This is not called by the parser itself, see braceSubstitution for its transclusion.
507 public function getTransclusionText( $title, $options ) {
508 // Must initialize first
510 $this->setOutputType( self
::OT_INCLUDES
);
511 $this->mOptions
= $options;
512 $this->setTitle( new FakeTitle
);
514 list( $text, $title ) = $this->getTemplateDom( $title );
515 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
516 return $this->getPreprocessor()->newFrame()->expand( $text, $flags );
520 * Get a random string
525 function getRandomString() {
526 return dechex(mt_rand(0, 0x7fffffff)) . dechex(mt_rand(0, 0x7fffffff));
529 function &getTitle() { return $this->mTitle
; }
530 function getOptions() { return $this->mOptions
; }
531 function getRevisionId() { return $this->mRevisionId
; }
532 function getOutput() { return $this->mOutput
; }
533 function nextLinkID() { return $this->mLinkID++
; }
535 function getFunctionLang() {
536 global $wgLang, $wgContLang;
538 $target = $this->mOptions
->getTargetLanguage();
539 if ( $target !== null ) {
542 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
547 * Get a preprocessor object
549 function getPreprocessor() {
550 if ( !isset( $this->mPreprocessor
) ) {
551 $class = $this->mPreprocessorClass
;
552 $this->mPreprocessor
= new $class( $this );
554 return $this->mPreprocessor
;
558 * Replaces all occurrences of HTML-style comments and the given tags
559 * in the text with a random marker and returns the next text. The output
560 * parameter $matches will be an associative array filled with data in
562 * 'UNIQ-xxxxx' => array(
565 * array( 'param' => 'x' ),
566 * '<element param="x">tag content</element>' ) )
568 * @param $elements list of element names. Comments are always extracted.
569 * @param $text Source text string.
570 * @param $uniq_prefix
575 function extractTagsAndParams($elements, $text, &$matches, $uniq_prefix = ''){
580 $taglist = implode( '|', $elements );
581 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
583 while ( $text != '' ) {
584 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
586 if( count( $p ) < 5 ) {
589 if( count( $p ) > 5 ) {
603 $marker = "$uniq_prefix-$element-" . sprintf('%08X', $n++
) . self
::MARKER_SUFFIX
;
604 $stripped .= $marker;
606 if ( $close === '/>' ) {
607 // Empty element tag, <tag />
612 if( $element === '!--' ) {
615 $end = "/(<\\/$element\\s*>)/i";
617 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
619 if( count( $q ) < 3 ) {
620 # No end tag -- let it run out to the end of the text.
629 $matches[$marker] = array( $element,
631 Sanitizer
::decodeTagAttributes( $attributes ),
632 "<$element$attributes$close$content$tail" );
638 * Get a list of strippable XML-like elements
640 function getStripList() {
641 return $this->mStripList
;
645 * @deprecated use replaceVariables
647 function strip( $text, $state, $stripcomments = false , $dontstrip = array () ) {
652 * Restores pre, math, and other extensions removed by strip()
654 * always call unstripNoWiki() after this one
656 * @deprecated use $this->mStripState->unstrip()
658 function unstrip( $text, $state ) {
659 return $state->unstripGeneral( $text );
663 * Always call this after unstrip() to preserve the order
666 * @deprecated use $this->mStripState->unstrip()
668 function unstripNoWiki( $text, $state ) {
669 return $state->unstripNoWiki( $text );
673 * @deprecated use $this->mStripState->unstripBoth()
675 function unstripForHTML( $text ) {
676 return $this->mStripState
->unstripBoth( $text );
680 * Add an item to the strip state
681 * Returns the unique tag which must be inserted into the stripped text
682 * The tag will be replaced with the original text in unstrip()
686 function insertStripItem( $text ) {
687 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
688 $this->mMarkerIndex++
;
689 $this->mStripState
->general
->setPair( $rnd, $text );
694 * Interface with html tidy
695 * @deprecated Use MWTidy::tidy()
697 public static function tidy( $text ) {
698 wfDeprecated( __METHOD__
);
699 return MWTidy
::tidy( $text );
703 * parse the wiki syntax used to render tables
707 function doTableStuff ( $text ) {
708 wfProfileIn( __METHOD__
);
710 $lines = StringUtils
::explode( "\n", $text );
712 $td_history = array (); // Is currently a td tag open?
713 $last_tag_history = array (); // Save history of last lag activated (td, th or caption)
714 $tr_history = array (); // Is currently a tr tag open?
715 $tr_attributes = array (); // history of tr attributes
716 $has_opened_tr = array(); // Did this table open a <tr> element?
717 $indent_level = 0; // indent level of the table
719 foreach ( $lines as $outLine ) {
720 $line = trim( $outLine );
722 if( $line == '' ) { // empty line, go to next line
723 $out .= $outLine."\n";
726 $first_character = $line[0];
729 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
730 // First check if we are starting a new table
731 $indent_level = strlen( $matches[1] );
733 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
734 $attributes = Sanitizer
::fixTagAttributes ( $attributes , 'table' );
736 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
737 array_push( $td_history , false );
738 array_push( $last_tag_history , '' );
739 array_push( $tr_history , false );
740 array_push( $tr_attributes , '' );
741 array_push( $has_opened_tr , false );
742 } else if ( count ( $td_history ) == 0 ) {
743 // Don't do any of the following
744 $out .= $outLine."\n";
746 } else if ( substr ( $line , 0 , 2 ) === '|}' ) {
747 // We are ending a table
748 $line = '</table>' . substr ( $line , 2 );
749 $last_tag = array_pop ( $last_tag_history );
751 if ( !array_pop ( $has_opened_tr ) ) {
752 $line = "<tr><td></td></tr>{$line}";
755 if ( array_pop ( $tr_history ) ) {
756 $line = "</tr>{$line}";
759 if ( array_pop ( $td_history ) ) {
760 $line = "</{$last_tag}>{$line}";
762 array_pop ( $tr_attributes );
763 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
764 } else if ( substr ( $line , 0 , 2 ) === '|-' ) {
765 // Now we have a table row
766 $line = preg_replace( '#^\|-+#', '', $line );
768 // Whats after the tag is now only attributes
769 $attributes = $this->mStripState
->unstripBoth( $line );
770 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
771 array_pop( $tr_attributes );
772 array_push( $tr_attributes, $attributes );
775 $last_tag = array_pop ( $last_tag_history );
776 array_pop ( $has_opened_tr );
777 array_push ( $has_opened_tr , true );
779 if ( array_pop ( $tr_history ) ) {
783 if ( array_pop ( $td_history ) ) {
784 $line = "</{$last_tag}>{$line}";
788 array_push ( $tr_history , false );
789 array_push ( $td_history , false );
790 array_push ( $last_tag_history , '' );
792 else if ( $first_character === '|' ||
$first_character === '!' ||
substr ( $line , 0 , 2 ) === '|+' ) {
793 // This might be cell elements, td, th or captions
794 if ( substr ( $line , 0 , 2 ) === '|+' ) {
795 $first_character = '+';
796 $line = substr ( $line , 1 );
799 $line = substr ( $line , 1 );
801 if ( $first_character === '!' ) {
802 $line = str_replace ( '!!' , '||' , $line );
805 // Split up multiple cells on the same line.
806 // FIXME : This can result in improper nesting of tags processed
807 // by earlier parser steps, but should avoid splitting up eg
808 // attribute values containing literal "||".
809 $cells = StringUtils
::explodeMarkup( '||' , $line );
813 // Loop through each table cell
814 foreach ( $cells as $cell )
817 if ( $first_character !== '+' )
819 $tr_after = array_pop ( $tr_attributes );
820 if ( !array_pop ( $tr_history ) ) {
821 $previous = "<tr{$tr_after}>\n";
823 array_push ( $tr_history , true );
824 array_push ( $tr_attributes , '' );
825 array_pop ( $has_opened_tr );
826 array_push ( $has_opened_tr , true );
829 $last_tag = array_pop ( $last_tag_history );
831 if ( array_pop ( $td_history ) ) {
832 $previous = "</{$last_tag}>{$previous}";
835 if ( $first_character === '|' ) {
837 } else if ( $first_character === '!' ) {
839 } else if ( $first_character === '+' ) {
840 $last_tag = 'caption';
845 array_push ( $last_tag_history , $last_tag );
847 // A cell could contain both parameters and data
848 $cell_data = explode ( '|' , $cell , 2 );
850 // Bug 553: Note that a '|' inside an invalid link should not
851 // be mistaken as delimiting cell parameters
852 if ( strpos( $cell_data[0], '[[' ) !== false ) {
853 $cell = "{$previous}<{$last_tag}>{$cell}";
854 } else if ( count ( $cell_data ) == 1 )
855 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
857 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
858 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
859 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
863 array_push ( $td_history , true );
866 $out .= $outLine . "\n";
869 // Closing open td, tr && table
870 while ( count ( $td_history ) > 0 )
872 if ( array_pop ( $td_history ) ) {
875 if ( array_pop ( $tr_history ) ) {
878 if ( !array_pop ( $has_opened_tr ) ) {
879 $out .= "<tr><td></td></tr>\n" ;
882 $out .= "</table>\n";
885 // Remove trailing line-ending (b/c)
886 if ( substr( $out, -1 ) === "\n" ) {
887 $out = substr( $out, 0, -1 );
890 // special case: don't return empty table
891 if( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
895 wfProfileOut( __METHOD__
);
901 * Helper function for parse() that transforms wiki markup into
902 * HTML. Only called for $mOutputType == self::OT_HTML.
906 function internalParse( $text, $isMain = true, $frame=false ) {
907 wfProfileIn( __METHOD__
);
911 # Hook to suspend the parser in this state
912 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
913 wfProfileOut( __METHOD__
);
917 // if $frame is provided, then use $frame for replacing any variables
919 // use frame depth to infer how include/noinclude tags should be handled
920 // depth=0 means this is the top-level document; otherwise it's an included document
924 $flag = Parser
::PTD_FOR_INCLUSION
;
925 $dom = $this->preprocessToDom( $text, $flag );
926 $text = $frame->expand( $dom );
928 // if $frame is not provided, then use old-style replaceVariables
930 $text = $this->replaceVariables( $text );
933 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
934 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
936 // Tables need to come after variable replacement for things to work
937 // properly; putting them before other transformations should keep
938 // exciting things like link expansions from showing up in surprising
940 $text = $this->doTableStuff( $text );
942 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
944 $text = $this->doDoubleUnderscore( $text );
946 $text = $this->doHeadings( $text );
947 if( $this->mOptions
->getUseDynamicDates() ) {
948 $df = DateFormatter
::getInstance();
949 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
951 $text = $this->doAllQuotes( $text );
952 $text = $this->replaceInternalLinks( $text );
953 $text = $this->replaceExternalLinks( $text );
955 # replaceInternalLinks may sometimes leave behind
956 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
957 $text = str_replace($this->mUniqPrefix
.'NOPARSE', '', $text);
959 $text = $this->doMagicLinks( $text );
960 $text = $this->formatHeadings( $text, $origText, $isMain );
962 wfProfileOut( __METHOD__
);
967 * Replace special strings like "ISBN xxx" and "RFC xxx" with
968 * magic external links.
973 function doMagicLinks( $text ) {
974 wfProfileIn( __METHOD__
);
975 $prots = $this->mUrlProtocols
;
976 $urlChar = self
::EXT_LINK_URL_CLASS
;
977 $text = preg_replace_callback(
979 (<a.*?</a>) | # m[1]: Skip link text
980 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
981 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
982 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
983 ISBN\s+(\b # m[5]: ISBN, capture number
984 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
985 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
986 [0-9Xx] # check digit
988 )!x', array( &$this, 'magicLinkCallback' ), $text );
989 wfProfileOut( __METHOD__
);
993 function magicLinkCallback( $m ) {
994 if ( isset( $m[1] ) && $m[1] !== '' ) {
997 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1000 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1001 # Free external link
1002 return $this->makeFreeExternalLink( $m[0] );
1003 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1006 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1009 $CssClass = 'mw-magiclink-rfc';
1011 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1013 $urlmsg = 'pubmedurl';
1014 $CssClass = 'mw-magiclink-pmid';
1017 throw new MWException( __METHOD__
.': unrecognised match type "' .
1018 substr($m[0], 0, 20 ) . '"' );
1020 $url = wfMsg( $urlmsg, $id);
1021 $sk = $this->mOptions
->getSkin();
1022 $la = $sk->getExternalLinkAttributes( "external $CssClass" );
1023 return "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1024 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1027 $num = strtr( $isbn, array(
1032 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1034 $titleObj->escapeLocalUrl() .
1035 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1042 * Make a free external link, given a user-supplied URL
1046 function makeFreeExternalLink( $url ) {
1048 wfProfileIn( __METHOD__
);
1050 $sk = $this->mOptions
->getSkin();
1053 # The characters '<' and '>' (which were escaped by
1054 # removeHTMLtags()) should not be included in
1055 # URLs, per RFC 2396.
1057 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1058 $trail = substr($url, $m2[0][1]) . $trail;
1059 $url = substr($url, 0, $m2[0][1]);
1062 # Move trailing punctuation to $trail
1064 # If there is no left bracket, then consider right brackets fair game too
1065 if ( strpos( $url, '(' ) === false ) {
1069 $numSepChars = strspn( strrev( $url ), $sep );
1070 if ( $numSepChars ) {
1071 $trail = substr( $url, -$numSepChars ) . $trail;
1072 $url = substr( $url, 0, -$numSepChars );
1075 $url = Sanitizer
::cleanUrl( $url );
1077 # Is this an external image?
1078 $text = $this->maybeMakeExternalImage( $url );
1079 if ( $text === false ) {
1080 # Not an image, make a link
1081 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1082 $this->getExternalLinkAttribs( $url ) );
1083 # Register it in the output object...
1084 # Replace unnecessary URL escape codes with their equivalent characters
1085 $pasteurized = self
::replaceUnusualEscapes( $url );
1086 $this->mOutput
->addExternalLink( $pasteurized );
1088 wfProfileOut( __METHOD__
);
1089 return $text . $trail;
1094 * Parse headers and return html
1098 function doHeadings( $text ) {
1099 wfProfileIn( __METHOD__
);
1100 for ( $i = 6; $i >= 1; --$i ) {
1101 $h = str_repeat( '=', $i );
1102 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1103 "<h$i>\\1</h$i>", $text );
1105 wfProfileOut( __METHOD__
);
1110 * Replace single quotes with HTML markup
1112 * @return string the altered text
1114 function doAllQuotes( $text ) {
1115 wfProfileIn( __METHOD__
);
1117 $lines = StringUtils
::explode( "\n", $text );
1118 foreach ( $lines as $line ) {
1119 $outtext .= $this->doQuotes( $line ) . "\n";
1121 $outtext = substr($outtext, 0,-1);
1122 wfProfileOut( __METHOD__
);
1127 * Helper function for doAllQuotes()
1129 public function doQuotes( $text ) {
1130 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1131 if ( count( $arr ) == 1 )
1135 # First, do some preliminary work. This may shift some apostrophes from
1136 # being mark-up to being text. It also counts the number of occurrences
1137 # of bold and italics mark-ups.
1141 foreach ( $arr as $r )
1143 if ( ( $i %
2 ) == 1 )
1145 # If there are ever four apostrophes, assume the first is supposed to
1146 # be text, and the remaining three constitute mark-up for bold text.
1147 if ( strlen( $arr[$i] ) == 4 )
1152 # If there are more than 5 apostrophes in a row, assume they're all
1153 # text except for the last 5.
1154 else if ( strlen( $arr[$i] ) > 5 )
1156 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1159 # Count the number of occurrences of bold and italics mark-ups.
1160 # We are not counting sequences of five apostrophes.
1161 if ( strlen( $arr[$i] ) == 2 ) { $numitalics++
; }
1162 else if ( strlen( $arr[$i] ) == 3 ) { $numbold++
; }
1163 else if ( strlen( $arr[$i] ) == 5 ) { $numitalics++
; $numbold++
; }
1168 # If there is an odd number of both bold and italics, it is likely
1169 # that one of the bold ones was meant to be an apostrophe followed
1170 # by italics. Which one we cannot know for certain, but it is more
1171 # likely to be one that has a single-letter word before it.
1172 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) )
1175 $firstsingleletterword = -1;
1176 $firstmultiletterword = -1;
1178 foreach ( $arr as $r )
1180 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) )
1182 $x1 = substr ($arr[$i-1], -1);
1183 $x2 = substr ($arr[$i-1], -2, 1);
1185 if ($firstspace == -1) $firstspace = $i;
1186 } else if ($x2 === ' ') {
1187 if ($firstsingleletterword == -1) $firstsingleletterword = $i;
1189 if ($firstmultiletterword == -1) $firstmultiletterword = $i;
1195 # If there is a single-letter word, use it!
1196 if ($firstsingleletterword > -1)
1198 $arr [ $firstsingleletterword ] = "''";
1199 $arr [ $firstsingleletterword-1 ] .= "'";
1201 # If not, but there's a multi-letter word, use that one.
1202 else if ($firstmultiletterword > -1)
1204 $arr [ $firstmultiletterword ] = "''";
1205 $arr [ $firstmultiletterword-1 ] .= "'";
1207 # ... otherwise use the first one that has neither.
1208 # (notice that it is possible for all three to be -1 if, for example,
1209 # there is only one pentuple-apostrophe in the line)
1210 else if ($firstspace > -1)
1212 $arr [ $firstspace ] = "''";
1213 $arr [ $firstspace-1 ] .= "'";
1217 # Now let's actually convert our apostrophic mush to HTML!
1222 foreach ($arr as $r)
1226 if ($state === 'both')
1233 if (strlen ($r) == 2)
1236 { $output .= '</i>'; $state = ''; }
1237 else if ($state === 'bi')
1238 { $output .= '</i>'; $state = 'b'; }
1239 else if ($state === 'ib')
1240 { $output .= '</b></i><b>'; $state = 'b'; }
1241 else if ($state === 'both')
1242 { $output .= '<b><i>'.$buffer.'</i>'; $state = 'b'; }
1243 else # $state can be 'b' or ''
1244 { $output .= '<i>'; $state .= 'i'; }
1246 else if (strlen ($r) == 3)
1249 { $output .= '</b>'; $state = ''; }
1250 else if ($state === 'bi')
1251 { $output .= '</i></b><i>'; $state = 'i'; }
1252 else if ($state === 'ib')
1253 { $output .= '</b>'; $state = 'i'; }
1254 else if ($state === 'both')
1255 { $output .= '<i><b>'.$buffer.'</b>'; $state = 'i'; }
1256 else # $state can be 'i' or ''
1257 { $output .= '<b>'; $state .= 'b'; }
1259 else if (strlen ($r) == 5)
1262 { $output .= '</b><i>'; $state = 'i'; }
1263 else if ($state === 'i')
1264 { $output .= '</i><b>'; $state = 'b'; }
1265 else if ($state === 'bi')
1266 { $output .= '</i></b>'; $state = ''; }
1267 else if ($state === 'ib')
1268 { $output .= '</b></i>'; $state = ''; }
1269 else if ($state === 'both')
1270 { $output .= '<i><b>'.$buffer.'</b></i>'; $state = ''; }
1271 else # ($state == '')
1272 { $buffer = ''; $state = 'both'; }
1277 # Now close all remaining tags. Notice that the order is important.
1278 if ($state === 'b' ||
$state === 'ib')
1280 if ($state === 'i' ||
$state === 'bi' ||
$state === 'ib')
1282 if ($state === 'bi')
1284 # There might be lonely ''''', so make sure we have a buffer
1285 if ($state === 'both' && $buffer)
1286 $output .= '<b><i>'.$buffer.'</i></b>';
1292 * Replace external links (REL)
1294 * Note: this is all very hackish and the order of execution matters a lot.
1295 * Make sure to run maintenance/parserTests.php if you change this code.
1299 function replaceExternalLinks( $text ) {
1301 wfProfileIn( __METHOD__
);
1303 $sk = $this->mOptions
->getSkin();
1305 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1306 $s = array_shift( $bits );
1309 while ( $i<count( $bits ) ) {
1311 $protocol = $bits[$i++
];
1312 $text = $bits[$i++
];
1313 $trail = $bits[$i++
];
1315 # The characters '<' and '>' (which were escaped by
1316 # removeHTMLtags()) should not be included in
1317 # URLs, per RFC 2396.
1319 if (preg_match('/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
)) {
1320 $text = substr($url, $m2[0][1]) . ' ' . $text;
1321 $url = substr($url, 0, $m2[0][1]);
1324 # If the link text is an image URL, replace it with an <img> tag
1325 # This happened by accident in the original parser, but some people used it extensively
1326 $img = $this->maybeMakeExternalImage( $text );
1327 if ( $img !== false ) {
1333 # Set linktype for CSS - if URL==text, link is essentially free
1334 $linktype = ($text === $url) ?
'free' : 'text';
1336 # No link text, e.g. [http://domain.tld/some.link]
1337 if ( $text == '' ) {
1338 # Autonumber if allowed. See bug #5918
1339 if ( strpos( wfUrlProtocols(), substr($protocol, 0, strpos($protocol, ':')) ) !== false ) {
1340 $langObj = $this->getFunctionLang();
1341 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1342 $linktype = 'autonumber';
1344 # Otherwise just use the URL
1345 $text = htmlspecialchars( $url );
1349 # Have link text, e.g. [http://domain.tld/some.link text]s
1351 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1354 $text = $wgContLang->markNoConversion($text);
1356 $url = Sanitizer
::cleanUrl( $url );
1358 # Use the encoded URL
1359 # This means that users can paste URLs directly into the text
1360 # Funny characters like ö aren't valid in URLs anyway
1361 # This was changed in August 2004
1362 $s .= $sk->makeExternalLink( $url, $text, false, $linktype,
1363 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1365 # Register link in the output object.
1366 # Replace unnecessary URL escape codes with the referenced character
1367 # This prevents spammers from hiding links from the filters
1368 $pasteurized = self
::replaceUnusualEscapes( $url );
1369 $this->mOutput
->addExternalLink( $pasteurized );
1372 wfProfileOut( __METHOD__
);
1377 * Get an associative array of additional HTML attributes appropriate for a
1378 * particular external link. This currently may include rel => nofollow
1379 * (depending on configuration, namespace, and the URL's domain) and/or a
1380 * target attribute (depending on configuration).
1382 * @param string $url Optional URL, to extract the domain from for rel =>
1383 * nofollow if appropriate
1384 * @return array Associative array of HTML attributes
1386 function getExternalLinkAttribs( $url = false ) {
1388 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1389 $ns = $this->mTitle
->getNamespace();
1390 if( $wgNoFollowLinks && !in_array($ns, $wgNoFollowNsExceptions) ) {
1391 $attribs['rel'] = 'nofollow';
1393 global $wgNoFollowDomainExceptions;
1394 if ( $wgNoFollowDomainExceptions ) {
1395 $bits = wfParseUrl( $url );
1396 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1397 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1398 if( substr( $bits['host'], -strlen( $domain ) )
1400 unset( $attribs['rel'] );
1407 if ( $this->mOptions
->getExternalLinkTarget() ) {
1408 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1415 * Replace unusual URL escape codes with their equivalent characters
1419 * @todo This can merge genuinely required bits in the path or query string,
1420 * breaking legit URLs. A proper fix would treat the various parts of
1421 * the URL differently; as a workaround, just use the output for
1422 * statistical records, not for actual linking/output.
1424 static function replaceUnusualEscapes( $url ) {
1425 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1426 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1430 * Callback function used in replaceUnusualEscapes().
1431 * Replaces unusual URL escape codes with their equivalent character
1435 private static function replaceUnusualEscapesCallback( $matches ) {
1436 $char = urldecode( $matches[0] );
1437 $ord = ord( $char );
1438 // Is it an unsafe or HTTP reserved character according to RFC 1738?
1439 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1440 // No, shouldn't be escaped
1443 // Yes, leave it escaped
1449 * make an image if it's allowed, either through the global
1450 * option, through the exception, or through the on-wiki whitelist
1453 function maybeMakeExternalImage( $url ) {
1454 $sk = $this->mOptions
->getSkin();
1455 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1456 $imagesexception = !empty($imagesfrom);
1458 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1459 if( $imagesexception && is_array( $imagesfrom ) ) {
1460 $imagematch = false;
1461 foreach( $imagesfrom as $match ) {
1462 if( strpos( $url, $match ) === 0 ) {
1467 } elseif( $imagesexception ) {
1468 $imagematch = (strpos( $url, $imagesfrom ) === 0);
1470 $imagematch = false;
1472 if ( $this->mOptions
->getAllowExternalImages()
1473 ||
( $imagesexception && $imagematch ) ) {
1474 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1476 $text = $sk->makeExternalImage( $url );
1479 if( !$text && $this->mOptions
->getEnableImageWhitelist()
1480 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1481 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1482 foreach( $whitelist as $entry ) {
1483 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1484 if( strpos( $entry, '#' ) === 0 ||
$entry === '' )
1486 if( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1487 # Image matches a whitelist entry
1488 $text = $sk->makeExternalImage( $url );
1497 * Process [[ ]] wikilinks
1498 * @return processed text
1502 function replaceInternalLinks( $s ) {
1503 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1508 * Process [[ ]] wikilinks (RIL)
1509 * @return LinkHolderArray
1513 function replaceInternalLinks2( &$s ) {
1516 wfProfileIn( __METHOD__
);
1518 wfProfileIn( __METHOD__
.'-setup' );
1519 static $tc = FALSE, $e1, $e1_img;
1520 # the % is needed to support urlencoded titles as well
1522 $tc = Title
::legalChars() . '#%';
1523 # Match a link having the form [[namespace:link|alternate]]trail
1524 $e1 = "/^([{$tc}]*)(\\|.*?)?]](.*)\$/sD";
1525 # Match cases where there is no "]]", which might still be images
1526 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1529 $sk = $this->mOptions
->getSkin();
1530 $holders = new LinkHolderArray( $this );
1532 #split the entire text string on occurences of [[
1533 $a = StringUtils
::explode( '[[', ' ' . $s );
1534 #get the first element (all text up to first [[), and remove the space we added
1537 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1538 $s = substr( $s, 1 );
1540 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1542 if ( $useLinkPrefixExtension ) {
1543 # Match the end of a line for a word that's not followed by whitespace,
1544 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1545 $e2 = wfMsgForContent( 'linkprefix' );
1548 if( is_null( $this->mTitle
) ) {
1549 wfProfileOut( __METHOD__
.'-setup' );
1550 wfProfileOut( __METHOD__
);
1551 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1553 $nottalk = !$this->mTitle
->isTalkPage();
1555 if ( $useLinkPrefixExtension ) {
1557 if ( preg_match( $e2, $s, $m ) ) {
1558 $first_prefix = $m[2];
1560 $first_prefix = false;
1566 if($wgContLang->hasVariants()) {
1567 $selflink = $wgContLang->convertLinkToAllVariants($this->mTitle
->getPrefixedText());
1569 $selflink = array($this->mTitle
->getPrefixedText());
1571 $useSubpages = $this->areSubpagesAllowed();
1572 wfProfileOut( __METHOD__
.'-setup' );
1574 # Loop for each link
1575 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1576 # Check for excessive memory usage
1577 if ( $holders->isBig() ) {
1579 # Do the existence check, replace the link holders and clear the array
1580 $holders->replace( $s );
1584 if ( $useLinkPrefixExtension ) {
1585 wfProfileIn( __METHOD__
.'-prefixhandling' );
1586 if ( preg_match( $e2, $s, $m ) ) {
1594 $prefix = $first_prefix;
1595 $first_prefix = false;
1597 wfProfileOut( __METHOD__
.'-prefixhandling' );
1600 $might_be_img = false;
1602 wfProfileIn( __METHOD__
."-e1" );
1603 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1605 if( $m[2] === '' ) {
1607 } elseif( $m[2] === '|' ) {
1608 $text = $this->getPipeTrickText( $m[1] );
1610 $text = substr( $m[2], 1 );
1613 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1614 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1615 # the real problem is with the $e1 regex
1618 # Still some problems for cases where the ] is meant to be outside punctuation,
1619 # and no image is in sight. See bug 2095.
1622 substr( $m[3], 0, 1 ) === ']' &&
1623 strpos($text, '[') !== false
1626 $text .= ']'; # so that replaceExternalLinks($text) works later
1627 $m[3] = substr( $m[3], 1 );
1630 # Handle pipe-trick for [[|<blah>]]
1631 $lnk = $m[1] === '' ?
$this->getPipeTrickLink( $text ) : $m[1];
1632 # fix up urlencoded title texts
1633 if( strpos( $lnk, '%' ) !== false ) {
1634 # Should anchors '#' also be rejected?
1635 $lnk = str_replace( array('<', '>'), array('<', '>'), urldecode($lnk) );
1639 } elseif( preg_match($e1_img, $line, $m) ) { # Invalid, but might be an image with a link in its caption
1640 $might_be_img = true;
1642 $lnk = strpos( $m[1], '%' ) === false ?
$m[1] : urldecode( $m[1] );
1644 } else { # Invalid form; output directly
1645 $s .= $prefix . '[[' . $line ;
1646 wfProfileOut( __METHOD__
."-e1" );
1649 wfProfileOut( __METHOD__
."-e1" );
1650 wfProfileIn( __METHOD__
."-misc" );
1652 # Don't allow internal links to pages containing
1653 # PROTO: where PROTO is a valid URL protocol; these
1654 # should be external links.
1655 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $lnk ) ) {
1656 $s .= $prefix . '[[' . $line ;
1657 wfProfileOut( __METHOD__
."-misc" );
1661 # Make subpage if necessary
1662 if ( $useSubpages ) {
1663 $link = $this->maybeDoSubpageLink( $lnk, $text );
1668 $noforce = (substr( $lnk, 0, 1 ) !== ':');
1670 # Strip off leading ':'
1671 $link = substr( $link, 1 );
1674 wfProfileOut( __METHOD__
."-misc" );
1675 wfProfileIn( __METHOD__
."-title" );
1676 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1677 if ( $nt === null ) {
1678 $s .= $prefix . '[[' . $line;
1679 wfProfileOut( __METHOD__
."-title" );
1683 $ns = $nt->getNamespace();
1684 $iw = $nt->getInterWiki();
1685 wfProfileOut( __METHOD__
."-title" );
1687 if ( $might_be_img ) { # if this is actually an invalid link
1688 wfProfileIn( __METHOD__
."-might_be_img" );
1689 if ( $ns == NS_FILE
&& $noforce ) { #but might be an image
1692 #look at the next 'line' to see if we can close it there
1694 $next_line = $a->current();
1695 if ( $next_line === false ||
$next_line === null ) {
1698 $m = explode( ']]', $next_line, 3 );
1699 if ( count( $m ) == 3 ) {
1700 # the first ]] closes the inner link, the second the image
1702 $text .= "[[{$m[0]}]]{$m[1]}";
1705 } elseif ( count( $m ) == 2 ) {
1706 #if there's exactly one ]] that's fine, we'll keep looking
1707 $text .= "[[{$m[0]}]]{$m[1]}";
1709 #if $next_line is invalid too, we need look no further
1710 $text .= '[[' . $next_line;
1715 # we couldn't find the end of this imageLink, so output it raw
1716 #but don't ignore what might be perfectly normal links in the text we've examined
1717 $holders->merge( $this->replaceInternalLinks2( $text ) );
1718 $s .= "{$prefix}[[$link|$text";
1719 # note: no $trail, because without an end, there *is* no trail
1720 wfProfileOut( __METHOD__
."-might_be_img" );
1723 } else { #it's not an image, so output it raw
1724 $s .= "{$prefix}[[$link|$text";
1725 # note: no $trail, because without an end, there *is* no trail
1726 wfProfileOut( __METHOD__
."-might_be_img" );
1729 wfProfileOut( __METHOD__
."-might_be_img" );
1732 $wasblank = ( $text == '' );
1733 if ( $wasblank ) $text = $link;
1735 # Link not escaped by : , create the various objects
1739 wfProfileIn( __METHOD__
."-interwiki" );
1740 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1741 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1742 $s = rtrim($s . $prefix);
1743 $s .= trim($trail, "\n") == '' ?
'': $prefix . $trail;
1744 wfProfileOut( __METHOD__
."-interwiki" );
1747 wfProfileOut( __METHOD__
."-interwiki" );
1749 if ( $ns == NS_FILE
) {
1750 wfProfileIn( __METHOD__
."-image" );
1751 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1753 # if no parameters were passed, $text
1754 # becomes something like "File:Foo.png",
1755 # which we don't want to pass on to the
1759 # recursively parse links inside the image caption
1760 # actually, this will parse them in any other parameters, too,
1761 # but it might be hard to fix that, and it doesn't matter ATM
1762 $text = $this->replaceExternalLinks($text);
1763 $holders->merge( $this->replaceInternalLinks2( $text ) );
1765 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1766 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1768 $s .= $prefix . $trail;
1770 $this->mOutput
->addImage( $nt->getDBkey() );
1771 wfProfileOut( __METHOD__
."-image" );
1776 if ( $ns == NS_CATEGORY
) {
1777 wfProfileIn( __METHOD__
."-category" );
1778 $s = rtrim($s . "\n"); # bug 87
1781 $sortkey = $this->getDefaultSort();
1785 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1786 $sortkey = str_replace( "\n", '', $sortkey );
1787 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1788 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1791 * Strip the whitespace Category links produce, see bug 87
1792 * @todo We might want to use trim($tmp, "\n") here.
1794 $s .= trim($prefix . $trail, "\n") == '' ?
'': $prefix . $trail;
1796 wfProfileOut( __METHOD__
."-category" );
1801 # Self-link checking
1802 if( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1803 if( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1804 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1809 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1810 # FIXME: Should do batch file existence checks, see comment below
1811 if( $ns == NS_MEDIA
) {
1812 wfProfileIn( __METHOD__
."-media" );
1813 # Give extensions a chance to select the file revision for us
1814 $skip = $time = false;
1815 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1817 $link = $sk->link( $nt );
1819 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1821 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1822 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1823 $this->mOutput
->addImage( $nt->getDBkey() );
1824 wfProfileOut( __METHOD__
."-media" );
1828 wfProfileIn( __METHOD__
."-always_known" );
1829 # Some titles, such as valid special pages or files in foreign repos, should
1830 # be shown as bluelinks even though they're not included in the page table
1832 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1833 # batch file existence checks for NS_FILE and NS_MEDIA
1834 if( $iw == '' && $nt->isAlwaysKnown() ) {
1835 $this->mOutput
->addLink( $nt );
1836 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1838 # Links will be added to the output link list after checking
1839 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1841 wfProfileOut( __METHOD__
."-always_known" );
1843 wfProfileOut( __METHOD__
);
1848 * Make a link placeholder. The text returned can be later resolved to a real link with
1849 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1850 * parsing of interwiki links, and secondly to allow all existence checks and
1851 * article length checks (for stub links) to be bundled into a single query.
1855 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1856 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1860 * Render a forced-blue link inline; protect against double expansion of
1861 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1862 * Since this little disaster has to split off the trail text to avoid
1863 * breaking URLs in the following text without breaking trails on the
1864 * wiki links, it's been made into a horrible function.
1867 * @param string $text
1868 * @param string $query
1869 * @param string $trail
1870 * @param string $prefix
1871 * @return string HTML-wikitext mix oh yuck
1873 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1874 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1875 $sk = $this->mOptions
->getSkin();
1876 // FIXME: use link() instead of deprecated makeKnownLinkObj()
1877 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1878 return $this->armorLinks( $link ) . $trail;
1882 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1883 * going to go through further parsing steps before inline URL expansion.
1885 * Not needed quite as much as it used to be since free links are a bit
1886 * more sensible these days. But bracketed links are still an issue.
1888 * @param string more-or-less HTML
1889 * @return string less-or-more HTML with NOPARSE bits
1891 function armorLinks( $text ) {
1892 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1893 "{$this->mUniqPrefix}NOPARSE$1", $text );
1897 * Return true if subpage links should be expanded on this page.
1900 function areSubpagesAllowed() {
1901 # Some namespaces don't allow subpages
1902 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
1906 * Handle link to subpage if necessary
1907 * @param string $target the source of the link
1908 * @param string &$text the link text, modified as necessary
1909 * @return string the full name of the link
1912 function maybeDoSubpageLink($target, &$text) {
1913 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
1917 * From the [[title|]] return link-text as though the used typed [[title|link-text]]
1918 * @param string $link from [[$link|]]
1919 * @return string $text for [[$link|$text]]
1921 function getPipeTrickText( $link ) {
1922 return Linker
::getPipeTrickText( $link );
1926 * From the [[|link-text]] return the title as though the user typed [[title|link-text]]
1927 * @param string $text from [[|$text]]
1928 * @param Title $title to resolve the link against
1929 * @return string $link for [[$link|$text]]
1931 function getPipeTrickLink( $text ) {
1932 return Linker
::getPipeTrickLink( $text, $this->mTitle
);
1936 * Used by doBlockLevels()
1939 /* private */ function closeParagraph() {
1941 if ( $this->mLastSection
!= '' ) {
1942 $result = '</' . $this->mLastSection
. ">\n";
1944 $this->mInPre
= false;
1945 $this->mLastSection
= '';
1948 # getCommon() returns the length of the longest common substring
1949 # of both arguments, starting at the beginning of both.
1951 /* private */ function getCommon( $st1, $st2 ) {
1952 $fl = strlen( $st1 );
1953 $shorter = strlen( $st2 );
1954 if ( $fl < $shorter ) { $shorter = $fl; }
1956 for ( $i = 0; $i < $shorter; ++
$i ) {
1957 if ( $st1{$i} != $st2{$i} ) { break; }
1961 # These next three functions open, continue, and close the list
1962 # element appropriate to the prefix character passed into them.
1964 /* private */ function openList( $char ) {
1965 $result = $this->closeParagraph();
1967 if ( '*' === $char ) { $result .= '<ul><li>'; }
1968 elseif ( '#' === $char ) { $result .= '<ol><li>'; }
1969 elseif ( ':' === $char ) { $result .= '<dl><dd>'; }
1970 elseif ( ';' === $char ) {
1971 $result .= '<dl><dt>';
1972 $this->mDTopen
= true;
1974 else { $result = '<!-- ERR 1 -->'; }
1979 /* private */ function nextItem( $char ) {
1980 if ( '*' === $char ||
'#' === $char ) { return '</li><li>'; }
1981 elseif ( ':' === $char ||
';' === $char ) {
1983 if ( $this->mDTopen
) { $close = '</dt>'; }
1984 if ( ';' === $char ) {
1985 $this->mDTopen
= true;
1986 return $close . '<dt>';
1988 $this->mDTopen
= false;
1989 return $close . '<dd>';
1992 return '<!-- ERR 2 -->';
1995 /* private */ function closeList( $char ) {
1996 if ( '*' === $char ) { $text = '</li></ul>'; }
1997 elseif ( '#' === $char ) { $text = '</li></ol>'; }
1998 elseif ( ':' === $char ) {
1999 if ( $this->mDTopen
) {
2000 $this->mDTopen
= false;
2001 $text = '</dt></dl>';
2003 $text = '</dd></dl>';
2006 else { return '<!-- ERR 3 -->'; }
2012 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2014 * @param $linestart bool whether or not this is at the start of a line.
2016 * @return string the lists rendered as HTML
2018 function doBlockLevels( $text, $linestart ) {
2019 wfProfileIn( __METHOD__
);
2021 # Parsing through the text line by line. The main thing
2022 # happening here is handling of block-level elements p, pre,
2023 # and making lists from lines starting with * # : etc.
2025 $textLines = StringUtils
::explode( "\n", $text );
2027 $lastPrefix = $output = '';
2028 $this->mDTopen
= $inBlockElem = false;
2030 $paragraphStack = false;
2032 foreach ( $textLines as $oLine ) {
2034 if ( !$linestart ) {
2044 $lastPrefixLength = strlen( $lastPrefix );
2045 $preCloseMatch = preg_match('/<\\/pre/i', $oLine );
2046 $preOpenMatch = preg_match('/<pre/i', $oLine );
2047 // If not in a <pre> element, scan for and figure out what prefixes are there.
2048 if ( !$this->mInPre
) {
2049 # Multiple prefixes may abut each other for nested lists.
2050 $prefixLength = strspn( $oLine, '*#:;' );
2051 $prefix = substr( $oLine, 0, $prefixLength );
2054 // ; and : are both from definition-lists, so they're equivalent
2055 // for the purposes of determining whether or not we need to open/close
2057 $prefix2 = str_replace( ';', ':', $prefix );
2058 $t = substr( $oLine, $prefixLength );
2059 $this->mInPre
= (bool)$preOpenMatch;
2061 # Don't interpret any other prefixes in preformatted text
2063 $prefix = $prefix2 = '';
2068 if( $prefixLength && $lastPrefix === $prefix2 ) {
2069 # Same as the last item, so no need to deal with nesting or opening stuff
2070 $output .= $this->nextItem( substr( $prefix, -1 ) );
2071 $paragraphStack = false;
2073 if ( substr( $prefix, -1 ) === ';') {
2074 # The one nasty exception: definition lists work like this:
2075 # ; title : definition text
2076 # So we check for : in the remainder text to split up the
2077 # title and definition, without b0rking links.
2079 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2081 $output .= $term . $this->nextItem( ':' );
2084 } elseif( $prefixLength ||
$lastPrefixLength ) {
2085 // We need to open or close prefixes, or both.
2087 # Either open or close a level...
2088 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2089 $paragraphStack = false;
2091 // Close all the prefixes which aren't shared.
2092 while( $commonPrefixLength < $lastPrefixLength ) {
2093 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2094 --$lastPrefixLength;
2097 // Continue the current prefix if appropriate.
2098 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2099 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2102 // Open prefixes where appropriate.
2103 while ( $prefixLength > $commonPrefixLength ) {
2104 $char = substr( $prefix, $commonPrefixLength, 1 );
2105 $output .= $this->openList( $char );
2107 if ( ';' === $char ) {
2108 # FIXME: This is dupe of code above
2109 if ($this->findColonNoLinks($t, $term, $t2) !== false) {
2111 $output .= $term . $this->nextItem( ':' );
2114 ++
$commonPrefixLength;
2116 $lastPrefix = $prefix2;
2119 // If we have no prefixes, go to paragraph mode.
2120 if( 0 == $prefixLength ) {
2121 wfProfileIn( __METHOD__
."-paragraph" );
2122 # No prefix (not in list)--go to paragraph mode
2123 // XXX: use a stack for nestable elements like span, table and div
2124 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2125 $closematch = preg_match(
2126 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2127 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2128 if ( $openmatch or $closematch ) {
2129 $paragraphStack = false;
2130 #Â TODO bug 5718: paragraph closed
2131 $output .= $this->closeParagraph();
2132 if ( $preOpenMatch and !$preCloseMatch ) {
2133 $this->mInPre
= true;
2135 if ( $closematch ) {
2136 $inBlockElem = false;
2138 $inBlockElem = true;
2140 } else if ( !$inBlockElem && !$this->mInPre
) {
2141 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' or trim($t) != '' ) ) {
2143 if ($this->mLastSection
!== 'pre') {
2144 $paragraphStack = false;
2145 $output .= $this->closeParagraph().'<pre>';
2146 $this->mLastSection
= 'pre';
2148 $t = substr( $t, 1 );
2151 if ( trim($t) == '' ) {
2152 if ( $paragraphStack ) {
2153 $output .= $paragraphStack.'<br />';
2154 $paragraphStack = false;
2155 $this->mLastSection
= 'p';
2157 if ($this->mLastSection
!== 'p' ) {
2158 $output .= $this->closeParagraph();
2159 $this->mLastSection
= '';
2160 $paragraphStack = '<p>';
2162 $paragraphStack = '</p><p>';
2166 if ( $paragraphStack ) {
2167 $output .= $paragraphStack;
2168 $paragraphStack = false;
2169 $this->mLastSection
= 'p';
2170 } else if ($this->mLastSection
!== 'p') {
2171 $output .= $this->closeParagraph().'<p>';
2172 $this->mLastSection
= 'p';
2177 wfProfileOut( __METHOD__
."-paragraph" );
2179 // somewhere above we forget to get out of pre block (bug 785)
2180 if($preCloseMatch && $this->mInPre
) {
2181 $this->mInPre
= false;
2183 if ($paragraphStack === false) {
2187 while ( $prefixLength ) {
2188 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2191 if ( $this->mLastSection
!= '' ) {
2192 $output .= '</' . $this->mLastSection
. '>';
2193 $this->mLastSection
= '';
2196 wfProfileOut( __METHOD__
);
2201 * Split up a string on ':', ignoring any occurences inside tags
2202 * to prevent illegal overlapping.
2203 * @param string $str the string to split
2204 * @param string &$before set to everything before the ':'
2205 * @param string &$after set to everything after the ':'
2206 * return string the position of the ':', or false if none found
2208 function findColonNoLinks($str, &$before, &$after) {
2209 wfProfileIn( __METHOD__
);
2211 $pos = strpos( $str, ':' );
2212 if( $pos === false ) {
2214 wfProfileOut( __METHOD__
);
2218 $lt = strpos( $str, '<' );
2219 if( $lt === false ||
$lt > $pos ) {
2220 // Easy; no tag nesting to worry about
2221 $before = substr( $str, 0, $pos );
2222 $after = substr( $str, $pos+
1 );
2223 wfProfileOut( __METHOD__
);
2227 // Ugly state machine to walk through avoiding tags.
2228 $state = self
::COLON_STATE_TEXT
;
2230 $len = strlen( $str );
2231 for( $i = 0; $i < $len; $i++
) {
2235 // (Using the number is a performance hack for common cases)
2236 case 0: // self::COLON_STATE_TEXT:
2239 // Could be either a <start> tag or an </end> tag
2240 $state = self
::COLON_STATE_TAGSTART
;
2245 $before = substr( $str, 0, $i );
2246 $after = substr( $str, $i +
1 );
2247 wfProfileOut( __METHOD__
);
2250 // Embedded in a tag; don't break it.
2253 // Skip ahead looking for something interesting
2254 $colon = strpos( $str, ':', $i );
2255 if( $colon === false ) {
2256 // Nothing else interesting
2257 wfProfileOut( __METHOD__
);
2260 $lt = strpos( $str, '<', $i );
2261 if( $stack === 0 ) {
2262 if( $lt === false ||
$colon < $lt ) {
2264 $before = substr( $str, 0, $colon );
2265 $after = substr( $str, $colon +
1 );
2266 wfProfileOut( __METHOD__
);
2270 if( $lt === false ) {
2271 // Nothing else interesting to find; abort!
2272 // We're nested, but there's no close tags left. Abort!
2275 // Skip ahead to next tag start
2277 $state = self
::COLON_STATE_TAGSTART
;
2280 case 1: // self::COLON_STATE_TAG:
2285 $state = self
::COLON_STATE_TEXT
;
2288 // Slash may be followed by >?
2289 $state = self
::COLON_STATE_TAGSLASH
;
2295 case 2: // self::COLON_STATE_TAGSTART:
2298 $state = self
::COLON_STATE_CLOSETAG
;
2301 $state = self
::COLON_STATE_COMMENT
;
2304 // Illegal early close? This shouldn't happen D:
2305 $state = self
::COLON_STATE_TEXT
;
2308 $state = self
::COLON_STATE_TAG
;
2311 case 3: // self::COLON_STATE_CLOSETAG:
2316 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2317 wfProfileOut( __METHOD__
);
2320 $state = self
::COLON_STATE_TEXT
;
2323 case self
::COLON_STATE_TAGSLASH
:
2325 // Yes, a self-closed tag <blah/>
2326 $state = self
::COLON_STATE_TEXT
;
2328 // Probably we're jumping the gun, and this is an attribute
2329 $state = self
::COLON_STATE_TAG
;
2332 case 5: // self::COLON_STATE_COMMENT:
2334 $state = self
::COLON_STATE_COMMENTDASH
;
2337 case self
::COLON_STATE_COMMENTDASH
:
2339 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2341 $state = self
::COLON_STATE_COMMENT
;
2344 case self
::COLON_STATE_COMMENTDASHDASH
:
2346 $state = self
::COLON_STATE_TEXT
;
2348 $state = self
::COLON_STATE_COMMENT
;
2352 throw new MWException( "State machine error in " . __METHOD__
);
2356 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2359 wfProfileOut( __METHOD__
);
2364 * Return value of a magic variable (like PAGENAME)
2368 function getVariableValue( $index, $frame=false ) {
2369 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2370 global $wgScriptPath, $wgStylePath;
2373 * Some of these require message or data lookups and can be
2374 * expensive to check many times.
2376 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2377 if ( isset( $this->mVarCache
[$index] ) ) {
2378 return $this->mVarCache
[$index];
2382 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2383 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2386 global $wgLocaltimezone;
2387 if ( isset( $wgLocaltimezone ) ) {
2388 $oldtz = date_default_timezone_get();
2389 date_default_timezone_set( $wgLocaltimezone );
2392 $localTimestamp = date( 'YmdHis', $ts );
2393 $localMonth = date( 'm', $ts );
2394 $localMonth1 = date( 'n', $ts );
2395 $localMonthName = date( 'n', $ts );
2396 $localDay = date( 'j', $ts );
2397 $localDay2 = date( 'd', $ts );
2398 $localDayOfWeek = date( 'w', $ts );
2399 $localWeek = date( 'W', $ts );
2400 $localYear = date( 'Y', $ts );
2401 $localHour = date( 'H', $ts );
2402 if ( isset( $wgLocaltimezone ) ) {
2403 date_default_timezone_set( $oldtz );
2407 case 'currentmonth':
2408 $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2410 case 'currentmonth1':
2411 $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2413 case 'currentmonthname':
2414 $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2416 case 'currentmonthnamegen':
2417 $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2419 case 'currentmonthabbrev':
2420 $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2423 $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2426 $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2429 $value = $wgContLang->formatNum( $localMonth );
2432 $value = $wgContLang->formatNum( $localMonth1 );
2434 case 'localmonthname':
2435 $value = $wgContLang->getMonthName( $localMonthName );
2437 case 'localmonthnamegen':
2438 $value = $wgContLang->getMonthNameGen( $localMonthName );
2440 case 'localmonthabbrev':
2441 $value = $wgContLang->getMonthAbbreviation( $localMonthName );
2444 $value = $wgContLang->formatNum( $localDay );
2447 $value = $wgContLang->formatNum( $localDay2 );
2450 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2453 $value = $this->mTitle
->getPartialURL();
2455 case 'fullpagename':
2456 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2458 case 'fullpagenamee':
2459 $value = $this->mTitle
->getPrefixedURL();
2462 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2464 case 'subpagenamee':
2465 $value = $this->mTitle
->getSubpageUrlForm();
2467 case 'basepagename':
2468 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2470 case 'basepagenamee':
2471 $value = wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2473 case 'talkpagename':
2474 if( $this->mTitle
->canTalk() ) {
2475 $talkPage = $this->mTitle
->getTalkPage();
2476 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2481 case 'talkpagenamee':
2482 if( $this->mTitle
->canTalk() ) {
2483 $talkPage = $this->mTitle
->getTalkPage();
2484 $value = $talkPage->getPrefixedUrl();
2489 case 'subjectpagename':
2490 $subjPage = $this->mTitle
->getSubjectPage();
2491 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2493 case 'subjectpagenamee':
2494 $subjPage = $this->mTitle
->getSubjectPage();
2495 $value = $subjPage->getPrefixedUrl();
2498 $text = $this->mTitle
->getText();
2499 $value = $this->getPipeTrickText( $text );
2502 $text = $this->mTitle
->getText();
2503 $value = wfUrlEncode( str_replace( ' ', '_', $this->getPipeTrickText( $text ) ) );
2506 // Let the edit saving system know we should parse the page
2507 // *after* a revision ID has been assigned.
2508 $this->mOutput
->setFlag( 'vary-revision' );
2509 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2510 $value = $this->mRevisionId
;
2513 // Let the edit saving system know we should parse the page
2514 // *after* a revision ID has been assigned. This is for null edits.
2515 $this->mOutput
->setFlag( 'vary-revision' );
2516 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2517 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2519 case 'revisionday2':
2520 // Let the edit saving system know we should parse the page
2521 // *after* a revision ID has been assigned. This is for null edits.
2522 $this->mOutput
->setFlag( 'vary-revision' );
2523 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2524 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2526 case 'revisionmonth':
2527 // Let the edit saving system know we should parse the page
2528 // *after* a revision ID has been assigned. This is for null edits.
2529 $this->mOutput
->setFlag( 'vary-revision' );
2530 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2531 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2533 case 'revisionyear':
2534 // Let the edit saving system know we should parse the page
2535 // *after* a revision ID has been assigned. This is for null edits.
2536 $this->mOutput
->setFlag( 'vary-revision' );
2537 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2538 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2540 case 'revisiontimestamp':
2541 // Let the edit saving system know we should parse the page
2542 // *after* a revision ID has been assigned. This is for null edits.
2543 $this->mOutput
->setFlag( 'vary-revision' );
2544 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2545 $value = $this->getRevisionTimestamp();
2547 case 'revisionuser':
2548 // Let the edit saving system know we should parse the page
2549 // *after* a revision ID has been assigned. This is for null edits.
2550 $this->mOutput
->setFlag( 'vary-revision' );
2551 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2552 $value = $this->getRevisionUser();
2555 $value = str_replace('_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2558 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2561 $value = $this->mTitle
->canTalk() ?
str_replace('_',' ',$this->mTitle
->getTalkNsText()) : '';
2564 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2566 case 'subjectspace':
2567 $value = $this->mTitle
->getSubjectNsText();
2569 case 'subjectspacee':
2570 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2572 case 'currentdayname':
2573 $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2576 $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2579 $value = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2582 $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2585 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2586 // int to remove the padding
2587 $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2590 $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2592 case 'localdayname':
2593 $value = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2596 $value = $wgContLang->formatNum( $localYear, true );
2599 $value = $wgContLang->time( $localTimestamp, false, false );
2602 $value = $wgContLang->formatNum( $localHour, true );
2605 // @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2606 // int to remove the padding
2607 $value = $wgContLang->formatNum( (int)$localWeek );
2610 $value = $wgContLang->formatNum( $localDayOfWeek );
2612 case 'numberofarticles':
2613 $value = $wgContLang->formatNum( SiteStats
::articles() );
2615 case 'numberoffiles':
2616 $value = $wgContLang->formatNum( SiteStats
::images() );
2618 case 'numberofusers':
2619 $value = $wgContLang->formatNum( SiteStats
::users() );
2621 case 'numberofactiveusers':
2622 $value = $wgContLang->formatNum( SiteStats
::activeUsers() );
2624 case 'numberofpages':
2625 $value = $wgContLang->formatNum( SiteStats
::pages() );
2627 case 'numberofadmins':
2628 $value = $wgContLang->formatNum( SiteStats
::numberingroup('sysop') );
2630 case 'numberofedits':
2631 $value = $wgContLang->formatNum( SiteStats
::edits() );
2633 case 'numberofviews':
2634 $value = $wgContLang->formatNum( SiteStats
::views() );
2636 case 'currenttimestamp':
2637 $value = wfTimestamp( TS_MW
, $ts );
2639 case 'localtimestamp':
2640 $value = $localTimestamp;
2642 case 'currentversion':
2643 $value = SpecialVersion
::getVersion();
2650 return $wgServerName;
2652 return $wgScriptPath;
2654 return $wgStylePath;
2655 case 'directionmark':
2656 return $wgContLang->getDirMark();
2657 case 'contentlanguage':
2658 global $wgContLanguageCode;
2659 return $wgContLanguageCode;
2662 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) )
2669 $this->mVarCache
[$index] = $value;
2675 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2679 function initialiseVariables() {
2680 wfProfileIn( __METHOD__
);
2681 $variableIDs = MagicWord
::getVariableIDs();
2682 $substIDs = MagicWord
::getSubstIDs();
2684 $this->mVariables
= new MagicWordArray( $variableIDs );
2685 $this->mSubsts
= new MagicWordArray( $substIDs );
2686 wfProfileOut( __METHOD__
);
2690 * Preprocess some wikitext and return the document tree.
2691 * This is the ghost of replace_variables().
2693 * @param string $text The text to parse
2694 * @param integer flags Bitwise combination of:
2695 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2696 * included. Default is to assume a direct page view.
2698 * The generated DOM tree must depend only on the input text and the flags.
2699 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2701 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2702 * change in the DOM tree for a given text, must be passed through the section identifier
2703 * in the section edit link and thus back to extractSections().
2705 * The output of this function is currently only cached in process memory, but a persistent
2706 * cache may be implemented at a later date which takes further advantage of these strict
2707 * dependency requirements.
2711 function preprocessToDom ( $text, $flags = 0 ) {
2712 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2717 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2719 public static function splitWhitespace( $s ) {
2720 $ltrimmed = ltrim( $s );
2721 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2722 $trimmed = rtrim( $ltrimmed );
2723 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2725 $w2 = substr( $ltrimmed, -$diff );
2729 return array( $w1, $trimmed, $w2 );
2733 * Replace magic variables, templates, and template arguments
2734 * with the appropriate text. Templates are substituted recursively,
2735 * taking care to avoid infinite loops.
2737 * Note that the substitution depends on value of $mOutputType:
2738 * self::OT_WIKI: only {{subst:}} templates
2739 * self::OT_PREPROCESS: templates but not extension tags
2740 * self::OT_HTML: all templates and extension tags
2742 * @param string $tex The text to transform
2743 * @param PPFrame $frame Object describing the arguments passed to the template.
2744 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2745 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2746 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2749 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2750 # Is there any text? Also, Prevent too big inclusions!
2751 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2754 wfProfileIn( __METHOD__
);
2756 if ( $frame === false ) {
2757 $frame = $this->getPreprocessor()->newFrame();
2758 } elseif ( !( $frame instanceof PPFrame
) ) {
2759 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2760 $frame = $this->getPreprocessor()->newCustomFrame($frame);
2763 $dom = $this->preprocessToDom( $text );
2764 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2765 $text = $frame->expand( $dom, $flags );
2767 wfProfileOut( __METHOD__
);
2771 /// Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2772 static function createAssocArgs( $args ) {
2773 $assocArgs = array();
2775 foreach( $args as $arg ) {
2776 $eqpos = strpos( $arg, '=' );
2777 if ( $eqpos === false ) {
2778 $assocArgs[$index++
] = $arg;
2780 $name = trim( substr( $arg, 0, $eqpos ) );
2781 $value = trim( substr( $arg, $eqpos+
1 ) );
2782 if ( $value === false ) {
2785 if ( $name !== false ) {
2786 $assocArgs[$name] = $value;
2795 * Warn the user when a parser limitation is reached
2796 * Will warn at most once the user per limitation type
2798 * @param string $limitationType, should be one of:
2799 * 'expensive-parserfunction' (corresponding messages: 'expensive-parserfunction-warning', 'expensive-parserfunction-category')
2800 * 'post-expand-template-argument' (corresponding messages: 'post-expand-template-argument-warning', 'post-expand-template-argument-category')
2801 * 'post-expand-template-inclusion' (corresponding messages: 'post-expand-template-inclusion-warning', 'post-expand-template-inclusion-category')
2802 * @params int $current, $max When an explicit limit has been
2803 * exceeded, provide the values (optional)
2805 function limitationWarn( $limitationType, $current=null, $max=null) {
2806 //does no harm if $current and $max are present but are unnecessary for the message
2807 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
2808 $this->mOutput
->addWarning( $warning );
2809 $this->addTrackingCategory( "$limitationType-category" );
2813 * Return the text of a template, after recursively
2814 * replacing any variables or templates within the template.
2816 * @param array $piece The parts of the template
2817 * $piece['title']: the title, i.e. the part before the |
2818 * $piece['parts']: the parameter array
2819 * $piece['lineStart']: whether the brace was at the start of a line
2820 * @param PPFrame The current frame, contains template arguments
2821 * @return string the text of the template
2824 function braceSubstitution( $piece, $frame ) {
2825 global $wgContLang, $wgNonincludableNamespaces;
2826 wfProfileIn( __METHOD__
);
2827 wfProfileIn( __METHOD__
.'-setup' );
2830 $found = false; # $text has been filled
2831 $nowiki = false; # wiki markup in $text should be escaped
2832 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2833 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2834 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2835 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2837 # Title object, where $text came from
2840 # $part1 is the bit before the first |, and must contain only title characters.
2841 # Various prefixes will be stripped from it later.
2842 $titleWithSpaces = $frame->expand( $piece['title'] );
2843 $part1 = trim( $titleWithSpaces );
2846 # Original title text preserved for various purposes
2847 $originalTitle = $part1;
2849 # $args is a list of argument nodes, starting from index 0, not including $part1
2850 $args = (null == $piece['parts']) ?
array() : $piece['parts'];
2851 wfProfileOut( __METHOD__
.'-setup' );
2854 wfProfileIn( __METHOD__
.'-modifiers' );
2857 $substMatch = $this->mSubsts
->matchStartAndRemove( $part1 );
2859 # Possibilities for substMatch: "subst", "safesubst" or FALSE
2860 # Whether to include depends also on whether we are in the pre-save-transform
2862 # safesubst || (subst && PST) || (false && !PST) => transclude (skip the if)
2863 # (false && PST) || (subst && !PST) => return input (handled by if)
2864 if ( $substMatch != 'safesubst' && ($substMatch == 'subst' xor $this->ot
['wiki']) ) {
2865 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2872 if ( !$found && $args->getLength() == 0 ) {
2873 $id = $this->mVariables
->matchStartToEnd( $part1 );
2874 if ( $id !== false ) {
2875 $text = $this->getVariableValue( $id, $frame );
2876 if (MagicWord
::getCacheTTL($id)>-1)
2877 $this->mOutput
->mContainsOldMagic
= true;
2882 # MSG, MSGNW and RAW
2885 $mwMsgnw = MagicWord
::get( 'msgnw' );
2886 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2889 # Remove obsolete MSG:
2890 $mwMsg = MagicWord
::get( 'msg' );
2891 $mwMsg->matchStartAndRemove( $part1 );
2895 $mwRaw = MagicWord
::get( 'raw' );
2896 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2897 $forceRawInterwiki = true;
2900 wfProfileOut( __METHOD__
.'-modifiers' );
2904 wfProfileIn( __METHOD__
. '-pfunc' );
2906 $colonPos = strpos( $part1, ':' );
2907 if ( $colonPos !== false ) {
2908 # Case sensitive functions
2909 $function = substr( $part1, 0, $colonPos );
2910 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2911 $function = $this->mFunctionSynonyms
[1][$function];
2913 # Case insensitive functions
2914 $function = $wgContLang->lc( $function );
2915 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2916 $function = $this->mFunctionSynonyms
[0][$function];
2922 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2923 $initialArgs = array( &$this );
2924 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2925 if ( $flags & SFH_OBJECT_ARGS
) {
2926 # Add a frame parameter, and pass the arguments as an array
2927 $allArgs = $initialArgs;
2928 $allArgs[] = $frame;
2929 for ( $i = 0; $i < $args->getLength(); $i++
) {
2930 $funcArgs[] = $args->item( $i );
2932 $allArgs[] = $funcArgs;
2934 # Convert arguments to plain text
2935 for ( $i = 0; $i < $args->getLength(); $i++
) {
2936 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2938 $allArgs = array_merge( $initialArgs, $funcArgs );
2941 # Workaround for PHP bug 35229 and similar
2942 if ( !is_callable( $callback ) ) {
2943 wfProfileOut( __METHOD__
. '-pfunc' );
2944 wfProfileOut( __METHOD__
);
2945 throw new MWException( "Tag hook for $function is not callable\n" );
2947 $result = call_user_func_array( $callback, $allArgs );
2950 $preprocessFlags = 0;
2952 if ( is_array( $result ) ) {
2953 if ( isset( $result[0] ) ) {
2955 unset( $result[0] );
2958 // Extract flags into the local scope
2959 // This allows callers to set flags such as nowiki, found, etc.
2965 $text = $this->preprocessToDom( $text, $preprocessFlags );
2970 wfProfileOut( __METHOD__
. '-pfunc' );
2973 # Finish mangling title and then check for loops.
2974 # Set $title to a Title object and $titleText to the PDBK
2977 # Split the title into page and subpage
2979 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2980 if ($subpage !== '') {
2981 $ns = $this->mTitle
->getNamespace();
2983 $title = Title
::newFromText( $part1, $ns );
2985 $titleText = $title->getPrefixedText();
2986 # Check for language variants if the template is not found
2987 if($wgContLang->hasVariants() && $title->getArticleID() == 0){
2988 $wgContLang->findVariantLink( $part1, $title, true );
2990 # Do recursion depth check
2991 $limit = $this->mOptions
->getMaxTemplateDepth();
2992 if ( $frame->depth
>= $limit ) {
2994 $text = '<span class="error">' . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit ) . '</span>';
2999 # Load from database
3000 if ( !$found && $title ) {
3001 wfProfileIn( __METHOD__
. '-loadtpl' );
3002 if ( !$title->isExternal() ) {
3003 if ( $title->getNamespace() == NS_SPECIAL
&& $this->mOptions
->getAllowSpecialInclusion() && $this->ot
['html'] ) {
3004 $text = SpecialPage
::capturePath( $title );
3005 if ( is_string( $text ) ) {
3008 $this->disableCache();
3010 } else if ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3011 $found = false; //access denied
3012 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3014 list( $text, $title ) = $this->getTemplateDom( $title );
3015 if ( $text !== false ) {
3021 # If the title is valid but undisplayable, make a link to it
3022 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3023 $text = "[[:$titleText]]";
3026 } elseif ( $title->isTrans() ) {
3027 // Interwiki transclusion
3028 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3029 $text = $this->interwikiTransclude( $title, 'render' );
3032 $text = $this->interwikiTransclude( $title, 'raw' );
3033 // Preprocess it like a template
3034 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3040 # Do infinite loop check
3041 # This has to be done after redirect resolution to avoid infinite loops via redirects
3042 if ( !$frame->loopCheck( $title ) ) {
3044 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3045 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3047 wfProfileOut( __METHOD__
. '-loadtpl' );
3050 # If we haven't found text to substitute by now, we're done
3051 # Recover the source wikitext and return it
3053 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3054 wfProfileOut( __METHOD__
);
3055 return array( 'object' => $text );
3058 # Expand DOM-style return values in a child frame
3059 if ( $isChildObj ) {
3060 # Clean up argument array
3061 $newFrame = $frame->newChild( $args, $title );
3064 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3065 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3066 # Expansion is eligible for the empty-frame cache
3067 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3068 $text = $this->mTplExpandCache
[$titleText];
3070 $text = $newFrame->expand( $text );
3071 $this->mTplExpandCache
[$titleText] = $text;
3074 # Uncached expansion
3075 $text = $newFrame->expand( $text );
3078 if ( $isLocalObj && $nowiki ) {
3079 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3080 $isLocalObj = false;
3083 # Replace raw HTML by a placeholder
3084 # Add a blank line preceding, to prevent it from mucking up
3085 # immediately preceding headings
3087 $text = "\n\n" . $this->insertStripItem( $text );
3089 # Escape nowiki-style return values
3090 elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3091 $text = wfEscapeWikiText( $text );
3093 # Bug 529: if the template begins with a table or block-level
3094 # element, it should be treated as beginning a new line.
3095 # This behaviour is somewhat controversial.
3096 elseif ( is_string( $text ) && !$piece['lineStart'] && preg_match('/^(?:{\\||:|;|#|\*)/', $text)) /*}*/{
3097 $text = "\n" . $text;
3100 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3101 # Error, oversize inclusion
3102 $text = "[[$originalTitle]]" .
3103 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3104 $this->limitationWarn( 'post-expand-template-inclusion' );
3107 if ( $isLocalObj ) {
3108 $ret = array( 'object' => $text );
3110 $ret = array( 'text' => $text );
3113 wfProfileOut( __METHOD__
);
3118 * Get the semi-parsed DOM representation of a template with a given title,
3119 * and its redirect destination title. Cached.
3121 function getTemplateDom( $title ) {
3122 $cacheTitle = $title;
3123 $titleText = $title->getPrefixedDBkey();
3125 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3126 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3127 $title = Title
::makeTitle( $ns, $dbk );
3128 $titleText = $title->getPrefixedDBkey();
3130 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3131 return array( $this->mTplDomCache
[$titleText], $title );
3134 // Cache miss, go to the database
3135 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3137 if ( $text === false ) {
3138 $this->mTplDomCache
[$titleText] = false;
3139 return array( false, $title );
3142 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3143 $this->mTplDomCache
[ $titleText ] = $dom;
3145 if (! $title->equals($cacheTitle)) {
3146 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3147 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3150 return array( $dom, $title );
3154 * Fetch the unparsed text of a template and register a reference to it.
3156 function fetchTemplateAndTitle( $title ) {
3157 $templateCb = $this->mOptions
->getTemplateCallback();
3158 $stuff = call_user_func( $templateCb, $title, $this );
3159 $text = $stuff['text'];
3160 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3161 if ( isset( $stuff['deps'] ) ) {
3162 foreach ( $stuff['deps'] as $dep ) {
3163 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3166 return array($text,$finalTitle);
3169 function fetchTemplate( $title ) {
3170 $rv = $this->fetchTemplateAndTitle($title);
3175 * Static function to get a template
3176 * Can be overridden via ParserOptions::setTemplateCallback().
3178 static function statelessFetchTemplate( $title, $parser=false ) {
3179 $text = $skip = false;
3180 $finalTitle = $title;
3183 // Loop to fetch the article, with up to 1 redirect
3184 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3185 # Give extensions a chance to select the revision instead
3186 $id = false; // Assume current
3187 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3193 'page_id' => $title->getArticleID(),
3197 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3198 $rev_id = $rev ?
$rev->getId() : 0;
3199 // If there is no current revision, there is no page
3200 if( $id === false && !$rev ) {
3201 $linkCache = LinkCache
::singleton();
3202 $linkCache->addBadLinkObj( $title );
3207 'page_id' => $title->getArticleID(),
3208 'rev_id' => $rev_id );
3211 $text = $rev->getText();
3212 } elseif( $title->getNamespace() == NS_MEDIAWIKI
) {
3214 $message = $wgContLang->lcfirst( $title->getText() );
3215 $text = wfMsgForContentNoTrans( $message );
3216 if( wfEmptyMsg( $message, $text ) ) {
3223 if ( $text === false ) {
3227 $finalTitle = $title;
3228 $title = Title
::newFromRedirect( $text );
3232 'finalTitle' => $finalTitle,
3237 * Transclude an interwiki link.
3239 function interwikiTransclude( $title, $action ) {
3240 global $wgEnableScaryTranscluding;
3242 if (!$wgEnableScaryTranscluding)
3243 return wfMsg('scarytranscludedisabled');
3245 $url = $title->getFullUrl( "action=$action" );
3247 if (strlen($url) > 255)
3248 return wfMsg('scarytranscludetoolong');
3249 return $this->fetchScaryTemplateMaybeFromCache($url);
3252 function fetchScaryTemplateMaybeFromCache($url) {
3253 global $wgTranscludeCacheExpiry;
3254 $dbr = wfGetDB(DB_SLAVE
);
3255 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3256 $obj = $dbr->selectRow('transcache', array('tc_time', 'tc_contents'),
3257 array('tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3259 return $obj->tc_contents
;
3262 $text = Http
::get($url);
3264 return wfMsg('scarytranscludefailed', $url);
3266 $dbw = wfGetDB(DB_MASTER
);
3267 $dbw->replace('transcache', array('tc_url'), array(
3269 'tc_time' => $dbw->timestamp( time() ),
3270 'tc_contents' => $text));
3276 * Triple brace replacement -- used for template arguments
3279 function argSubstitution( $piece, $frame ) {
3280 wfProfileIn( __METHOD__
);
3283 $parts = $piece['parts'];
3284 $nameWithSpaces = $frame->expand( $piece['title'] );
3285 $argName = trim( $nameWithSpaces );
3287 $text = $frame->getArgument( $argName );
3288 if ( $text === false && $parts->getLength() > 0
3292 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3295 # No match in frame, use the supplied default
3296 $object = $parts->item( 0 )->getChildren();
3298 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3299 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3300 $this->limitationWarn( 'post-expand-template-argument' );
3303 if ( $text === false && $object === false ) {
3305 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3307 if ( $error !== false ) {
3310 if ( $object !== false ) {
3311 $ret = array( 'object' => $object );
3313 $ret = array( 'text' => $text );
3316 wfProfileOut( __METHOD__
);
3321 * Return the text to be used for a given extension tag.
3322 * This is the ghost of strip().
3324 * @param array $params Associative array of parameters:
3325 * name PPNode for the tag name
3326 * attr PPNode for unparsed text where tag attributes are thought to be
3327 * attributes Optional associative array of parsed attributes
3328 * inner Contents of extension element
3329 * noClose Original text did not have a close tag
3330 * @param PPFrame $frame
3332 function extensionSubstitution( $params, $frame ) {
3333 global $wgRawHtml, $wgContLang;
3335 $name = $frame->expand( $params['name'] );
3336 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3337 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3338 $marker = "{$this->mUniqPrefix}-$name-" . sprintf('%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3340 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3341 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3342 if ( $isFunctionTag ) {
3343 $markerType = 'none';
3345 $markerType = 'general';
3347 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3348 $name = strtolower( $name );
3349 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3350 if ( isset( $params['attributes'] ) ) {
3351 $attributes = $attributes +
$params['attributes'];
3354 if( isset( $this->mTagHooks
[$name] ) ) {
3355 # Workaround for PHP bug 35229 and similar
3356 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3357 throw new MWException( "Tag hook for $name is not callable\n" );
3359 $output = call_user_func_array( $this->mTagHooks
[$name],
3360 array( $content, $attributes, $this, $frame ) );
3361 } elseif( isset( $this->mFunctionTagHooks
[$name] ) ) {
3362 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3363 if( !is_callable( $callback ) )
3364 throw new MWException( "Tag hook for $name is not callable\n" );
3366 $output = call_user_func_array( $callback,
3367 array( &$this, $frame, $content, $attributes ) );
3369 $output = '<span class="error">Invalid tag extension name: ' .
3370 htmlspecialchars( $name ) . '</span>';
3373 if ( is_array( $output ) ) {
3374 // Extract flags to local scope (to override $markerType)
3376 $output = $flags[0];
3381 if ( is_null( $attrText ) ) {
3384 if ( isset( $params['attributes'] ) ) {
3385 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3386 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3387 htmlspecialchars( $attrValue ) . '"';
3390 if ( $content === null ) {
3391 $output = "<$name$attrText/>";
3393 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3394 $output = "<$name$attrText>$content$close";
3398 if( $markerType === 'none' ) {
3400 } elseif ( $markerType === 'nowiki' ) {
3401 $this->mStripState
->nowiki
->setPair( $marker, $output );
3402 } elseif ( $markerType === 'general' ) {
3403 $this->mStripState
->general
->setPair( $marker, $output );
3405 throw new MWException( __METHOD__
.': invalid marker type' );
3411 * Increment an include size counter
3413 * @param string $type The type of expansion
3414 * @param integer $size The size of the text
3415 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3417 function incrementIncludeSize( $type, $size ) {
3418 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3421 $this->mIncludeSizes
[$type] +
= $size;
3427 * Increment the expensive function count
3429 * @return boolean False if the limit has been exceeded
3431 function incrementExpensiveFunctionCount() {
3432 global $wgExpensiveParserFunctionLimit;
3433 $this->mExpensiveFunctionCount++
;
3434 if($this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit) {
3441 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3442 * Fills $this->mDoubleUnderscores, returns the modified text
3444 function doDoubleUnderscore( $text ) {
3445 wfProfileIn( __METHOD__
);
3447 // The position of __TOC__ needs to be recorded
3448 $mw = MagicWord
::get( 'toc' );
3449 if( $mw->match( $text ) ) {
3450 $this->mShowToc
= true;
3451 $this->mForceTocPosition
= true;
3453 // Set a placeholder. At the end we'll fill it in with the TOC.
3454 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3456 // Only keep the first one.
3457 $text = $mw->replace( '', $text );
3460 // Now match and remove the rest of them
3461 $mwa = MagicWord
::getDoubleUnderscoreArray();
3462 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3464 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3465 $this->mOutput
->mNoGallery
= true;
3467 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3468 $this->mShowToc
= false;
3470 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3471 $this->mOutput
->setProperty( 'hiddencat', 'y' );
3472 $this->addTrackingCategory( 'hidden-category-category' );
3474 # (bug 8068) Allow control over whether robots index a page.
3476 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3477 # is not desirable, the last one on the page should win.
3478 if( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3479 $this->mOutput
->setIndexPolicy( 'noindex' );
3480 $this->addTrackingCategory( 'noindex-category' );
3482 if( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ){
3483 $this->mOutput
->setIndexPolicy( 'index' );
3484 $this->addTrackingCategory( 'index-category' );
3487 wfProfileOut( __METHOD__
);
3492 * Add a tracking category, getting the title from a system message,
3493 * or print a debug message if the title is invalid.
3494 * @param $msg String message key
3495 * @return Bool whether the addition was successful
3497 protected function addTrackingCategory( $msg ){
3498 $cat = wfMsgForContent( $msg );
3500 # Allow tracking categories to be disabled by setting them to "-"
3501 if( $cat === '-' ) return false;
3503 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3504 if ( $containerCategory ) {
3505 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3508 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3514 * This function accomplishes several tasks:
3515 * 1) Auto-number headings if that option is enabled
3516 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3517 * 3) Add a Table of contents on the top for users who have enabled the option
3518 * 4) Auto-anchor headings
3520 * It loops through all headlines, collects the necessary data, then splits up the
3521 * string and re-inserts the newly formatted headlines.
3523 * @param string $text
3524 * @param string $origText Original, untouched wikitext
3525 * @param boolean $isMain
3528 function formatHeadings( $text, $origText, $isMain=true ) {
3529 global $wgMaxTocLevel, $wgContLang, $wgHtml5, $wgExperimentalHtmlIds;
3531 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3532 $showEditLink = $this->mOptions
->getEditSection();
3534 // Do not call quickUserCan unless necessary
3535 if( $showEditLink && !$this->mTitle
->quickUserCan( 'edit' ) ) {
3539 # Inhibit editsection links if requested in the page
3540 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ||
$this->mOptions
->getIsPrintable() ) {
3544 # Get all headlines for numbering them and adding funky stuff like [edit]
3545 # links - this is for later, but we need the number of headlines right now
3547 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3549 # if there are fewer than 4 headlines in the article, do not show TOC
3550 # unless it's been explicitly enabled.
3551 $enoughToc = $this->mShowToc
&&
3552 (($numMatches >= 4) ||
$this->mForceTocPosition
);
3554 # Allow user to stipulate that a page should have a "new section"
3555 # link added via __NEWSECTIONLINK__
3556 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3557 $this->mOutput
->setNewSection( true );
3560 # Allow user to remove the "new section"
3561 # link via __NONEWSECTIONLINK__
3562 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3563 $this->mOutput
->hideNewSection( true );
3566 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3567 # override above conditions and always show TOC above first header
3568 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3569 $this->mShowToc
= true;
3573 # We need this to perform operations on the HTML
3574 $sk = $this->mOptions
->getSkin();
3580 # Ugh .. the TOC should have neat indentation levels which can be
3581 # passed to the skin functions. These are determined here
3585 $sublevelCount = array();
3586 $levelCount = array();
3592 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3593 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3594 $oldType = $this->mOutputType
;
3595 $this->setOutputType( self
::OT_WIKI
);
3596 $frame = $this->getPreprocessor()->newFrame();
3597 $root = $this->preprocessToDom( $origText );
3598 $node = $root->getFirstChild();
3602 foreach( $matches[3] as $headline ) {
3603 $isTemplate = false;
3605 $sectionIndex = false;
3607 $markerMatches = array();
3608 if (preg_match("/^$markerRegex/", $headline, $markerMatches)) {
3609 $serial = $markerMatches[1];
3610 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3611 $isTemplate = ($titleText != $baseTitleText);
3612 $headline = preg_replace("/^$markerRegex/", "", $headline);
3616 $prevlevel = $level;
3617 $prevtoclevel = $toclevel;
3619 $level = $matches[1][$headlineCount];
3621 if ( $level > $prevlevel ) {
3622 # Increase TOC level
3624 $sublevelCount[$toclevel] = 0;
3625 if( $toclevel<$wgMaxTocLevel ) {
3626 $prevtoclevel = $toclevel;
3627 $toc .= $sk->tocIndent();
3631 elseif ( $level < $prevlevel && $toclevel > 1 ) {
3632 # Decrease TOC level, find level to jump to
3634 for ($i = $toclevel; $i > 0; $i--) {
3635 if ( $levelCount[$i] == $level ) {
3636 # Found last matching level
3640 elseif ( $levelCount[$i] < $level ) {
3641 # Found first matching level below current level
3646 if( $i == 0 ) $toclevel = 1;
3647 if( $toclevel<$wgMaxTocLevel ) {
3648 if($prevtoclevel < $wgMaxTocLevel) {
3649 # Unindent only if the previous toc level was shown :p
3650 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3651 $prevtoclevel = $toclevel;
3653 $toc .= $sk->tocLineEnd();
3658 # No change in level, end TOC line
3659 if( $toclevel<$wgMaxTocLevel ) {
3660 $toc .= $sk->tocLineEnd();
3664 $levelCount[$toclevel] = $level;
3666 # count number of headlines for each level
3667 @$sublevelCount[$toclevel]++
;
3669 for( $i = 1; $i <= $toclevel; $i++
) {
3670 if( !empty( $sublevelCount[$i] ) ) {
3674 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3679 # The safe header is a version of the header text safe to use for links
3680 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3681 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3683 # Remove link placeholders by the link text.
3684 # <!--LINK number-->
3686 # link text with suffix
3687 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3689 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3690 $tocline = preg_replace(
3691 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3695 $tocline = trim( $tocline );
3697 # For the anchor, strip out HTML-y stuff period
3698 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3699 $safeHeadline = preg_replace( '/[ _]+/', ' ', $safeHeadline );
3700 $safeHeadline = trim( $safeHeadline );
3702 # Save headline for section edit hint before it's escaped
3703 $headlineHint = $safeHeadline;
3705 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
3706 # For reverse compatibility, provide an id that's
3707 # HTML4-compatible, like we used to.
3709 # It may be worth noting, academically, that it's possible for
3710 # the legacy anchor to conflict with a non-legacy headline
3711 # anchor on the page. In this case likely the "correct" thing
3712 # would be to either drop the legacy anchors or make sure
3713 # they're numbered first. However, this would require people
3714 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3715 # manually, so let's not bother worrying about it.
3716 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
3717 array( 'noninitial', 'legacy' ) );
3718 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3720 if ( $legacyHeadline == $safeHeadline ) {
3721 # No reason to have both (in fact, we can't)
3722 $legacyHeadline = false;
3725 $legacyHeadline = false;
3726 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
3730 # HTML names must be case-insensitively unique (bug 10721). FIXME:
3731 # Does this apply to Unicode characters? Because we aren't
3732 # handling those here.
3733 $arrayKey = strtolower( $safeHeadline );
3734 if ( $legacyHeadline === false ) {
3735 $legacyArrayKey = false;
3737 $legacyArrayKey = strtolower( $legacyHeadline );
3740 # count how many in assoc. array so we can track dupes in anchors
3741 if ( isset( $refers[$arrayKey] ) ) {
3742 $refers[$arrayKey]++
;
3744 $refers[$arrayKey] = 1;
3746 if ( isset( $refers[$legacyArrayKey] ) ) {
3747 $refers[$legacyArrayKey]++
;
3749 $refers[$legacyArrayKey] = 1;
3752 # Don't number the heading if it is the only one (looks silly)
3753 if( $doNumberHeadings && count( $matches[3] ) > 1) {
3754 # the two are different if the line contains a link
3755 $headline = $numbering . ' ' . $headline;
3758 # Create the anchor for linking from the TOC to the section
3759 $anchor = $safeHeadline;
3760 $legacyAnchor = $legacyHeadline;
3761 if ( $refers[$arrayKey] > 1 ) {
3762 $anchor .= '_' . $refers[$arrayKey];
3764 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3765 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3767 if( $enoughToc && ( !isset($wgMaxTocLevel) ||
$toclevel<$wgMaxTocLevel ) ) {
3768 $toc .= $sk->tocLine($anchor, $tocline,
3769 $numbering, $toclevel, ($isTemplate ?
false : $sectionIndex));
3772 # Add the section to the section tree
3773 # Find the DOM node for this header
3774 while ( $node && !$isTemplate ) {
3775 if ( $node->getName() === 'h' ) {
3776 $bits = $node->splitHeading();
3777 if ( $bits['i'] == $sectionIndex )
3780 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
3781 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
3782 $node = $node->getNextSibling();
3785 'toclevel' => $toclevel,
3788 'number' => $numbering,
3789 'index' => ($isTemplate ?
'T-' : '' ) . $sectionIndex,
3790 'fromtitle' => $titleText,
3791 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
3792 'anchor' => $anchor,
3795 # give headline the correct <h#> tag
3796 if( $showEditLink && $sectionIndex !== false ) {
3798 # Put a T flag in the section identifier, to indicate to extractSections()
3799 # that sections inside <includeonly> should be counted.
3800 $editlink = $sk->doEditSectionLink(Title
::newFromText( $titleText ), "T-$sectionIndex");
3802 $editlink = $sk->doEditSectionLink($this->mTitle
, $sectionIndex, $headlineHint);
3807 $head[$headlineCount] = $sk->makeHeadline( $level,
3808 $matches['attrib'][$headlineCount], $anchor, $headline,
3809 $editlink, $legacyAnchor );
3814 $this->setOutputType( $oldType );
3816 # Never ever show TOC if no headers
3817 if( $numVisible < 1 ) {
3822 if( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3823 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3825 $toc = $sk->tocList( $toc );
3826 $this->mOutput
->setTOCHTML( $toc );
3830 $this->mOutput
->setSections( $tocraw );
3833 # split up and insert constructed headlines
3835 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3838 foreach( $blocks as $block ) {
3839 if( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3840 # This is the [edit] link that appears for the top block of text when
3841 # section editing is enabled
3843 # Disabled because it broke block formatting
3844 # For example, a bullet point in the top line
3845 # $full .= $sk->editSectionLink(0);
3848 if( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3849 # Top anchor now in skin
3853 if( !empty( $head[$i] ) ) {
3858 if( $this->mForceTocPosition
) {
3859 return str_replace( '<!--MWTOC-->', $toc, $full );
3866 * Merge $tree2 into $tree1 by replacing the section with index
3867 * $section in $tree1 and its descendants with the sections in $tree2.
3868 * Note that in the returned section tree, only the 'index' and
3869 * 'byteoffset' fields are guaranteed to be correct.
3870 * @param $tree1 array Section tree from ParserOutput::getSectons()
3871 * @param $tree2 array Section tree
3872 * @param $section int Section index
3873 * @param $title Title Title both section trees come from
3874 * @param $len2 int Length of the original wikitext for $tree2
3875 * @return array Merged section tree
3877 public static function mergeSectionTrees( $tree1, $tree2, $section, $title, $len2 ) {
3880 $targetLevel = false;
3884 $numbering = array( 0 );
3885 $titletext = $title->getPrefixedDBkey();
3886 foreach ( $tree1 as $s ) {
3887 if ( $targetLevel !== false ) {
3888 if ( $s['level'] <= $targetLevel )
3889 // We've skipped enough
3890 $targetLevel = false;
3894 if ( $s['index'] != $section ||
3895 $s['fromtitle'] != $titletext ) {
3896 self
::incrementNumbering( $numbering,
3897 $s['toclevel'], $lastLevel );
3899 // Rewrite index, byteoffset and number
3900 if ( $s['fromtitle'] == $titletext ) {
3901 $s['index'] = $nextIndex++
;
3903 $s['byteoffset'] +
= $len2;
3905 $s['number'] = implode( '.', array_map(
3906 array( $wgContLang, 'formatnum' ),
3908 $lastLevel = $s['toclevel'];
3911 // We're at $section
3912 // Insert sections from $tree2 here
3913 foreach ( $tree2 as $s2 ) {
3914 // Rewrite the fields in $s2
3915 // before inserting it
3916 $s2['toclevel'] +
= $s['toclevel'] - 1;
3917 $s2['level'] +
= $s['level'] - 1;
3918 $s2['index'] = $nextIndex++
;
3919 $s2['byteoffset'] +
= $s['byteoffset'];
3921 self
::incrementNumbering( $numbering,
3922 $s2['toclevel'], $lastLevel );
3923 $s2['number'] = implode( '.', array_map(
3924 array( $wgContLang, 'formatnum' ),
3926 $lastLevel = $s2['toclevel'];
3929 // Skip all descendants of $section in $tree1
3930 $targetLevel = $s['level'];
3938 * Increment a section number. Helper function for mergeSectionTrees()
3939 * @param $number array Array representing a section number
3940 * @param $level int Current TOC level (depth)
3941 * @param $lastLevel int Level of previous TOC entry
3943 private static function incrementNumbering( &$number, $level, $lastLevel ) {
3944 if ( $level > $lastLevel )
3945 $number[$level - 1] = 1;
3946 else if ( $level < $lastLevel ) {
3947 foreach ( $number as $key => $unused )
3948 if ( $key >= $level )
3949 unset( $number[$key] );
3950 $number[$level - 1]++
;
3952 $number[$level - 1]++
;
3956 * Transform wiki markup when saving a page by doing \r\n -> \n
3957 * conversion, substitting signatures, {{subst:}} templates, etc.
3959 * @param string $text the text to transform
3960 * @param Title &$title the Title object for the current article
3961 * @param User $user the User object describing the current user
3962 * @param ParserOptions $options parsing options
3963 * @param bool $clearState whether to clear the parser state first
3964 * @return string the altered wiki markup
3967 function preSaveTransform( $text, Title
$title, $user, $options, $clearState = true ) {
3968 $this->mOptions
= $options;
3969 $this->setTitle( $title );
3970 $this->setOutputType( self
::OT_WIKI
);
3972 if ( $clearState ) {
3973 $this->clearState();
3979 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
3980 $text = $this->pstPass2( $text, $user );
3981 $text = $this->mStripState
->unstripBoth( $text );
3986 * Pre-save transform helper function
3989 function pstPass2( $text, $user ) {
3990 global $wgContLang, $wgLocaltimezone;
3992 /* Note: This is the timestamp saved as hardcoded wikitext to
3993 * the database, we use $wgContLang here in order to give
3994 * everyone the same signature and use the default one rather
3995 * than the one selected in each user's preferences.
3997 * (see also bug 12815)
3999 $ts = $this->mOptions
->getTimestamp();
4000 if ( isset( $wgLocaltimezone ) ) {
4001 $tz = $wgLocaltimezone;
4003 $tz = date_default_timezone_get();
4006 $unixts = wfTimestamp( TS_UNIX
, $ts );
4007 $oldtz = date_default_timezone_get();
4008 date_default_timezone_set( $tz );
4009 $ts = date( 'YmdHis', $unixts );
4010 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4012 /* Allow translation of timezones trough wiki. date() can return
4013 * whatever crap the system uses, localised or not, so we cannot
4014 * ship premade translations.
4016 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4017 $value = wfMsgForContent( $key );
4018 if ( !wfEmptyMsg( $key, $value ) ) $tzMsg = $value;
4020 date_default_timezone_set( $oldtz );
4022 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4024 # Variable replacement
4025 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4026 $text = $this->replaceVariables( $text );
4029 $sigText = $this->getUserSig( $user );
4030 $text = strtr( $text, array(
4032 '~~~~' => "$sigText $d",
4036 # Links of the form [[|<blah>]] or [[<blah>|]] perform pipe tricks
4037 # Note this only allows the # in the position it works.
4038 global $wgLegalTitleChars;
4039 $pipeTrickRe = "/\[\[(?:(\\|)([$wgLegalTitleChars]+)|([#$wgLegalTitleChars]+)\\|)\]\]/";
4040 $text = preg_replace_callback( $pipeTrickRe, array( $this, 'pstPipeTrickCallback' ), $text );
4042 # Trim trailing whitespace
4043 $text = rtrim( $text );
4049 * Called from pstPass2 to perform the pipe trick on links.
4050 * Original was either [[|text]] or [[link|]]
4052 * @param Array ("|" or "", text, link) $m
4054 function pstPipeTrickCallback( $m )
4056 if( $m[1] ) { # [[|<blah>]]
4058 $link = $this->getPipeTrickLink( $text );
4059 } else { # [[<blah>|]]
4061 $text = $this->getPipeTrickText( $link );
4064 return $link === $text ?
"[[$link]]" : "[[$link|$text]]";
4068 * Fetch the user's signature text, if any, and normalize to
4069 * validated, ready-to-insert wikitext.
4070 * If you have pre-fetched the nickname or the fancySig option, you can
4071 * specify them here to save a database query.
4076 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4077 global $wgMaxSigChars;
4079 $username = $user->getName();
4081 // If not given, retrieve from the user object.
4082 if ( $nickname === false )
4083 $nickname = $user->getOption( 'nickname' );
4085 if ( is_null( $fancySig ) )
4086 $fancySig = $user->getBoolOption( 'fancysig' );
4088 $nickname = $nickname == null ?
$username : $nickname;
4090 if( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4091 $nickname = $username;
4092 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4093 } elseif( $fancySig !== false ) {
4094 # Sig. might contain markup; validate this
4095 if( $this->validateSig( $nickname ) !== false ) {
4096 # Validated; clean up (if needed) and return it
4097 return $this->cleanSig( $nickname, true );
4099 # Failed to validate; fall back to the default
4100 $nickname = $username;
4101 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4105 // Make sure nickname doesnt get a sig in a sig
4106 $nickname = $this->cleanSigInSig( $nickname );
4108 # If we're still here, make it a link to the user page
4109 $userText = wfEscapeWikiText( $username );
4110 $nickText = wfEscapeWikiText( $nickname );
4111 if ( $user->isAnon() ) {
4112 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4114 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4119 * Check that the user's signature contains no bad XML
4121 * @param string $text
4122 * @return mixed An expanded string, or false if invalid.
4124 function validateSig( $text ) {
4125 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4129 * Clean up signature text
4131 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4132 * 2) Substitute all transclusions
4134 * @param string $text
4135 * @param $parsing Whether we're cleaning (preferences save) or parsing
4136 * @return string Signature text
4138 function cleanSig( $text, $parsing = false ) {
4141 $this->clearState();
4142 $this->setTitle( $wgTitle );
4143 $this->mOptions
= new ParserOptions
;
4144 $this->setOutputType
= self
::OT_PREPROCESS
;
4147 # Option to disable this feature
4148 if ( !$this->mOptions
->getCleanSignatures() ) {
4152 # FIXME: regex doesn't respect extension tags or nowiki
4153 # => Move this logic to braceSubstitution()
4154 $substWord = MagicWord
::get( 'subst' );
4155 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4156 $substText = '{{' . $substWord->getSynonym( 0 );
4158 $text = preg_replace( $substRegex, $substText, $text );
4159 $text = $this->cleanSigInSig( $text );
4160 $dom = $this->preprocessToDom( $text );
4161 $frame = $this->getPreprocessor()->newFrame();
4162 $text = $frame->expand( $dom );
4165 $text = $this->mStripState
->unstripBoth( $text );
4172 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4173 * @param string $text
4174 * @return string Signature text with /~{3,5}/ removed
4176 function cleanSigInSig( $text ) {
4177 $text = preg_replace( '/~{3,5}/', '', $text );
4182 * Set up some variables which are usually set up in parse()
4183 * so that an external function can call some class members with confidence
4186 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
4187 $this->setTitle( $title );
4188 $this->mOptions
= $options;
4189 $this->setOutputType( $outputType );
4190 if ( $clearState ) {
4191 $this->clearState();
4196 * Wrapper for preprocess()
4198 * @param string $text the text to preprocess
4199 * @param ParserOptions $options options
4203 function transformMsg( $text, $options ) {
4205 static $executing = false;
4207 # Guard against infinite recursion
4213 wfProfileIn(__METHOD__
);
4214 $text = $this->preprocess( $text, $wgTitle, $options );
4217 wfProfileOut(__METHOD__
);
4222 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4223 * The callback should have the following form:
4224 * function myParserHook( $text, $params, &$parser ) { ... }
4226 * Transform and return $text. Use $parser for any required context, e.g. use
4227 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4231 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
4232 * @param mixed $callback The callback function (and object) to use for the tag
4234 * @return The old value of the mTagHooks array associated with the hook
4236 function setHook( $tag, $callback ) {
4237 $tag = strtolower( $tag );
4238 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4239 $this->mTagHooks
[$tag] = $callback;
4240 if( !in_array( $tag, $this->mStripList
) ) {
4241 $this->mStripList
[] = $tag;
4247 /* An old work-around for bug 2257 - deprecated 2010-02-13 */
4248 function setTransparentTagHook( $tag, $callback ) {
4249 wfDeprecated( __METHOD__
);
4250 $tag = strtolower( $tag );
4251 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4252 $this->mTransparentTagHooks
[$tag] = $callback;
4258 * Remove all tag hooks
4260 function clearTagHooks() {
4261 $this->mTagHooks
= array();
4262 $this->mStripList
= $this->mDefaultStripList
;
4266 * Create a function, e.g. {{sum:1|2|3}}
4267 * The callback function should have the form:
4268 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4270 * Or with SFH_OBJECT_ARGS:
4271 * function myParserFunction( $parser, $frame, $args ) { ... }
4273 * The callback may either return the text result of the function, or an array with the text
4274 * in element 0, and a number of flags in the other elements. The names of the flags are
4275 * specified in the keys. Valid flags are:
4276 * found The text returned is valid, stop processing the template. This
4278 * nowiki Wiki markup in the return value should be escaped
4279 * isHTML The returned text is HTML, armour it against wikitext transformation
4283 * @param string $id The magic word ID
4284 * @param mixed $callback The callback function (and object) to use
4285 * @param integer $flags a combination of the following flags:
4286 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4288 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4289 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4290 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4291 * the arguments, and to control the way they are expanded.
4293 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4294 * arguments, for instance:
4295 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4297 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4298 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4299 * working if/when this is changed.
4301 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4304 * Please read the documentation in includes/parser/Preprocessor.php for more information
4305 * about the methods available in PPFrame and PPNode.
4307 * @return The old callback function for this name, if any
4309 function setFunctionHook( $id, $callback, $flags = 0 ) {
4312 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4313 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4315 # Add to function cache
4316 $mw = MagicWord
::get( $id );
4318 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4320 $synonyms = $mw->getSynonyms();
4321 $sensitive = intval( $mw->isCaseSensitive() );
4323 foreach ( $synonyms as $syn ) {
4325 if ( !$sensitive ) {
4326 $syn = $wgContLang->lc( $syn );
4329 if ( !( $flags & SFH_NO_HASH
) ) {
4332 # Remove trailing colon
4333 if ( substr( $syn, -1, 1 ) === ':' ) {
4334 $syn = substr( $syn, 0, -1 );
4336 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4342 * Get all registered function hook identifiers
4346 function getFunctionHooks() {
4347 return array_keys( $this->mFunctionHooks
);
4351 * Create a tag function, e.g. <test>some stuff</test>.
4352 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4353 * Unlike parser functions, their content is not preprocessed.
4355 function setFunctionTagHook( $tag, $callback, $flags ) {
4356 $tag = strtolower( $tag );
4357 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4358 $this->mFunctionTagHooks
[$tag] : null;
4359 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4361 if( !in_array( $tag, $this->mStripList
) ) {
4362 $this->mStripList
[] = $tag;
4369 * FIXME: update documentation. makeLinkObj() is deprecated.
4370 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4371 * Placeholders created in Skin::makeLinkObj()
4372 * Returns an array of link CSS classes, indexed by PDBK.
4374 function replaceLinkHolders( &$text, $options = 0 ) {
4375 return $this->mLinkHolders
->replace( $text );
4379 * Replace <!--LINK--> link placeholders with plain text of links
4380 * (not HTML-formatted).
4381 * @param string $text
4384 function replaceLinkHoldersText( $text ) {
4385 return $this->mLinkHolders
->replaceText( $text );
4389 * Renders an image gallery from a text with one line per image.
4390 * text labels may be given by using |-style alternative text. E.g.
4391 * Image:one.jpg|The number "1"
4392 * Image:tree.jpg|A tree
4393 * given as text will return the HTML of a gallery with two images,
4394 * labeled 'The number "1"' and
4397 function renderImageGallery( $text, $params ) {
4398 $ig = new ImageGallery();
4399 $ig->setContextTitle( $this->mTitle
);
4400 $ig->setShowBytes( false );
4401 $ig->setShowFilename( false );
4402 $ig->setParser( $this );
4403 $ig->setHideBadImages();
4404 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4405 $ig->useSkin( $this->mOptions
->getSkin() );
4406 $ig->mRevisionId
= $this->mRevisionId
;
4408 if( isset( $params['caption'] ) ) {
4409 $caption = $params['caption'];
4410 $caption = htmlspecialchars( $caption );
4411 $caption = $this->replaceInternalLinks( $caption );
4412 $ig->setCaptionHtml( $caption );
4414 if( isset( $params['perrow'] ) ) {
4415 $ig->setPerRow( $params['perrow'] );
4417 if( isset( $params['widths'] ) ) {
4418 $ig->setWidths( $params['widths'] );
4420 if( isset( $params['heights'] ) ) {
4421 $ig->setHeights( $params['heights'] );
4424 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4426 $lines = StringUtils
::explode( "\n", $text );
4427 foreach ( $lines as $line ) {
4428 # match lines like these:
4429 # Image:someimage.jpg|This is some image
4431 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4433 if ( count( $matches ) == 0 ) {
4437 if ( strpos( $matches[0], '%' ) !== false )
4438 $matches[1] = urldecode( $matches[1] );
4439 $tp = Title
::newFromText( $matches[1]/*, NS_FILE*/ );
4441 if( is_null( $nt ) ) {
4442 # Bogus title. Ignore these so we don't bomb out later.
4445 if ( isset( $matches[3] ) ) {
4446 $label = $matches[3];
4451 $html = $this->recursiveTagParse( trim( $label ) );
4453 $ig->add( $nt, $html );
4455 # Only add real images (bug #5586)
4456 if ( $nt->getNamespace() == NS_FILE
) {
4457 $this->mOutput
->addImage( $nt->getDBkey() );
4460 return $ig->toHTML();
4463 function getImageParams( $handler ) {
4465 $handlerClass = get_class( $handler );
4469 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4470 // Initialise static lists
4471 static $internalParamNames = array(
4472 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4473 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4474 'bottom', 'text-bottom' ),
4475 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4476 'upright', 'border', 'link', 'alt' ),
4478 static $internalParamMap;
4479 if ( !$internalParamMap ) {
4480 $internalParamMap = array();
4481 foreach ( $internalParamNames as $type => $names ) {
4482 foreach ( $names as $name ) {
4483 $magicName = str_replace( '-', '_', "img_$name" );
4484 $internalParamMap[$magicName] = array( $type, $name );
4489 // Add handler params
4490 $paramMap = $internalParamMap;
4492 $handlerParamMap = $handler->getParamMap();
4493 foreach ( $handlerParamMap as $magic => $paramName ) {
4494 $paramMap[$magic] = array( 'handler', $paramName );
4497 $this->mImageParams
[$handlerClass] = $paramMap;
4498 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4500 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4504 * Parse image options text and use it to make an image
4505 * @param Title $title
4506 * @param string $options
4507 * @param LinkHolderArray $holders
4509 function makeImage( $title, $options, $holders = false ) {
4510 # Check if the options text is of the form "options|alt text"
4512 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4513 # * left no resizing, just left align. label is used for alt= only
4514 # * right same, but right aligned
4515 # * none same, but not aligned
4516 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4517 # * center center the image
4518 # * frame Keep original image size, no magnify-button.
4519 # * framed Same as "frame"
4520 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4521 # * upright reduce width for upright images, rounded to full __0 px
4522 # * border draw a 1px border around the image
4523 # * alt Text for HTML alt attribute (defaults to empty)
4524 # * link Set the target of the image link. Can be external, interwiki, or local
4525 # vertical-align values (no % or length right now):
4535 $parts = StringUtils
::explode( "|", $options );
4536 $sk = $this->mOptions
->getSkin();
4538 # Give extensions a chance to select the file revision for us
4539 $skip = $time = $descQuery = false;
4540 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4543 return $sk->link( $title );
4547 $imagename = $title->getDBkey();
4548 $file = wfFindFile( $title, array( 'time' => $time ) );
4550 $handler = $file ?
$file->getHandler() : false;
4552 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4554 # Process the input parameters
4556 $params = array( 'frame' => array(), 'handler' => array(),
4557 'horizAlign' => array(), 'vertAlign' => array() );
4558 foreach( $parts as $part ) {
4559 $part = trim( $part );
4560 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4562 if( isset( $paramMap[$magicName] ) ) {
4563 list( $type, $paramName ) = $paramMap[$magicName];
4565 // Special case; width and height come in one variable together
4566 if( $type === 'handler' && $paramName === 'width' ) {
4568 # (bug 13500) In both cases (width/height and width only),
4569 # permit trailing "px" for backward compatibility.
4570 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4571 $width = intval( $m[1] );
4572 $height = intval( $m[2] );
4573 if ( $handler->validateParam( 'width', $width ) ) {
4574 $params[$type]['width'] = $width;
4577 if ( $handler->validateParam( 'height', $height ) ) {
4578 $params[$type]['height'] = $height;
4581 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4582 $width = intval( $value );
4583 if ( $handler->validateParam( 'width', $width ) ) {
4584 $params[$type]['width'] = $width;
4587 } // else no validation -- bug 13436
4589 if ( $type === 'handler' ) {
4590 # Validate handler parameter
4591 $validated = $handler->validateParam( $paramName, $value );
4593 # Validate internal parameters
4594 switch( $paramName ) {
4597 // @todo Fixme: possibly check validity here for
4598 // manualthumb? downstream behavior seems odd with
4599 // missing manual thumbs.
4601 $value = $this->stripAltText( $value, $holders );
4604 $chars = self
::EXT_LINK_URL_CLASS
;
4605 $prots = $this->mUrlProtocols
;
4606 if ( $value === '' ) {
4607 $paramName = 'no-link';
4610 } elseif ( preg_match( "/^$prots/", $value ) ) {
4611 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4612 $paramName = 'link-url';
4613 $this->mOutput
->addExternalLink( $value );
4617 $linkTitle = Title
::newFromText( $value );
4619 $paramName = 'link-title';
4620 $value = $linkTitle;
4621 $this->mOutput
->addLink( $linkTitle );
4627 // Most other things appear to be empty or numeric...
4628 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4633 $params[$type][$paramName] = $value;
4637 if ( !$validated ) {
4642 # Process alignment parameters
4643 if ( $params['horizAlign'] ) {
4644 $params['frame']['align'] = key( $params['horizAlign'] );
4646 if ( $params['vertAlign'] ) {
4647 $params['frame']['valign'] = key( $params['vertAlign'] );
4650 $params['frame']['caption'] = $caption;
4652 # Will the image be presented in a frame, with the caption below?
4653 $imageIsFramed = isset( $params['frame']['frame'] ) ||
4654 isset( $params['frame']['framed'] ) ||
4655 isset( $params['frame']['thumbnail'] ) ||
4656 isset( $params['frame']['manualthumb'] );
4658 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4659 # came to also set the caption, ordinary text after the image -- which
4660 # makes no sense, because that just repeats the text multiple times in
4661 # screen readers. It *also* came to set the title attribute.
4663 # Now that we have an alt attribute, we should not set the alt text to
4664 # equal the caption: that's worse than useless, it just repeats the
4665 # text. This is the framed/thumbnail case. If there's no caption, we
4666 # use the unnamed parameter for alt text as well, just for the time be-
4667 # ing, if the unnamed param is set and the alt param is not.
4669 # For the future, we need to figure out if we want to tweak this more,
4670 # e.g., introducing a title= parameter for the title; ignoring the un-
4671 # named parameter entirely for images without a caption; adding an ex-
4672 # plicit caption= parameter and preserving the old magic unnamed para-
4674 if ( $imageIsFramed ) { # Framed image
4675 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
4676 # No caption or alt text, add the filename as the alt text so
4677 # that screen readers at least get some description of the image
4678 $params['frame']['alt'] = $title->getText();
4680 # Do not set $params['frame']['title'] because tooltips don't make sense
4682 } else { # Inline image
4683 if ( !isset( $params['frame']['alt'] ) ) {
4684 # No alt text, use the "caption" for the alt text
4685 if ( $caption !== '') {
4686 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
4688 # No caption, fall back to using the filename for the
4690 $params['frame']['alt'] = $title->getText();
4693 # Use the "caption" for the tooltip text
4694 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4697 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4699 # Linker does the rest
4700 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4702 # Give the handler a chance to modify the parser object
4704 $handler->parserTransformHook( $this, $file );
4710 protected function stripAltText( $caption, $holders ) {
4711 # Strip bad stuff out of the title (tooltip). We can't just use
4712 # replaceLinkHoldersText() here, because if this function is called
4713 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4715 $tooltip = $holders->replaceText( $caption );
4717 $tooltip = $this->replaceLinkHoldersText( $caption );
4720 # make sure there are no placeholders in thumbnail attributes
4721 # that are later expanded to html- so expand them now and
4723 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
4724 $tooltip = Sanitizer
::stripAllTags( $tooltip );
4730 * Set a flag in the output object indicating that the content is dynamic and
4731 * shouldn't be cached.
4733 function disableCache() {
4734 wfDebug( "Parser output marked as uncacheable.\n" );
4735 $this->mOutput
->mCacheTime
= -1;
4739 * Callback from the Sanitizer for expanding items found in HTML attribute
4740 * values, so they can be safely tested and escaped.
4741 * @param string $text
4742 * @param PPFrame $frame
4746 function attributeStripCallback( &$text, $frame = false ) {
4747 $text = $this->replaceVariables( $text, $frame );
4748 $text = $this->mStripState
->unstripBoth( $text );
4757 function Title( $x = null ) { return wfSetVar( $this->mTitle
, $x ); }
4758 function Options( $x = null ) { return wfSetVar( $this->mOptions
, $x ); }
4759 function OutputType( $x = null ) { return wfSetVar( $this->mOutputType
, $x ); }
4765 function getTags() { return array_merge( array_keys($this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) ); }
4770 * Break wikitext input into sections, and either pull or replace
4771 * some particular section's text.
4773 * External callers should use the getSection and replaceSection methods.
4775 * @param string $text Page wikitext
4776 * @param string $section A section identifier string of the form:
4777 * <flag1> - <flag2> - ... - <section number>
4779 * Currently the only recognised flag is "T", which means the target section number
4780 * was derived during a template inclusion parse, in other words this is a template
4781 * section edit link. If no flags are given, it was an ordinary section edit link.
4782 * This flag is required to avoid a section numbering mismatch when a section is
4783 * enclosed by <includeonly> (bug 6563).
4785 * The section number 0 pulls the text before the first heading; other numbers will
4786 * pull the given section along with its lower-level subsections. If the section is
4787 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4789 * @param string $mode One of "get" or "replace"
4790 * @param string $newText Replacement text for section data.
4791 * @return string for "get", the extracted section text.
4792 * for "replace", the whole page with the section replaced.
4794 private function extractSections( $text, $section, $mode, $newText='' ) {
4796 $this->clearState();
4797 $this->setTitle( $wgTitle ); // not generally used but removes an ugly failure mode
4798 $this->mOptions
= new ParserOptions
;
4799 $this->setOutputType( self
::OT_WIKI
);
4801 $frame = $this->getPreprocessor()->newFrame();
4803 // Process section extraction flags
4805 $sectionParts = explode( '-', $section );
4806 $sectionIndex = array_pop( $sectionParts );
4807 foreach ( $sectionParts as $part ) {
4808 if ( $part === 'T' ) {
4809 $flags |
= self
::PTD_FOR_INCLUSION
;
4812 // Preprocess the text
4813 $root = $this->preprocessToDom( $text, $flags );
4815 // <h> nodes indicate section breaks
4816 // They can only occur at the top level, so we can find them by iterating the root's children
4817 $node = $root->getFirstChild();
4819 // Find the target section
4820 if ( $sectionIndex == 0 ) {
4821 // Section zero doesn't nest, level=big
4822 $targetLevel = 1000;
4825 if ( $node->getName() === 'h' ) {
4826 $bits = $node->splitHeading();
4827 if ( $bits['i'] == $sectionIndex ) {
4828 $targetLevel = $bits['level'];
4832 if ( $mode === 'replace' ) {
4833 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4835 $node = $node->getNextSibling();
4841 if ( $mode === 'get' ) {
4848 // Find the end of the section, including nested sections
4850 if ( $node->getName() === 'h' ) {
4851 $bits = $node->splitHeading();
4852 $curLevel = $bits['level'];
4853 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4857 if ( $mode === 'get' ) {
4858 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4860 $node = $node->getNextSibling();
4863 // Write out the remainder (in replace mode only)
4864 if ( $mode === 'replace' ) {
4865 // Output the replacement text
4866 // Add two newlines on -- trailing whitespace in $newText is conventionally
4867 // stripped by the editor, so we need both newlines to restore the paragraph gap
4868 // Only add trailing whitespace if there is newText
4869 if($newText != "") {
4870 $outText .= $newText . "\n\n";
4874 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4875 $node = $node->getNextSibling();
4879 if ( is_string( $outText ) ) {
4880 // Re-insert stripped tags
4881 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4888 * This function returns the text of a section, specified by a number ($section).
4889 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4890 * the first section before any such heading (section 0).
4892 * If a section contains subsections, these are also returned.
4894 * @param string $text text to look in
4895 * @param string $section section identifier
4896 * @param string $deftext default to return if section is not found
4897 * @return string text of the requested section
4899 public function getSection( $text, $section, $deftext='' ) {
4900 return $this->extractSections( $text, $section, "get", $deftext );
4903 public function replaceSection( $oldtext, $section, $text ) {
4904 return $this->extractSections( $oldtext, $section, "replace", $text );
4908 * Get the timestamp associated with the current revision, adjusted for
4909 * the default server-local timestamp
4911 function getRevisionTimestamp() {
4912 if ( is_null( $this->mRevisionTimestamp
) ) {
4913 wfProfileIn( __METHOD__
);
4915 $dbr = wfGetDB( DB_SLAVE
);
4916 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4917 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4919 // Normalize timestamp to internal MW format for timezone processing.
4920 // This has the added side-effect of replacing a null value with
4921 // the current time, which gives us more sensible behavior for
4923 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4925 // The cryptic '' timezone parameter tells to use the site-default
4926 // timezone offset instead of the user settings.
4928 // Since this value will be saved into the parser cache, served
4929 // to other users, and potentially even used inside links and such,
4930 // it needs to be consistent for all visitors.
4931 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4933 wfProfileOut( __METHOD__
);
4935 return $this->mRevisionTimestamp
;
4939 * Get the name of the user that edited the last revision
4941 function getRevisionUser() {
4942 // if this template is subst: the revision id will be blank,
4943 // so just use the current user's name
4944 if( $this->mRevisionId
) {
4945 $revision = Revision
::newFromId( $this->mRevisionId
);
4946 $revuser = $revision->getUserText();
4949 $revuser = $wgUser->getName();
4955 * Mutator for $mDefaultSort
4957 * @param $sort New value
4959 public function setDefaultSort( $sort ) {
4960 $this->mDefaultSort
= $sort;
4964 * Accessor for $mDefaultSort
4965 * Will use the title/prefixed title if none is set
4969 public function getDefaultSort() {
4970 global $wgCategoryPrefixedDefaultSortkey;
4971 if( $this->mDefaultSort
!== false ) {
4972 return $this->mDefaultSort
;
4973 } elseif ($this->mTitle
->getNamespace() == NS_CATEGORY ||
4974 !$wgCategoryPrefixedDefaultSortkey) {
4975 return $this->mTitle
->getText();
4977 return $this->mTitle
->getPrefixedText();
4982 * Accessor for $mDefaultSort
4983 * Unlike getDefaultSort(), will return false if none is set
4985 * @return string or false
4987 public function getCustomDefaultSort() {
4988 return $this->mDefaultSort
;
4992 * Try to guess the section anchor name based on a wikitext fragment
4993 * presumably extracted from a heading, for example "Header" from
4996 public function guessSectionNameFromWikiText( $text ) {
4997 # Strip out wikitext links(they break the anchor)
4998 $text = $this->stripSectionName( $text );
4999 $headline = Sanitizer
::decodeCharReferences( $text );
5001 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
5002 $headline = trim( $headline );
5003 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
5004 $replacearray = array(
5009 array_keys( $replacearray ),
5010 array_values( $replacearray ),
5015 * Strips a text string of wikitext for use in a section anchor
5017 * Accepts a text string and then removes all wikitext from the
5018 * string and leaves only the resultant text (i.e. the result of
5019 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5020 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5021 * to create valid section anchors by mimicing the output of the
5022 * parser when headings are parsed.
5024 * @param $text string Text string to be stripped of wikitext
5025 * for use in a Section anchor
5026 * @return Filtered text string
5028 public function stripSectionName( $text ) {
5029 # Strip internal link markup
5030 $text = preg_replace('/\[\[:?([^[|]+)\|([^[]+)\]\]/','$2',$text);
5031 $text = preg_replace('/\[\[:?([^[]+)\|?\]\]/','$1',$text);
5033 # Strip external link markup (FIXME: Not Tolerant to blank link text
5034 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5035 # on how many empty links there are on the page - need to figure that out.
5036 $text = preg_replace('/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/','$2',$text);
5038 # Parse wikitext quotes (italics & bold)
5039 $text = $this->doQuotes($text);
5042 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5046 function srvus( $text ) {
5047 return $this->testSrvus( $text, $this->mOutputType
);
5051 * strip/replaceVariables/unstrip for preprocessor regression testing
5053 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
5054 $this->clearState();
5055 if ( ! ( $title instanceof Title
) ) {
5056 $title = Title
::newFromText( $title );
5058 $this->mTitle
= $title;
5059 $this->mOptions
= $options;
5060 $this->setOutputType( $outputType );
5061 $text = $this->replaceVariables( $text );
5062 $text = $this->mStripState
->unstripBoth( $text );
5063 $text = Sanitizer
::removeHTMLtags( $text );
5067 function testPst( $text, $title, $options ) {
5069 if ( ! ( $title instanceof Title
) ) {
5070 $title = Title
::newFromText( $title );
5072 return $this->preSaveTransform( $text, $title, $wgUser, $options );
5075 function testPreprocess( $text, $title, $options ) {
5076 if ( ! ( $title instanceof Title
) ) {
5077 $title = Title
::newFromText( $title );
5079 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5082 function markerSkipCallback( $s, $callback ) {
5085 while ( $i < strlen( $s ) ) {
5086 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5087 if ( $markerStart === false ) {
5088 $out .= call_user_func( $callback, substr( $s, $i ) );
5091 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5092 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5093 if ( $markerEnd === false ) {
5094 $out .= substr( $s, $markerStart );
5097 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5098 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5106 function serialiseHalfParsedText( $text ) {
5108 $data['text'] = $text;
5110 // First, find all strip markers, and store their
5111 // data in an array.
5112 $stripState = new StripState
;
5114 while( ( $start_pos = strpos( $text, $this->mUniqPrefix
, $pos ) ) && ( $end_pos = strpos( $text, self
::MARKER_SUFFIX
, $pos ) ) ) {
5115 $end_pos +
= strlen( self
::MARKER_SUFFIX
);
5116 $marker = substr( $text, $start_pos, $end_pos-$start_pos );
5118 if ( !empty( $this->mStripState
->general
->data
[$marker] ) ) {
5119 $replaceArray = $stripState->general
;
5120 $stripText = $this->mStripState
->general
->data
[$marker];
5121 } elseif ( !empty( $this->mStripState
->nowiki
->data
[$marker] ) ) {
5122 $replaceArray = $stripState->nowiki
;
5123 $stripText = $this->mStripState
->nowiki
->data
[$marker];
5125 throw new MWException( "Hanging strip marker: '$marker'." );
5128 $replaceArray->setPair( $marker, $stripText );
5131 $data['stripstate'] = $stripState;
5133 // Now, find all of our links, and store THEIR
5134 // data in an array! :)
5135 $links = array( 'internal' => array(), 'interwiki' => array() );
5139 while( ( $start_pos = strpos( $text, '<!--LINK ', $pos ) ) ) {
5140 list( $ns, $trail ) = explode( ':', substr( $text, $start_pos +
strlen( '<!--LINK ' ) ), 2 );
5143 if (empty( $links['internal'][$ns] )) {
5144 $links['internal'][$ns] = array();
5147 $key = trim( substr( $trail, 0, strpos( $trail, '-->' ) ) );
5148 $links['internal'][$ns][] = $this->mLinkHolders
->internals
[$ns][$key];
5149 $pos = $start_pos +
strlen( "<!--LINK $ns:$key-->" );
5155 while( ( $start_pos = strpos( $text, '<!--IWLINK ', $pos ) ) ) {
5156 $data = substr( $text, $start_pos );
5157 $key = trim( substr( $data, 0, strpos( $data, '-->' ) ) );
5158 $links['interwiki'][] = $this->mLinkHolders
->interwiki
[$key];
5159 $pos = $start_pos +
strlen( "<!--IWLINK $key-->" );
5162 $data['linkholder'] = $links;
5167 function unserialiseHalfParsedText( $data, $intPrefix = null /* Unique identifying prefix */ ) {
5169 $intPrefix = $this->getRandomString();
5171 // First, extract the strip state.
5172 $stripState = $data['stripstate'];
5173 $this->mStripState
->general
->merge( $stripState->general
);
5174 $this->mStripState
->nowiki
->merge( $stripState->nowiki
);
5176 // Now, extract the text, and renumber links
5177 $text = $data['text'];
5178 $links = $data['linkholder'];
5181 foreach( $links['internal'] as $ns => $nsLinks ) {
5182 foreach( $nsLinks as $key => $entry ) {
5183 $newKey = $intPrefix . '-' . $key;
5184 $this->mLinkHolders
->internals
[$ns][$newKey] = $entry;
5186 $text = str_replace( "<!--LINK $ns:$key-->", "<!--LINK $ns:$newKey-->", $text );
5191 foreach( $links['interwiki'] as $key => $entry ) {
5192 $newKey = "$intPrefix-$key";
5193 $this->mLinkHolders
->interwikis
[$newKey] = $entry;
5195 $text = str_replace( "<!--IWLINK $key-->", "<!--IWLINK $newKey-->", $text );
5198 // Should be good to go.
5204 * @todo document, briefly.
5208 var $general, $nowiki;
5210 function __construct() {
5211 $this->general
= new ReplacementArray
;
5212 $this->nowiki
= new ReplacementArray
;
5215 function unstripGeneral( $text ) {
5216 wfProfileIn( __METHOD__
);
5219 $text = $this->general
->replace( $text );
5220 } while ( $text !== $oldText );
5221 wfProfileOut( __METHOD__
);
5225 function unstripNoWiki( $text ) {
5226 wfProfileIn( __METHOD__
);
5229 $text = $this->nowiki
->replace( $text );
5230 } while ( $text !== $oldText );
5231 wfProfileOut( __METHOD__
);
5235 function unstripBoth( $text ) {
5236 wfProfileIn( __METHOD__
);
5239 $text = $this->general
->replace( $text );
5240 $text = $this->nowiki
->replace( $text );
5241 } while ( $text !== $oldText );
5242 wfProfileOut( __METHOD__
);
5248 * @todo document, briefly.
5251 class OnlyIncludeReplacer
{
5254 function replace( $matches ) {
5255 if ( substr( $matches[1], -1 ) === "\n" ) {
5256 $this->output
.= substr( $matches[1], 0, -1 );
5258 $this->output
.= $matches[1];