3 * @defgroup Parser Parser
7 * File for Parser and related classes
12 * PHP Parser - Processes wiki markup (which uses a more user-friendly
13 * syntax, such as "[[link]]" for making links), and provides a one-way
14 * transformation of that wiki markup it into XHTML output / markup
15 * (which in turn the browser understands, and can display).
18 * There are five main entry points into the Parser class:
20 * produces HTML output
22 * produces altered wiki markup.
24 * removes HTML comments and expands templates
26 * Cleans a signature before saving it to preferences
28 * Extracts sections from an article for section editing
30 * Removes <noinclude> sections, and <includeonly> tags.
33 * objects: $wgLang, $wgContLang
35 * NOT $wgArticle, $wgUser or $wgTitle. Keep them away!
38 * $wgUseTex*, $wgUseDynamicDates*, $wgInterwikiMagic*,
39 * $wgNamespacesWithSubpages, $wgAllowExternalImages*,
40 * $wgLocaltimezone, $wgAllowSpecialInclusion*,
43 * * only within ParserOptions
50 * Update this version number when the ParserOutput format
51 * changes in an incompatible way, so the parser cache
52 * can automatically discard old data.
54 const VERSION
= '1.6.4';
56 # Flags for Parser::setFunctionHook
57 # Also available as global constants from Defines.php
58 const SFH_NO_HASH
= 1;
59 const SFH_OBJECT_ARGS
= 2;
61 # Constants needed for external link processing
62 # Everything except bracket, space, or control characters
63 const EXT_LINK_URL_CLASS
= '[^][<>"\\x00-\\x20\\x7F]';
64 const EXT_IMAGE_REGEX
= '/^(http:\/\/|https:\/\/)([^][<>"\\x00-\\x20\\x7F]+)
65 \\/([A-Za-z0-9_.,~%\\-+&;#*?!=()@\\x80-\\xFF]+)\\.((?i)gif|png|jpg|jpeg)$/Sx';
67 # State constants for the definition list colon extraction
68 const COLON_STATE_TEXT
= 0;
69 const COLON_STATE_TAG
= 1;
70 const COLON_STATE_TAGSTART
= 2;
71 const COLON_STATE_CLOSETAG
= 3;
72 const COLON_STATE_TAGSLASH
= 4;
73 const COLON_STATE_COMMENT
= 5;
74 const COLON_STATE_COMMENTDASH
= 6;
75 const COLON_STATE_COMMENTDASHDASH
= 7;
77 # Flags for preprocessToDom
78 const PTD_FOR_INCLUSION
= 1;
80 # Allowed values for $this->mOutputType
81 # Parameter to startExternalParse().
82 const OT_HTML
= 1; # like parse()
83 const OT_WIKI
= 2; # like preSaveTransform()
84 const OT_PREPROCESS
= 3; # like preprocess()
86 const OT_PLAIN
= 4; # like extractSections() - portions of the original are returned unchanged.
88 # Marker Suffix needs to be accessible staticly.
89 const MARKER_SUFFIX
= "-QINU\x7f";
92 var $mTagHooks, $mTransparentTagHooks, $mFunctionHooks, $mFunctionSynonyms, $mVariables;
93 var $mSubstWords, $mImageParams, $mImageParamsMagicArray, $mStripList, $mMarkerIndex;
94 var $mPreprocessor, $mExtLinkBracketedRegex, $mUrlProtocols, $mDefaultStripList;
95 var $mVarCache, $mConf, $mFunctionTagHooks;
98 # Cleared with clearState():
99 var $mOutput, $mAutonumber, $mDTopen, $mStripState;
100 var $mIncludeCount, $mArgStack, $mLastSection, $mInPre;
101 var $mLinkHolders, $mLinkID;
102 var $mIncludeSizes, $mPPNodeCount, $mDefaultSort;
103 var $mTplExpandCache; # empty-frame expansion cache
104 var $mTplRedirCache, $mTplDomCache, $mHeadings, $mDoubleUnderscores;
105 var $mExpensiveFunctionCount; # number of expensive parser function calls
108 # These are variables reset at least once per parse regardless of $clearState
109 var $mOptions; # ParserOptions object
110 var $mTitle; # Title context, used for self-link rendering and similar things
111 var $mOutputType; # Output type, one of the OT_xxx constants
112 var $ot; # Shortcut alias, see setOutputType()
113 var $mRevisionId; # ID to display in {{REVISIONID}} tags
114 var $mRevisionTimestamp; # The timestamp of the specified revision ID
115 var $mRevIdForTs; # The revision ID which was used to fetch the timestamp
122 function __construct( $conf = array() ) {
123 $this->mConf
= $conf;
124 $this->mTagHooks
= array();
125 $this->mTransparentTagHooks
= array();
126 $this->mFunctionHooks
= array();
127 $this->mFunctionTagHooks
= array();
128 $this->mFunctionSynonyms
= array( 0 => array(), 1 => array() );
129 $this->mDefaultStripList
= $this->mStripList
= array();
130 $this->mUrlProtocols
= wfUrlProtocols();
131 $this->mExtLinkBracketedRegex
= '/\[(\b(' . wfUrlProtocols() . ')'.
132 '[^][<>"\\x00-\\x20\\x7F]+) *([^\]\\x00-\\x08\\x0a-\\x1F]*?)\]/S';
133 $this->mVarCache
= array();
134 if ( isset( $conf['preprocessorClass'] ) ) {
135 $this->mPreprocessorClass
= $conf['preprocessorClass'];
136 } elseif ( extension_loaded( 'domxml' ) ) {
137 # PECL extension that conflicts with the core DOM extension (bug 13770)
138 wfDebug( "Warning: you have the obsolete domxml extension for PHP. Please remove it!\n" );
139 $this->mPreprocessorClass
= 'Preprocessor_Hash';
140 } elseif ( extension_loaded( 'dom' ) ) {
141 $this->mPreprocessorClass
= 'Preprocessor_DOM';
143 $this->mPreprocessorClass
= 'Preprocessor_Hash';
145 $this->mMarkerIndex
= 0;
146 $this->mFirstCall
= true;
150 * Reduce memory usage to reduce the impact of circular references
152 function __destruct() {
153 if ( isset( $this->mLinkHolders
) ) {
154 $this->mLinkHolders
->__destruct();
156 foreach ( $this as $name => $value ) {
157 unset( $this->$name );
162 * Do various kinds of initialisation on the first call of the parser
164 function firstCallInit() {
165 if ( !$this->mFirstCall
) {
168 $this->mFirstCall
= false;
170 wfProfileIn( __METHOD__
);
172 CoreParserFunctions
::register( $this );
173 CoreTagHooks
::register( $this );
174 $this->initialiseVariables();
176 wfRunHooks( 'ParserFirstCallInit', array( &$this ) );
177 wfProfileOut( __METHOD__
);
185 function clearState() {
186 wfProfileIn( __METHOD__
);
187 if ( $this->mFirstCall
) {
188 $this->firstCallInit();
190 $this->mOutput
= new ParserOutput
;
191 $this->mAutonumber
= 0;
192 $this->mLastSection
= '';
193 $this->mDTopen
= false;
194 $this->mIncludeCount
= array();
195 $this->mStripState
= new StripState
;
196 $this->mArgStack
= false;
197 $this->mInPre
= false;
198 $this->mLinkHolders
= new LinkHolderArray( $this );
200 $this->mRevisionTimestamp
= $this->mRevisionId
= null;
201 $this->mVarCache
= array();
204 * Prefix for temporary replacement strings for the multipass parser.
205 * \x07 should never appear in input as it's disallowed in XML.
206 * Using it at the front also gives us a little extra robustness
207 * since it shouldn't match when butted up against identifier-like
210 * Must not consist of all title characters, or else it will change
211 * the behaviour of <nowiki> in a link.
213 # $this->mUniqPrefix = "\x07UNIQ" . Parser::getRandomString();
214 # Changed to \x7f to allow XML double-parsing -- TS
215 $this->mUniqPrefix
= "\x7fUNIQ" . self
::getRandomString();
218 # Clear these on every parse, bug 4549
219 $this->mTplExpandCache
= $this->mTplRedirCache
= $this->mTplDomCache
= array();
221 $this->mShowToc
= true;
222 $this->mForceTocPosition
= false;
223 $this->mIncludeSizes
= array(
227 $this->mPPNodeCount
= 0;
228 $this->mDefaultSort
= false;
229 $this->mHeadings
= array();
230 $this->mDoubleUnderscores
= array();
231 $this->mExpensiveFunctionCount
= 0;
234 if ( isset( $this->mPreprocessor
) && $this->mPreprocessor
->parser
!== $this ) {
235 $this->mPreprocessor
= null;
238 wfRunHooks( 'ParserClearState', array( &$this ) );
239 wfProfileOut( __METHOD__
);
243 * Convert wikitext to HTML
244 * Do not call this function recursively.
246 * @param $text String: text we want to parse
247 * @param $title A title object
248 * @param $options ParserOptions
249 * @param $linestart boolean
250 * @param $clearState boolean
251 * @param $revid Int: number to pass in {{REVISIONID}}
252 * @return ParserOutput a ParserOutput
254 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
256 * First pass--just handle <nowiki> sections, pass the rest off
257 * to internalParse() which does all the real work.
260 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang, $wgDisableLangConversion, $wgDisableTitleConversion;
261 $fname = __METHOD__
.'-' . wfGetCaller();
262 wfProfileIn( __METHOD__
);
263 wfProfileIn( $fname );
269 $this->mOptions
= $options;
270 $this->setTitle( $title ); # Page title has to be set for the pre-processor
272 $oldRevisionId = $this->mRevisionId
;
273 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
274 if ( $revid !== null ) {
275 $this->mRevisionId
= $revid;
276 $this->mRevisionTimestamp
= null;
278 $this->setOutputType( self
::OT_HTML
);
279 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
281 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
282 $text = $this->internalParse( $text );
284 $text = $this->mStripState
->unstripGeneral( $text );
286 # Clean up special characters, only run once, next-to-last before doBlockLevels
288 # french spaces, last one Guillemet-left
289 # only if there is something before the space
290 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
291 # french spaces, Guillemet-right
292 '/(\\302\\253) /' => '\\1 ',
293 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
295 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
297 $text = $this->doBlockLevels( $text, $linestart );
299 $this->replaceLinkHolders( $text );
302 * The page doesn't get language converted if
304 * b) Content isn't converted
305 * c) It's a conversion table
307 if ( !( $wgDisableLangConversion
308 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
309 ||
$this->mTitle
->isConversionTable() ) ) {
311 # The position of the convert() call should not be changed. it
312 # assumes that the links are all replaced and the only thing left
313 # is the <nowiki> mark.
315 $text = $wgContLang->convert( $text );
319 * A page get its title converted except:
320 * a) Language conversion is globally disabled
321 * b) Title convert is globally disabled
322 * c) The page is a redirect page
323 * d) User request with a "linkconvert" set to "no"
324 * e) A "nocontentconvert" magic word has been set
325 * f) A "notitleconvert" magic word has been set
326 * g) User sets "noconvertlink" in his/her preference
328 * Note that if a user tries to set a title in a conversion
329 * rule but content conversion was not done, then the parser
330 * won't pick it up. This is probably expected behavior.
332 if ( !( $wgDisableLangConversion
333 ||
$wgDisableTitleConversion
334 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
335 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
336 ||
$this->mOutput
->getDisplayTitle() !== false ) )
338 $convruletitle = $wgContLang->getConvRuleTitle();
339 if ( $convruletitle ) {
340 $this->mOutput
->setTitleText( $convruletitle );
342 $titleText = $wgContLang->convertTitle( $title );
343 $this->mOutput
->setTitleText( $titleText );
347 $text = $this->mStripState
->unstripNoWiki( $text );
349 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
351 //!JF Move to its own function
353 $uniq_prefix = $this->mUniqPrefix
;
355 $elements = array_keys( $this->mTransparentTagHooks
);
356 $text = self
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
358 foreach ( $matches as $marker => $data ) {
359 list( $element, $content, $params, $tag ) = $data;
360 $tagName = strtolower( $element );
361 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
362 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
366 $this->mStripState
->general
->setPair( $marker, $output );
368 $text = $this->mStripState
->unstripGeneral( $text );
370 $text = Sanitizer
::normalizeCharReferences( $text );
372 if ( ( $wgUseTidy && $this->mOptions
->mTidy
) ||
$wgAlwaysUseTidy ) {
373 $text = MWTidy
::tidy( $text );
375 # attempt to sanitize at least some nesting problems
376 # (bug #2702 and quite a few others)
378 # ''Something [http://www.cool.com cool''] -->
379 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
380 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
381 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
382 # fix up an anchor inside another anchor, only
383 # at least for a single single nested link (bug 3695)
384 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
385 '\\1\\2</a>\\3</a>\\1\\4</a>',
386 # fix div inside inline elements- doBlockLevels won't wrap a line which
387 # contains a div, so fix it up here; replace
388 # div with escaped text
389 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
390 '\\1\\3<div\\5>\\6</div>\\8\\9',
391 # remove empty italic or bold tag pairs, some
392 # introduced by rules above
393 '/<([bi])><\/\\1>/' => '',
396 $text = preg_replace(
397 array_keys( $tidyregs ),
398 array_values( $tidyregs ),
401 global $wgExpensiveParserFunctionLimit;
402 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
403 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
406 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
408 # Information on include size limits, for the benefit of users who try to skirt them
409 if ( $this->mOptions
->getEnableLimitReport() ) {
410 $max = $this->mOptions
->getMaxIncludeSize();
411 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
413 "NewPP limit report\n" .
414 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
415 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
416 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
418 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
419 $text .= "\n<!-- \n$limitReport-->\n";
421 $this->mOutput
->setText( $text );
423 $this->mRevisionId
= $oldRevisionId;
424 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
425 wfProfileOut( $fname );
426 wfProfileOut( __METHOD__
);
428 return $this->mOutput
;
432 * Recursive parser entry point that can be called from an extension tag
435 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
437 * @param $text String: text extension wants to have parsed
438 * @param $frame PPFrame: The frame to use for expanding any template variables
440 function recursiveTagParse( $text, $frame=false ) {
441 wfProfileIn( __METHOD__
);
442 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
443 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
444 $text = $this->internalParse( $text, false, $frame );
445 wfProfileOut( __METHOD__
);
450 * Expand templates and variables in the text, producing valid, static wikitext.
451 * Also removes comments.
453 function preprocess( $text, $title, $options, $revid = null ) {
454 wfProfileIn( __METHOD__
);
456 $this->setOutputType( self
::OT_PREPROCESS
);
457 $this->mOptions
= $options;
458 $this->setTitle( $title );
459 if ( $revid !== null ) {
460 $this->mRevisionId
= $revid;
462 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
463 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
464 $text = $this->replaceVariables( $text );
465 $text = $this->mStripState
->unstripBoth( $text );
466 wfProfileOut( __METHOD__
);
471 * Process the wikitext for the ?preload= feature. (bug 5210)
473 * <noinclude>, <includeonly> etc. are parsed as for template transclusion,
474 * comments, templates, arguments, tags hooks and parser functions are untouched.
476 public function getPreloadText( $text, $title, $options ) {
477 # Parser (re)initialisation
479 $this->setOutputType( self
::OT_PLAIN
);
480 $this->mOptions
= $options;
481 $this->setTitle( $title );
483 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
484 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
485 return $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
489 * Get a random string
494 function getRandomString() {
495 return dechex( mt_rand( 0, 0x7fffffff ) ) . dechex( mt_rand( 0, 0x7fffffff ) );
499 * Accessor for mUniqPrefix.
503 public function uniqPrefix() {
504 if ( !isset( $this->mUniqPrefix
) ) {
505 # @todo Fixme: this is probably *horribly wrong*
506 # LanguageConverter seems to want $wgParser's uniqPrefix, however
507 # if this is called for a parser cache hit, the parser may not
508 # have ever been initialized in the first place.
509 # Not really sure what the heck is supposed to be going on here.
511 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
513 return $this->mUniqPrefix
;
517 * Set the context title
519 function setTitle( $t ) {
520 if ( !$t ||
$t instanceof FakeTitle
) {
521 $t = Title
::newFromText( 'NO TITLE' );
524 if ( strval( $t->getFragment() ) !== '' ) {
525 # Strip the fragment to avoid various odd effects
526 $this->mTitle
= clone $t;
527 $this->mTitle
->setFragment( '' );
534 * Accessor for the Title object
536 * @return Title object
538 function &getTitle() {
539 return $this->mTitle
;
543 * Accessor/mutator for the Title object
545 * @param $x New Title object or null to just get the current one
546 * @return Title object
548 function Title( $x = null ) {
549 return wfSetVar( $this->mTitle
, $x );
553 * Set the output type
555 * @param $ot Integer: new value
557 function setOutputType( $ot ) {
558 $this->mOutputType
= $ot;
561 'html' => $ot == self
::OT_HTML
,
562 'wiki' => $ot == self
::OT_WIKI
,
563 'pre' => $ot == self
::OT_PREPROCESS
,
564 'plain' => $ot == self
::OT_PLAIN
,
569 * Accessor/mutator for the output type
571 * @param $x New value or null to just get the current one
574 function OutputType( $x = null ) {
575 return wfSetVar( $this->mOutputType
, $x );
579 * Get the ParserOutput object
581 * @return ParserOutput object
583 function getOutput() {
584 return $this->mOutput
;
588 * Get the ParserOptions object
590 * @return ParserOptions object
592 function getOptions() {
593 return $this->mOptions
;
597 * Accessor/mutator for the ParserOptions object
599 * @param $x New value or null to just get the current one
600 * @return Current ParserOptions object
602 function Options( $x = null ) {
603 return wfSetVar( $this->mOptions
, $x );
606 function nextLinkID() {
607 return $this->mLinkID++
;
610 function getFunctionLang() {
611 global $wgLang, $wgContLang;
613 $target = $this->mOptions
->getTargetLanguage();
614 if ( $target !== null ) {
617 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
622 * Get a preprocessor object
624 * @return Preprocessor instance
626 function getPreprocessor() {
627 if ( !isset( $this->mPreprocessor
) ) {
628 $class = $this->mPreprocessorClass
;
629 $this->mPreprocessor
= new $class( $this );
631 return $this->mPreprocessor
;
635 * Replaces all occurrences of HTML-style comments and the given tags
636 * in the text with a random marker and returns the next text. The output
637 * parameter $matches will be an associative array filled with data in
639 * 'UNIQ-xxxxx' => array(
642 * array( 'param' => 'x' ),
643 * '<element param="x">tag content</element>' ) )
645 * @param $elements list of element names. Comments are always extracted.
646 * @param $text Source text string.
647 * @param $matches Out parameter, Array: extarcted tags
648 * @param $uniq_prefix
649 * @return String: stripped text
653 public function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
658 $taglist = implode( '|', $elements );
659 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
661 while ( $text != '' ) {
662 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
664 if ( count( $p ) < 5 ) {
667 if ( count( $p ) > 5 ) {
681 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
682 $stripped .= $marker;
684 if ( $close === '/>' ) {
685 # Empty element tag, <tag />
690 if ( $element === '!--' ) {
693 $end = "/(<\\/$element\\s*>)/i";
695 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
697 if ( count( $q ) < 3 ) {
698 # No end tag -- let it run out to the end of the text.
707 $matches[$marker] = array( $element,
709 Sanitizer
::decodeTagAttributes( $attributes ),
710 "<$element$attributes$close$content$tail" );
716 * Get a list of strippable XML-like elements
718 function getStripList() {
719 return $this->mStripList
;
723 * @deprecated use replaceVariables
725 function strip( $text, $state, $stripcomments = false , $dontstrip = array() ) {
730 * Restores pre, math, and other extensions removed by strip()
732 * always call unstripNoWiki() after this one
734 * @deprecated use $this->mStripState->unstrip()
736 function unstrip( $text, $state ) {
737 return $state->unstripGeneral( $text );
741 * Always call this after unstrip() to preserve the order
744 * @deprecated use $this->mStripState->unstrip()
746 function unstripNoWiki( $text, $state ) {
747 return $state->unstripNoWiki( $text );
751 * @deprecated use $this->mStripState->unstripBoth()
753 function unstripForHTML( $text ) {
754 return $this->mStripState
->unstripBoth( $text );
758 * Add an item to the strip state
759 * Returns the unique tag which must be inserted into the stripped text
760 * The tag will be replaced with the original text in unstrip()
764 function insertStripItem( $text ) {
765 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
766 $this->mMarkerIndex++
;
767 $this->mStripState
->general
->setPair( $rnd, $text );
772 * Interface with html tidy
773 * @deprecated Use MWTidy::tidy()
775 public static function tidy( $text ) {
776 wfDeprecated( __METHOD__
);
777 return MWTidy
::tidy( $text );
781 * parse the wiki syntax used to render tables
785 function doTableStuff( $text ) {
786 wfProfileIn( __METHOD__
);
788 $lines = StringUtils
::explode( "\n", $text );
791 $td_history = array(); # Is currently a td tag open?
792 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
793 $tr_history = array(); # Is currently a tr tag open?
794 $tr_attributes = array(); # history of tr attributes
795 $has_opened_tr = array(); # Did this table open a <tr> element?
796 $indent_level = 0; # indent level of the table
798 $table_tag = 'table';
802 $caption_tag = 'caption';
804 $extra_table_attribs = null;
805 $extra_tr_attribs = null;
806 $extra_td_attribs = null;
808 $convert_style = false;
810 foreach ( $lines as $outLine ) {
811 $line = trim( $outLine );
813 if ( $line === '' ) { # empty line, go to next line
814 $out .= $outLine."\n";
818 $first_character = $line[0];
821 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
822 # First check if we are starting a new table
823 $indent_level = strlen( $matches[1] );
825 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
827 $attr = Sanitizer
::decodeTagAttributes( $attributes );
829 $mode = @$attr['mode'];
830 if ( !$mode ) $mode = 'data';
832 if ( $mode == 'grid' ||
$mode == 'layout' ) {
837 $caption_tag = 'div';
839 $extra_table_attribs = array( 'class' => 'grid-table' );
840 $extra_tr_attribs = array( 'class' => 'grid-row' );
841 $extra_td_attribs = array( 'class' => 'grid-cell' );
843 $convert_style = true;
846 if ($convert_style) $attr['style'] = Sanitizer
::styleFromAttributes( $attr );
847 $attr = Sanitizer
::validateTagAttributes( $attr, $table_tag );
848 $attributes = Sanitizer
::collapseTagAttributes( $attr, $extra_table_attribs );
850 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<$table_tag{$attributes}>";
851 array_push( $td_history , false );
852 array_push( $last_tag_history , '' );
853 array_push( $tr_history , false );
854 array_push( $tr_attributes , '' );
855 array_push( $has_opened_tr , false );
856 } elseif ( count( $td_history ) == 0 ) {
857 # Don't do any of the following
858 $out .= $outLine."\n";
860 } elseif ( substr( $line , 0 , 2 ) === '|}' ) {
861 # We are ending a table
862 $line = "</$table_tag>" . substr( $line , 2 );
863 $last_tag = array_pop( $last_tag_history );
865 if ( !array_pop( $has_opened_tr ) ) {
866 $line = "<$tr_tag><$td_tag></$td_tag></$tr_tag>{$line}";
869 if ( array_pop( $tr_history ) ) {
870 $line = "</$tr_tag>{$line}";
873 if ( array_pop( $td_history ) ) {
874 $line = "</{$last_tag}>{$line}";
876 array_pop( $tr_attributes );
877 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
878 } elseif ( substr( $line , 0 , 2 ) === '|-' ) {
879 # Now we have a table row
880 $line = preg_replace( '#^\|-+#', '', $line );
882 # Whats after the tag is now only attributes
883 $attributes = $this->mStripState
->unstripBoth( $line );
885 $attr = Sanitizer
::decodeTagAttributes( $attributes );
886 if ($convert_style) $attr['style'] = Sanitizer
::styleFromAttributes( $attr );
887 $attr = Sanitizer
::validateTagAttributes( $attr, $tr_tag );
888 $attributes = Sanitizer
::collapseTagAttributes( $attr, $extra_tr_attribs );
890 array_pop( $tr_attributes );
891 array_push( $tr_attributes, $attributes );
894 $last_tag = array_pop( $last_tag_history );
895 array_pop( $has_opened_tr );
896 array_push( $has_opened_tr , true );
898 if ( array_pop( $tr_history ) ) {
899 $line = "</$tr_tag>";
902 if ( array_pop( $td_history ) ) {
903 $line = "</{$last_tag}>{$line}";
907 array_push( $tr_history , false );
908 array_push( $td_history , false );
909 array_push( $last_tag_history , '' );
910 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line , 0 , 2 ) === '|+' ) {
911 # This might be cell elements, td, th or captions
912 if ( substr( $line , 0 , 2 ) === '|+' ) {
913 $first_character = '+';
914 $line = substr( $line , 1 );
917 $line = substr( $line , 1 );
919 if ( $first_character === '!' ) {
920 $line = str_replace( '!!' , '||' , $line );
923 # Split up multiple cells on the same line.
924 # FIXME : This can result in improper nesting of tags processed
925 # by earlier parser steps, but should avoid splitting up eg
926 # attribute values containing literal "||".
927 $cells = StringUtils
::explodeMarkup( '||' , $line );
931 # Loop through each table cell
932 foreach ( $cells as $cell ) {
934 if ( $first_character !== '+' ) {
935 $tr_after = array_pop( $tr_attributes );
936 if ( !array_pop( $tr_history ) ) {
937 $previous = "<$tr_tag{$tr_after}>\n";
939 array_push( $tr_history , true );
940 array_push( $tr_attributes , '' );
941 array_pop( $has_opened_tr );
942 array_push( $has_opened_tr , true );
945 $last_tag = array_pop( $last_tag_history );
947 if ( array_pop( $td_history ) ) {
948 $previous = "</{$last_tag}>{$previous}";
951 if ( $first_character === '|' ) {
953 } elseif ( $first_character === '!' ) {
955 } elseif ( $first_character === '+' ) {
956 $last_tag = $caption_tag;
961 array_push( $last_tag_history , $last_tag );
963 # A cell could contain both parameters and data
964 $cell_data = explode( '|' , $cell , 2 );
968 # Bug 553: Note that a '|' inside an invalid link should not
969 # be mistaken as delimiting cell parameters
970 if ( strpos( $cell_data[0], '[[' ) !== false ) {
971 if ($extra_td_attribs) $attributes = Sanitizer
::collapseTagAttributes( $extra_td_attribs );
972 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell}";
973 } elseif ( count( $cell_data ) == 1 ) {
974 if ($extra_td_attribs) $attributes = Sanitizer
::collapseTagAttributes( $extra_td_attribs );
975 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[0]}";
977 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
979 $attr = Sanitizer
::decodeTagAttributes( $attributes );
980 if ($convert_style) $attr['style'] = Sanitizer
::styleFromAttributes( $attr );
981 $attr = Sanitizer
::validateTagAttributes( $attr, $last_tag );
982 $attributes = Sanitizer
::collapseTagAttributes( $attr, $extra_td_attribs );
984 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
988 array_push( $td_history , true );
991 $out .= $outLine . "\n";
994 # Closing open td, tr && table
995 while ( count( $td_history ) > 0 ) {
996 if ( array_pop( $td_history ) ) {
997 $out .= "</$td_tag>\n";
999 if ( array_pop( $tr_history ) ) {
1000 $out .= "</$tr_tag>\n";
1002 if ( !array_pop( $has_opened_tr ) ) {
1003 $out .= "<$tr_tag><$td_tag></$td_tag></$tr_tag>\n" ;
1006 $out .= "</$table_tag>\n";
1009 # Remove trailing line-ending (b/c)
1010 if ( substr( $out, -1 ) === "\n" ) {
1011 $out = substr( $out, 0, -1 );
1014 # special case: don't return empty table
1015 if ( $out === "<$table_tag>\n<$tr_tag><$td_tag></$td_tag></$tr_tag>\n</$table_tag>" ) {
1019 wfProfileOut( __METHOD__
);
1025 * Helper function for parse() that transforms wiki markup into
1026 * HTML. Only called for $mOutputType == self::OT_HTML.
1030 function internalParse( $text, $isMain = true, $frame=false ) {
1031 wfProfileIn( __METHOD__
);
1035 # Hook to suspend the parser in this state
1036 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
1037 wfProfileOut( __METHOD__
);
1041 # if $frame is provided, then use $frame for replacing any variables
1043 # use frame depth to infer how include/noinclude tags should be handled
1044 # depth=0 means this is the top-level document; otherwise it's an included document
1045 if ( !$frame->depth
) {
1048 $flag = Parser
::PTD_FOR_INCLUSION
;
1050 $dom = $this->preprocessToDom( $text, $flag );
1051 $text = $frame->expand( $dom );
1053 # if $frame is not provided, then use old-style replaceVariables
1054 $text = $this->replaceVariables( $text );
1057 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
1058 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
1060 # Tables need to come after variable replacement for things to work
1061 # properly; putting them before other transformations should keep
1062 # exciting things like link expansions from showing up in surprising
1064 $text = $this->doTableStuff( $text );
1066 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
1068 $text = $this->doDoubleUnderscore( $text );
1070 $text = $this->doHeadings( $text );
1071 if ( $this->mOptions
->getUseDynamicDates() ) {
1072 $df = DateFormatter
::getInstance();
1073 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
1075 $text = $this->replaceInternalLinks( $text );
1076 $text = $this->doAllQuotes( $text );
1077 $text = $this->replaceExternalLinks( $text );
1079 # replaceInternalLinks may sometimes leave behind
1080 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
1081 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
1083 $text = $this->doMagicLinks( $text );
1084 $text = $this->formatHeadings( $text, $origText, $isMain );
1086 wfProfileOut( __METHOD__
);
1091 * Replace special strings like "ISBN xxx" and "RFC xxx" with
1092 * magic external links.
1097 function doMagicLinks( $text ) {
1098 wfProfileIn( __METHOD__
);
1099 $prots = $this->mUrlProtocols
;
1100 $urlChar = self
::EXT_LINK_URL_CLASS
;
1101 $text = preg_replace_callback(
1103 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
1104 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
1105 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
1106 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
1107 ISBN\s+(\b # m[5]: ISBN, capture number
1108 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
1109 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
1110 [0-9Xx] # check digit
1112 )!x', array( &$this, 'magicLinkCallback' ), $text );
1113 wfProfileOut( __METHOD__
);
1117 function magicLinkCallback( $m ) {
1118 if ( isset( $m[1] ) && $m[1] !== '' ) {
1121 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1124 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1125 # Free external link
1126 return $this->makeFreeExternalLink( $m[0] );
1127 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1130 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1133 $CssClass = 'mw-magiclink-rfc';
1135 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1137 $urlmsg = 'pubmedurl';
1138 $CssClass = 'mw-magiclink-pmid';
1141 throw new MWException( __METHOD__
.': unrecognised match type "' .
1142 substr( $m[0], 0, 20 ) . '"' );
1144 $url = wfMsg( $urlmsg, $id);
1145 $sk = $this->mOptions
->getSkin();
1146 $la = $sk->getExternalLinkAttributes( "external $CssClass" );
1147 return "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1148 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1151 $num = strtr( $isbn, array(
1156 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1158 $titleObj->escapeLocalUrl() .
1159 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1166 * Make a free external link, given a user-supplied URL
1170 function makeFreeExternalLink( $url ) {
1172 wfProfileIn( __METHOD__
);
1174 $sk = $this->mOptions
->getSkin();
1177 # The characters '<' and '>' (which were escaped by
1178 # removeHTMLtags()) should not be included in
1179 # URLs, per RFC 2396.
1181 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1182 $trail = substr( $url, $m2[0][1] ) . $trail;
1183 $url = substr( $url, 0, $m2[0][1] );
1186 # Move trailing punctuation to $trail
1188 # If there is no left bracket, then consider right brackets fair game too
1189 if ( strpos( $url, '(' ) === false ) {
1193 $numSepChars = strspn( strrev( $url ), $sep );
1194 if ( $numSepChars ) {
1195 $trail = substr( $url, -$numSepChars ) . $trail;
1196 $url = substr( $url, 0, -$numSepChars );
1199 $url = Sanitizer
::cleanUrl( $url );
1201 # Is this an external image?
1202 $text = $this->maybeMakeExternalImage( $url );
1203 if ( $text === false ) {
1204 # Not an image, make a link
1205 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1206 $this->getExternalLinkAttribs( $url ) );
1207 # Register it in the output object...
1208 # Replace unnecessary URL escape codes with their equivalent characters
1209 $pasteurized = self
::replaceUnusualEscapes( $url );
1210 $this->mOutput
->addExternalLink( $pasteurized );
1212 wfProfileOut( __METHOD__
);
1213 return $text . $trail;
1218 * Parse headers and return html
1222 function doHeadings( $text ) {
1223 wfProfileIn( __METHOD__
);
1224 for ( $i = 6; $i >= 1; --$i ) {
1225 $h = str_repeat( '=', $i );
1226 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1227 "<h$i>\\1</h$i>", $text );
1229 wfProfileOut( __METHOD__
);
1234 * Replace single quotes with HTML markup
1236 * @return string the altered text
1238 function doAllQuotes( $text ) {
1239 wfProfileIn( __METHOD__
);
1241 $lines = StringUtils
::explode( "\n", $text );
1242 foreach ( $lines as $line ) {
1243 $outtext .= $this->doQuotes( $line ) . "\n";
1245 $outtext = substr( $outtext, 0,-1 );
1246 wfProfileOut( __METHOD__
);
1251 * Helper function for doAllQuotes()
1253 public function doQuotes( $text ) {
1254 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1255 if ( count( $arr ) == 1 ) {
1258 # First, do some preliminary work. This may shift some apostrophes from
1259 # being mark-up to being text. It also counts the number of occurrences
1260 # of bold and italics mark-ups.
1264 foreach ( $arr as $r ) {
1265 if ( ( $i %
2 ) == 1 ) {
1266 # If there are ever four apostrophes, assume the first is supposed to
1267 # be text, and the remaining three constitute mark-up for bold text.
1268 if ( strlen( $arr[$i] ) == 4 ) {
1271 } elseif ( strlen( $arr[$i] ) > 5 ) {
1272 # If there are more than 5 apostrophes in a row, assume they're all
1273 # text except for the last 5.
1274 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1277 # Count the number of occurrences of bold and italics mark-ups.
1278 # We are not counting sequences of five apostrophes.
1279 if ( strlen( $arr[$i] ) == 2 ) {
1281 } elseif ( strlen( $arr[$i] ) == 3 ) {
1283 } elseif ( strlen( $arr[$i] ) == 5 ) {
1291 # If there is an odd number of both bold and italics, it is likely
1292 # that one of the bold ones was meant to be an apostrophe followed
1293 # by italics. Which one we cannot know for certain, but it is more
1294 # likely to be one that has a single-letter word before it.
1295 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1297 $firstsingleletterword = -1;
1298 $firstmultiletterword = -1;
1300 foreach ( $arr as $r ) {
1301 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1302 $x1 = substr( $arr[$i-1], -1 );
1303 $x2 = substr( $arr[$i-1], -2, 1 );
1304 if ( $x1 === ' ' ) {
1305 if ( $firstspace == -1 ) {
1308 } elseif ( $x2 === ' ') {
1309 if ( $firstsingleletterword == -1 ) {
1310 $firstsingleletterword = $i;
1313 if ( $firstmultiletterword == -1 ) {
1314 $firstmultiletterword = $i;
1321 # If there is a single-letter word, use it!
1322 if ( $firstsingleletterword > -1 ) {
1323 $arr[$firstsingleletterword] = "''";
1324 $arr[$firstsingleletterword-1] .= "'";
1325 } elseif ( $firstmultiletterword > -1 ) {
1326 # If not, but there's a multi-letter word, use that one.
1327 $arr[$firstmultiletterword] = "''";
1328 $arr[$firstmultiletterword-1] .= "'";
1329 } elseif ( $firstspace > -1 ) {
1330 # ... otherwise use the first one that has neither.
1331 # (notice that it is possible for all three to be -1 if, for example,
1332 # there is only one pentuple-apostrophe in the line)
1333 $arr[$firstspace] = "''";
1334 $arr[$firstspace-1] .= "'";
1338 # Now let's actually convert our apostrophic mush to HTML!
1343 foreach ( $arr as $r ) {
1344 if ( ( $i %
2 ) == 0 ) {
1345 if ( $state === 'both' ) {
1351 if ( strlen( $r ) == 2 ) {
1352 if ( $state === 'i' ) {
1353 $output .= '</i>'; $state = '';
1354 } elseif ( $state === 'bi' ) {
1355 $output .= '</i>'; $state = 'b';
1356 } elseif ( $state === 'ib' ) {
1357 $output .= '</b></i><b>'; $state = 'b';
1358 } elseif ( $state === 'both' ) {
1359 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1360 } else { # $state can be 'b' or ''
1361 $output .= '<i>'; $state .= 'i';
1363 } elseif ( strlen( $r ) == 3 ) {
1364 if ( $state === 'b' ) {
1365 $output .= '</b>'; $state = '';
1366 } elseif ( $state === 'bi' ) {
1367 $output .= '</i></b><i>'; $state = 'i';
1368 } elseif ( $state === 'ib' ) {
1369 $output .= '</b>'; $state = 'i';
1370 } elseif ( $state === 'both' ) {
1371 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1372 } else { # $state can be 'i' or ''
1373 $output .= '<b>'; $state .= 'b';
1375 } elseif ( strlen( $r ) == 5 ) {
1376 if ( $state === 'b' ) {
1377 $output .= '</b><i>'; $state = 'i';
1378 } elseif ( $state === 'i' ) {
1379 $output .= '</i><b>'; $state = 'b';
1380 } elseif ( $state === 'bi' ) {
1381 $output .= '</i></b>'; $state = '';
1382 } elseif ( $state === 'ib' ) {
1383 $output .= '</b></i>'; $state = '';
1384 } elseif ( $state === 'both' ) {
1385 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1386 } else { # ($state == '')
1387 $buffer = ''; $state = 'both';
1393 # Now close all remaining tags. Notice that the order is important.
1394 if ( $state === 'b' ||
$state === 'ib' ) {
1397 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1400 if ( $state === 'bi' ) {
1403 # There might be lonely ''''', so make sure we have a buffer
1404 if ( $state === 'both' && $buffer ) {
1405 $output .= '<b><i>'.$buffer.'</i></b>';
1412 * Replace external links (REL)
1414 * Note: this is all very hackish and the order of execution matters a lot.
1415 * Make sure to run maintenance/parserTests.php if you change this code.
1419 function replaceExternalLinks( $text ) {
1421 wfProfileIn( __METHOD__
);
1423 $sk = $this->mOptions
->getSkin();
1425 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1426 $s = array_shift( $bits );
1429 while ( $i<count( $bits ) ) {
1431 $protocol = $bits[$i++
];
1432 $text = $bits[$i++
];
1433 $trail = $bits[$i++
];
1435 # The characters '<' and '>' (which were escaped by
1436 # removeHTMLtags()) should not be included in
1437 # URLs, per RFC 2396.
1439 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1440 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1441 $url = substr( $url, 0, $m2[0][1] );
1444 # If the link text is an image URL, replace it with an <img> tag
1445 # This happened by accident in the original parser, but some people used it extensively
1446 $img = $this->maybeMakeExternalImage( $text );
1447 if ( $img !== false ) {
1453 # Set linktype for CSS - if URL==text, link is essentially free
1454 $linktype = ( $text === $url ) ?
'free' : 'text';
1456 # No link text, e.g. [http://domain.tld/some.link]
1457 if ( $text == '' ) {
1458 # Autonumber if allowed. See bug #5918
1459 if ( strpos( wfUrlProtocols(), substr( $protocol, 0, strpos( $protocol, ':' ) ) ) !== false ) {
1460 $langObj = $this->getFunctionLang();
1461 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1462 $linktype = 'autonumber';
1464 # Otherwise just use the URL
1465 $text = htmlspecialchars( $url );
1469 # Have link text, e.g. [http://domain.tld/some.link text]s
1471 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1474 $text = $wgContLang->markNoConversion( $text );
1476 $url = Sanitizer
::cleanUrl( $url );
1478 # Use the encoded URL
1479 # This means that users can paste URLs directly into the text
1480 # Funny characters like ö aren't valid in URLs anyway
1481 # This was changed in August 2004
1482 $s .= $sk->makeExternalLink( $url, $text, false, $linktype,
1483 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1485 # Register link in the output object.
1486 # Replace unnecessary URL escape codes with the referenced character
1487 # This prevents spammers from hiding links from the filters
1488 $pasteurized = self
::replaceUnusualEscapes( $url );
1489 $this->mOutput
->addExternalLink( $pasteurized );
1492 wfProfileOut( __METHOD__
);
1497 * Get an associative array of additional HTML attributes appropriate for a
1498 * particular external link. This currently may include rel => nofollow
1499 * (depending on configuration, namespace, and the URL's domain) and/or a
1500 * target attribute (depending on configuration).
1502 * @param $url String: optional URL, to extract the domain from for rel =>
1503 * nofollow if appropriate
1504 * @return Array: associative array of HTML attributes
1506 function getExternalLinkAttribs( $url = false ) {
1508 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1509 $ns = $this->mTitle
->getNamespace();
1510 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) ) {
1511 $attribs['rel'] = 'nofollow';
1513 global $wgNoFollowDomainExceptions;
1514 if ( $wgNoFollowDomainExceptions ) {
1515 $bits = wfParseUrl( $url );
1516 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1517 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1518 if ( substr( $bits['host'], -strlen( $domain ) ) == $domain ) {
1519 unset( $attribs['rel'] );
1526 if ( $this->mOptions
->getExternalLinkTarget() ) {
1527 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1534 * Replace unusual URL escape codes with their equivalent characters
1536 * @param $url String
1539 * @todo This can merge genuinely required bits in the path or query string,
1540 * breaking legit URLs. A proper fix would treat the various parts of
1541 * the URL differently; as a workaround, just use the output for
1542 * statistical records, not for actual linking/output.
1544 static function replaceUnusualEscapes( $url ) {
1545 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1546 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1550 * Callback function used in replaceUnusualEscapes().
1551 * Replaces unusual URL escape codes with their equivalent character
1553 private static function replaceUnusualEscapesCallback( $matches ) {
1554 $char = urldecode( $matches[0] );
1555 $ord = ord( $char );
1556 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1557 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1558 # No, shouldn't be escaped
1561 # Yes, leave it escaped
1567 * make an image if it's allowed, either through the global
1568 * option, through the exception, or through the on-wiki whitelist
1571 function maybeMakeExternalImage( $url ) {
1572 $sk = $this->mOptions
->getSkin();
1573 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1574 $imagesexception = !empty( $imagesfrom );
1576 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1577 if ( $imagesexception && is_array( $imagesfrom ) ) {
1578 $imagematch = false;
1579 foreach ( $imagesfrom as $match ) {
1580 if ( strpos( $url, $match ) === 0 ) {
1585 } elseif ( $imagesexception ) {
1586 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1588 $imagematch = false;
1590 if ( $this->mOptions
->getAllowExternalImages()
1591 ||
( $imagesexception && $imagematch ) ) {
1592 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1594 $text = $sk->makeExternalImage( $url );
1597 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1598 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1599 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1600 foreach ( $whitelist as $entry ) {
1601 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1602 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1605 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1606 # Image matches a whitelist entry
1607 $text = $sk->makeExternalImage( $url );
1616 * Process [[ ]] wikilinks
1617 * @return processed text
1621 function replaceInternalLinks( $s ) {
1622 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1627 * Process [[ ]] wikilinks (RIL)
1628 * @return LinkHolderArray
1632 function replaceInternalLinks2( &$s ) {
1635 wfProfileIn( __METHOD__
);
1637 wfProfileIn( __METHOD__
.'-setup' );
1638 static $tc = FALSE, $e1, $e1_img;
1639 # the % is needed to support urlencoded titles as well
1641 $tc = Title
::legalChars() . '#%';
1642 # Match a link having the form [[namespace:link|alternate]]trail
1643 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1644 # Match cases where there is no "]]", which might still be images
1645 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1648 $sk = $this->mOptions
->getSkin();
1649 $holders = new LinkHolderArray( $this );
1651 # split the entire text string on occurences of [[
1652 $a = StringUtils
::explode( '[[', ' ' . $s );
1653 # get the first element (all text up to first [[), and remove the space we added
1656 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1657 $s = substr( $s, 1 );
1659 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1661 if ( $useLinkPrefixExtension ) {
1662 # Match the end of a line for a word that's not followed by whitespace,
1663 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1664 $e2 = wfMsgForContent( 'linkprefix' );
1667 if ( is_null( $this->mTitle
) ) {
1668 wfProfileOut( __METHOD__
.'-setup' );
1669 wfProfileOut( __METHOD__
);
1670 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1672 $nottalk = !$this->mTitle
->isTalkPage();
1674 if ( $useLinkPrefixExtension ) {
1676 if ( preg_match( $e2, $s, $m ) ) {
1677 $first_prefix = $m[2];
1679 $first_prefix = false;
1685 if ( $wgContLang->hasVariants() ) {
1686 $selflink = $wgContLang->convertLinkToAllVariants( $this->mTitle
->getPrefixedText() );
1688 $selflink = array( $this->mTitle
->getPrefixedText() );
1690 $useSubpages = $this->areSubpagesAllowed();
1691 wfProfileOut( __METHOD__
.'-setup' );
1693 # Loop for each link
1694 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1695 # Check for excessive memory usage
1696 if ( $holders->isBig() ) {
1698 # Do the existence check, replace the link holders and clear the array
1699 $holders->replace( $s );
1703 if ( $useLinkPrefixExtension ) {
1704 wfProfileIn( __METHOD__
.'-prefixhandling' );
1705 if ( preg_match( $e2, $s, $m ) ) {
1712 if ( $first_prefix ) {
1713 $prefix = $first_prefix;
1714 $first_prefix = false;
1716 wfProfileOut( __METHOD__
.'-prefixhandling' );
1719 $might_be_img = false;
1721 wfProfileIn( __METHOD__
."-e1" );
1722 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1724 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1725 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1726 # the real problem is with the $e1 regex
1729 # Still some problems for cases where the ] is meant to be outside punctuation,
1730 # and no image is in sight. See bug 2095.
1732 if ( $text !== '' &&
1733 substr( $m[3], 0, 1 ) === ']' &&
1734 strpos( $text, '[' ) !== false
1737 $text .= ']'; # so that replaceExternalLinks($text) works later
1738 $m[3] = substr( $m[3], 1 );
1740 # fix up urlencoded title texts
1741 if ( strpos( $m[1], '%' ) !== false ) {
1742 # Should anchors '#' also be rejected?
1743 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode( $m[1] ) );
1746 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1747 $might_be_img = true;
1749 if ( strpos( $m[1], '%' ) !== false ) {
1750 $m[1] = urldecode( $m[1] );
1753 } else { # Invalid form; output directly
1754 $s .= $prefix . '[[' . $line ;
1755 wfProfileOut( __METHOD__
."-e1" );
1758 wfProfileOut( __METHOD__
."-e1" );
1759 wfProfileIn( __METHOD__
."-misc" );
1761 # Don't allow internal links to pages containing
1762 # PROTO: where PROTO is a valid URL protocol; these
1763 # should be external links.
1764 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1765 $s .= $prefix . '[[' . $line ;
1766 wfProfileOut( __METHOD__
."-misc" );
1770 # Make subpage if necessary
1771 if ( $useSubpages ) {
1772 $link = $this->maybeDoSubpageLink( $m[1], $text );
1777 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1779 # Strip off leading ':'
1780 $link = substr( $link, 1 );
1783 wfProfileOut( __METHOD__
."-misc" );
1784 wfProfileIn( __METHOD__
."-title" );
1785 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1786 if ( $nt === null ) {
1787 $s .= $prefix . '[[' . $line;
1788 wfProfileOut( __METHOD__
."-title" );
1792 $ns = $nt->getNamespace();
1793 $iw = $nt->getInterWiki();
1794 wfProfileOut( __METHOD__
."-title" );
1796 if ( $might_be_img ) { # if this is actually an invalid link
1797 wfProfileIn( __METHOD__
."-might_be_img" );
1798 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1801 # look at the next 'line' to see if we can close it there
1803 $next_line = $a->current();
1804 if ( $next_line === false ||
$next_line === null ) {
1807 $m = explode( ']]', $next_line, 3 );
1808 if ( count( $m ) == 3 ) {
1809 # the first ]] closes the inner link, the second the image
1811 $text .= "[[{$m[0]}]]{$m[1]}";
1814 } elseif ( count( $m ) == 2 ) {
1815 # if there's exactly one ]] that's fine, we'll keep looking
1816 $text .= "[[{$m[0]}]]{$m[1]}";
1818 # if $next_line is invalid too, we need look no further
1819 $text .= '[[' . $next_line;
1824 # we couldn't find the end of this imageLink, so output it raw
1825 # but don't ignore what might be perfectly normal links in the text we've examined
1826 $holders->merge( $this->replaceInternalLinks2( $text ) );
1827 $s .= "{$prefix}[[$link|$text";
1828 # note: no $trail, because without an end, there *is* no trail
1829 wfProfileOut( __METHOD__
."-might_be_img" );
1832 } else { # it's not an image, so output it raw
1833 $s .= "{$prefix}[[$link|$text";
1834 # note: no $trail, because without an end, there *is* no trail
1835 wfProfileOut( __METHOD__
."-might_be_img" );
1838 wfProfileOut( __METHOD__
."-might_be_img" );
1841 $wasblank = ( $text == '' );
1845 # Bug 4598 madness. Handle the quotes only if they come from the alternate part
1846 # [[Lista d''e paise d''o munno]] -> <a href="">Lista d''e paise d''o munno</a>
1847 # [[Criticism of Harry Potter|Criticism of ''Harry Potter'']] -> <a href="Criticism of Harry Potter">Criticism of <i>Harry Potter</i></a>
1848 $text = $this->doQuotes($text);
1851 # Link not escaped by : , create the various objects
1855 wfProfileIn( __METHOD__
."-interwiki" );
1856 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1857 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1858 $s = rtrim( $s . $prefix );
1859 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1860 wfProfileOut( __METHOD__
."-interwiki" );
1863 wfProfileOut( __METHOD__
."-interwiki" );
1865 if ( $ns == NS_FILE
) {
1866 wfProfileIn( __METHOD__
."-image" );
1867 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1869 # if no parameters were passed, $text
1870 # becomes something like "File:Foo.png",
1871 # which we don't want to pass on to the
1875 # recursively parse links inside the image caption
1876 # actually, this will parse them in any other parameters, too,
1877 # but it might be hard to fix that, and it doesn't matter ATM
1878 $text = $this->replaceExternalLinks( $text );
1879 $holders->merge( $this->replaceInternalLinks2( $text ) );
1881 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1882 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1884 $s .= $prefix . $trail;
1886 $this->mOutput
->addImage( $nt->getDBkey() );
1887 wfProfileOut( __METHOD__
."-image" );
1892 if ( $ns == NS_CATEGORY
) {
1893 wfProfileIn( __METHOD__
."-category" );
1894 $s = rtrim( $s . "\n" ); # bug 87
1897 $sortkey = $this->getDefaultSort();
1901 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1902 $sortkey = str_replace( "\n", '', $sortkey );
1903 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1904 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1907 * Strip the whitespace Category links produce, see bug 87
1908 * @todo We might want to use trim($tmp, "\n") here.
1910 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'': $prefix . $trail;
1912 wfProfileOut( __METHOD__
."-category" );
1917 # Self-link checking
1918 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1919 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1920 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1925 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1926 # FIXME: Should do batch file existence checks, see comment below
1927 if ( $ns == NS_MEDIA
) {
1928 wfProfileIn( __METHOD__
."-media" );
1929 # Give extensions a chance to select the file revision for us
1930 $skip = $time = false;
1931 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1933 $link = $sk->link( $nt );
1935 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1937 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1938 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1939 $this->mOutput
->addImage( $nt->getDBkey() );
1940 wfProfileOut( __METHOD__
."-media" );
1944 wfProfileIn( __METHOD__
."-always_known" );
1945 # Some titles, such as valid special pages or files in foreign repos, should
1946 # be shown as bluelinks even though they're not included in the page table
1948 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1949 # batch file existence checks for NS_FILE and NS_MEDIA
1950 if ( $iw == '' && $nt->isAlwaysKnown() ) {
1951 $this->mOutput
->addLink( $nt );
1952 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1954 # Links will be added to the output link list after checking
1955 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1957 wfProfileOut( __METHOD__
."-always_known" );
1959 wfProfileOut( __METHOD__
);
1964 * Make a link placeholder. The text returned can be later resolved to a real link with
1965 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1966 * parsing of interwiki links, and secondly to allow all existence checks and
1967 * article length checks (for stub links) to be bundled into a single query.
1971 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1972 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1976 * Render a forced-blue link inline; protect against double expansion of
1977 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1978 * Since this little disaster has to split off the trail text to avoid
1979 * breaking URLs in the following text without breaking trails on the
1980 * wiki links, it's been made into a horrible function.
1983 * @param $text String
1984 * @param $query String
1985 * @param $trail String
1986 * @param $prefix String
1987 * @return String: HTML-wikitext mix oh yuck
1989 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1990 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1991 $sk = $this->mOptions
->getSkin();
1992 # FIXME: use link() instead of deprecated makeKnownLinkObj()
1993 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1994 return $this->armorLinks( $link ) . $trail;
1998 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1999 * going to go through further parsing steps before inline URL expansion.
2001 * Not needed quite as much as it used to be since free links are a bit
2002 * more sensible these days. But bracketed links are still an issue.
2004 * @param $text String: more-or-less HTML
2005 * @return String: less-or-more HTML with NOPARSE bits
2007 function armorLinks( $text ) {
2008 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
2009 "{$this->mUniqPrefix}NOPARSE$1", $text );
2013 * Return true if subpage links should be expanded on this page.
2016 function areSubpagesAllowed() {
2017 # Some namespaces don't allow subpages
2018 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
2022 * Handle link to subpage if necessary
2024 * @param $target String: the source of the link
2025 * @param &$text String: the link text, modified as necessary
2026 * @return string the full name of the link
2029 function maybeDoSubpageLink( $target, &$text ) {
2030 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
2034 * Used by doBlockLevels()
2037 function closeParagraph() {
2039 if ( $this->mLastSection
!= '' ) {
2040 $result = '</' . $this->mLastSection
. ">\n";
2042 $this->mInPre
= false;
2043 $this->mLastSection
= '';
2048 * getCommon() returns the length of the longest common substring
2049 * of both arguments, starting at the beginning of both.
2052 function getCommon( $st1, $st2 ) {
2053 $fl = strlen( $st1 );
2054 $shorter = strlen( $st2 );
2055 if ( $fl < $shorter ) {
2059 for ( $i = 0; $i < $shorter; ++
$i ) {
2060 if ( $st1{$i} != $st2{$i} ) {
2068 * These next three functions open, continue, and close the list
2069 * element appropriate to the prefix character passed into them.
2072 function openList( $char ) {
2073 $result = $this->closeParagraph();
2075 if ( '*' === $char ) {
2076 $result .= '<ul><li>';
2077 } elseif ( '#' === $char ) {
2078 $result .= '<ol><li>';
2079 } elseif ( ':' === $char ) {
2080 $result .= '<dl><dd>';
2081 } elseif ( ';' === $char ) {
2082 $result .= '<dl><dt>';
2083 $this->mDTopen
= true;
2085 $result = '<!-- ERR 1 -->';
2093 * @param $char String
2096 function nextItem( $char ) {
2097 if ( '*' === $char ||
'#' === $char ) {
2099 } elseif ( ':' === $char ||
';' === $char ) {
2101 if ( $this->mDTopen
) {
2104 if ( ';' === $char ) {
2105 $this->mDTopen
= true;
2106 return $close . '<dt>';
2108 $this->mDTopen
= false;
2109 return $close . '<dd>';
2112 return '<!-- ERR 2 -->';
2117 * @param $char String
2120 function closeList( $char ) {
2121 if ( '*' === $char ) {
2122 $text = '</li></ul>';
2123 } elseif ( '#' === $char ) {
2124 $text = '</li></ol>';
2125 } elseif ( ':' === $char ) {
2126 if ( $this->mDTopen
) {
2127 $this->mDTopen
= false;
2128 $text = '</dt></dl>';
2130 $text = '</dd></dl>';
2133 return '<!-- ERR 3 -->';
2140 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2142 * @param $text String
2143 * @param $linestart Boolean: whether or not this is at the start of a line.
2145 * @return string the lists rendered as HTML
2147 function doBlockLevels( $text, $linestart ) {
2148 wfProfileIn( __METHOD__
);
2150 # Parsing through the text line by line. The main thing
2151 # happening here is handling of block-level elements p, pre,
2152 # and making lists from lines starting with * # : etc.
2154 $textLines = StringUtils
::explode( "\n", $text );
2156 $lastPrefix = $output = '';
2157 $this->mDTopen
= $inBlockElem = false;
2159 $paragraphStack = false;
2161 foreach ( $textLines as $oLine ) {
2163 if ( !$linestart ) {
2173 $lastPrefixLength = strlen( $lastPrefix );
2174 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2175 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2176 # If not in a <pre> element, scan for and figure out what prefixes are there.
2177 if ( !$this->mInPre
) {
2178 # Multiple prefixes may abut each other for nested lists.
2179 $prefixLength = strspn( $oLine, '*#:;' );
2180 $prefix = substr( $oLine, 0, $prefixLength );
2183 # ; and : are both from definition-lists, so they're equivalent
2184 # for the purposes of determining whether or not we need to open/close
2186 $prefix2 = str_replace( ';', ':', $prefix );
2187 $t = substr( $oLine, $prefixLength );
2188 $this->mInPre
= (bool)$preOpenMatch;
2190 # Don't interpret any other prefixes in preformatted text
2192 $prefix = $prefix2 = '';
2197 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2198 # Same as the last item, so no need to deal with nesting or opening stuff
2199 $output .= $this->nextItem( substr( $prefix, -1 ) );
2200 $paragraphStack = false;
2202 if ( substr( $prefix, -1 ) === ';') {
2203 # The one nasty exception: definition lists work like this:
2204 # ; title : definition text
2205 # So we check for : in the remainder text to split up the
2206 # title and definition, without b0rking links.
2208 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2210 $output .= $term . $this->nextItem( ':' );
2213 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2214 # We need to open or close prefixes, or both.
2216 # Either open or close a level...
2217 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2218 $paragraphStack = false;
2220 # Close all the prefixes which aren't shared.
2221 while ( $commonPrefixLength < $lastPrefixLength ) {
2222 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2223 --$lastPrefixLength;
2226 # Continue the current prefix if appropriate.
2227 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2228 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2231 # Open prefixes where appropriate.
2232 while ( $prefixLength > $commonPrefixLength ) {
2233 $char = substr( $prefix, $commonPrefixLength, 1 );
2234 $output .= $this->openList( $char );
2236 if ( ';' === $char ) {
2237 # FIXME: This is dupe of code above
2238 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2240 $output .= $term . $this->nextItem( ':' );
2243 ++
$commonPrefixLength;
2245 $lastPrefix = $prefix2;
2248 # If we have no prefixes, go to paragraph mode.
2249 if ( 0 == $prefixLength ) {
2250 wfProfileIn( __METHOD__
."-paragraph" );
2251 # No prefix (not in list)--go to paragraph mode
2252 # XXX: use a stack for nestable elements like span, table and div
2253 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2254 $closematch = preg_match(
2255 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2256 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2257 if ( $openmatch or $closematch ) {
2258 $paragraphStack = false;
2259 #Â TODO bug 5718: paragraph closed
2260 $output .= $this->closeParagraph();
2261 if ( $preOpenMatch and !$preCloseMatch ) {
2262 $this->mInPre
= true;
2264 if ( $closematch ) {
2265 $inBlockElem = false;
2267 $inBlockElem = true;
2269 } elseif ( !$inBlockElem && !$this->mInPre
) {
2270 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2272 if ( $this->mLastSection
!== 'pre' ) {
2273 $paragraphStack = false;
2274 $output .= $this->closeParagraph().'<pre>';
2275 $this->mLastSection
= 'pre';
2277 $t = substr( $t, 1 );
2280 if ( trim( $t ) === '' ) {
2281 if ( $paragraphStack ) {
2282 $output .= $paragraphStack.'<br />';
2283 $paragraphStack = false;
2284 $this->mLastSection
= 'p';
2286 if ( $this->mLastSection
!== 'p' ) {
2287 $output .= $this->closeParagraph();
2288 $this->mLastSection
= '';
2289 $paragraphStack = '<p>';
2291 $paragraphStack = '</p><p>';
2295 if ( $paragraphStack ) {
2296 $output .= $paragraphStack;
2297 $paragraphStack = false;
2298 $this->mLastSection
= 'p';
2299 } elseif ( $this->mLastSection
!== 'p' ) {
2300 $output .= $this->closeParagraph().'<p>';
2301 $this->mLastSection
= 'p';
2306 wfProfileOut( __METHOD__
."-paragraph" );
2308 # somewhere above we forget to get out of pre block (bug 785)
2309 if ( $preCloseMatch && $this->mInPre
) {
2310 $this->mInPre
= false;
2312 if ( $paragraphStack === false ) {
2316 while ( $prefixLength ) {
2317 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2320 if ( $this->mLastSection
!= '' ) {
2321 $output .= '</' . $this->mLastSection
. '>';
2322 $this->mLastSection
= '';
2325 wfProfileOut( __METHOD__
);
2330 * Split up a string on ':', ignoring any occurences inside tags
2331 * to prevent illegal overlapping.
2333 * @param $str String: the string to split
2334 * @param &$before String: set to everything before the ':'
2335 * @param &$after String: set to everything after the ':'
2336 * return String: the position of the ':', or false if none found
2338 function findColonNoLinks( $str, &$before, &$after ) {
2339 wfProfileIn( __METHOD__
);
2341 $pos = strpos( $str, ':' );
2342 if ( $pos === false ) {
2344 wfProfileOut( __METHOD__
);
2348 $lt = strpos( $str, '<' );
2349 if ( $lt === false ||
$lt > $pos ) {
2350 # Easy; no tag nesting to worry about
2351 $before = substr( $str, 0, $pos );
2352 $after = substr( $str, $pos+
1 );
2353 wfProfileOut( __METHOD__
);
2357 # Ugly state machine to walk through avoiding tags.
2358 $state = self
::COLON_STATE_TEXT
;
2360 $len = strlen( $str );
2361 for( $i = 0; $i < $len; $i++
) {
2365 # (Using the number is a performance hack for common cases)
2366 case 0: # self::COLON_STATE_TEXT:
2369 # Could be either a <start> tag or an </end> tag
2370 $state = self
::COLON_STATE_TAGSTART
;
2373 if ( $stack == 0 ) {
2375 $before = substr( $str, 0, $i );
2376 $after = substr( $str, $i +
1 );
2377 wfProfileOut( __METHOD__
);
2380 # Embedded in a tag; don't break it.
2383 # Skip ahead looking for something interesting
2384 $colon = strpos( $str, ':', $i );
2385 if ( $colon === false ) {
2386 # Nothing else interesting
2387 wfProfileOut( __METHOD__
);
2390 $lt = strpos( $str, '<', $i );
2391 if ( $stack === 0 ) {
2392 if ( $lt === false ||
$colon < $lt ) {
2394 $before = substr( $str, 0, $colon );
2395 $after = substr( $str, $colon +
1 );
2396 wfProfileOut( __METHOD__
);
2400 if ( $lt === false ) {
2401 # Nothing else interesting to find; abort!
2402 # We're nested, but there's no close tags left. Abort!
2405 # Skip ahead to next tag start
2407 $state = self
::COLON_STATE_TAGSTART
;
2410 case 1: # self::COLON_STATE_TAG:
2415 $state = self
::COLON_STATE_TEXT
;
2418 # Slash may be followed by >?
2419 $state = self
::COLON_STATE_TAGSLASH
;
2425 case 2: # self::COLON_STATE_TAGSTART:
2428 $state = self
::COLON_STATE_CLOSETAG
;
2431 $state = self
::COLON_STATE_COMMENT
;
2434 # Illegal early close? This shouldn't happen D:
2435 $state = self
::COLON_STATE_TEXT
;
2438 $state = self
::COLON_STATE_TAG
;
2441 case 3: # self::COLON_STATE_CLOSETAG:
2446 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2447 wfProfileOut( __METHOD__
);
2450 $state = self
::COLON_STATE_TEXT
;
2453 case self
::COLON_STATE_TAGSLASH
:
2455 # Yes, a self-closed tag <blah/>
2456 $state = self
::COLON_STATE_TEXT
;
2458 # Probably we're jumping the gun, and this is an attribute
2459 $state = self
::COLON_STATE_TAG
;
2462 case 5: # self::COLON_STATE_COMMENT:
2464 $state = self
::COLON_STATE_COMMENTDASH
;
2467 case self
::COLON_STATE_COMMENTDASH
:
2469 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2471 $state = self
::COLON_STATE_COMMENT
;
2474 case self
::COLON_STATE_COMMENTDASHDASH
:
2476 $state = self
::COLON_STATE_TEXT
;
2478 $state = self
::COLON_STATE_COMMENT
;
2482 throw new MWException( "State machine error in " . __METHOD__
);
2486 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2489 wfProfileOut( __METHOD__
);
2494 * Return value of a magic variable (like PAGENAME)
2498 function getVariableValue( $index, $frame=false ) {
2499 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2500 global $wgScriptPath, $wgStylePath;
2503 * Some of these require message or data lookups and can be
2504 * expensive to check many times.
2506 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2507 if ( isset( $this->mVarCache
[$index] ) ) {
2508 return $this->mVarCache
[$index];
2512 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2513 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2516 global $wgLocaltimezone;
2517 if ( isset( $wgLocaltimezone ) ) {
2518 $oldtz = date_default_timezone_get();
2519 date_default_timezone_set( $wgLocaltimezone );
2522 $localTimestamp = date( 'YmdHis', $ts );
2523 $localMonth = date( 'm', $ts );
2524 $localMonth1 = date( 'n', $ts );
2525 $localMonthName = date( 'n', $ts );
2526 $localDay = date( 'j', $ts );
2527 $localDay2 = date( 'd', $ts );
2528 $localDayOfWeek = date( 'w', $ts );
2529 $localWeek = date( 'W', $ts );
2530 $localYear = date( 'Y', $ts );
2531 $localHour = date( 'H', $ts );
2532 if ( isset( $wgLocaltimezone ) ) {
2533 date_default_timezone_set( $oldtz );
2537 case 'currentmonth':
2538 $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2540 case 'currentmonth1':
2541 $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2543 case 'currentmonthname':
2544 $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2546 case 'currentmonthnamegen':
2547 $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2549 case 'currentmonthabbrev':
2550 $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2553 $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2556 $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2559 $value = $wgContLang->formatNum( $localMonth );
2562 $value = $wgContLang->formatNum( $localMonth1 );
2564 case 'localmonthname':
2565 $value = $wgContLang->getMonthName( $localMonthName );
2567 case 'localmonthnamegen':
2568 $value = $wgContLang->getMonthNameGen( $localMonthName );
2570 case 'localmonthabbrev':
2571 $value = $wgContLang->getMonthAbbreviation( $localMonthName );
2574 $value = $wgContLang->formatNum( $localDay );
2577 $value = $wgContLang->formatNum( $localDay2 );
2580 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2583 $value = $this->mTitle
->getPartialURL();
2585 case 'fullpagename':
2586 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2588 case 'fullpagenamee':
2589 $value = $this->mTitle
->getPrefixedURL();
2592 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2594 case 'subpagenamee':
2595 $value = $this->mTitle
->getSubpageUrlForm();
2597 case 'basepagename':
2598 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2600 case 'basepagenamee':
2601 $value = wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2603 case 'talkpagename':
2604 if ( $this->mTitle
->canTalk() ) {
2605 $talkPage = $this->mTitle
->getTalkPage();
2606 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2611 case 'talkpagenamee':
2612 if ( $this->mTitle
->canTalk() ) {
2613 $talkPage = $this->mTitle
->getTalkPage();
2614 $value = $talkPage->getPrefixedUrl();
2619 case 'subjectpagename':
2620 $subjPage = $this->mTitle
->getSubjectPage();
2621 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2623 case 'subjectpagenamee':
2624 $subjPage = $this->mTitle
->getSubjectPage();
2625 $value = $subjPage->getPrefixedUrl();
2628 # Let the edit saving system know we should parse the page
2629 # *after* a revision ID has been assigned.
2630 $this->mOutput
->setFlag( 'vary-revision' );
2631 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2632 $value = $this->mRevisionId
;
2635 # Let the edit saving system know we should parse the page
2636 # *after* a revision ID has been assigned. This is for null edits.
2637 $this->mOutput
->setFlag( 'vary-revision' );
2638 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2639 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2641 case 'revisionday2':
2642 # Let the edit saving system know we should parse the page
2643 # *after* a revision ID has been assigned. This is for null edits.
2644 $this->mOutput
->setFlag( 'vary-revision' );
2645 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2646 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2648 case 'revisionmonth':
2649 # Let the edit saving system know we should parse the page
2650 # *after* a revision ID has been assigned. This is for null edits.
2651 $this->mOutput
->setFlag( 'vary-revision' );
2652 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2653 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2655 case 'revisionmonth1':
2656 # Let the edit saving system know we should parse the page
2657 # *after* a revision ID has been assigned. This is for null edits.
2658 $this->mOutput
->setFlag( 'vary-revision' );
2659 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2660 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2662 case 'revisionyear':
2663 # Let the edit saving system know we should parse the page
2664 # *after* a revision ID has been assigned. This is for null edits.
2665 $this->mOutput
->setFlag( 'vary-revision' );
2666 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2667 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2669 case 'revisiontimestamp':
2670 # Let the edit saving system know we should parse the page
2671 # *after* a revision ID has been assigned. This is for null edits.
2672 $this->mOutput
->setFlag( 'vary-revision' );
2673 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2674 $value = $this->getRevisionTimestamp();
2676 case 'revisionuser':
2677 # Let the edit saving system know we should parse the page
2678 # *after* a revision ID has been assigned. This is for null edits.
2679 $this->mOutput
->setFlag( 'vary-revision' );
2680 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2681 $value = $this->getRevisionUser();
2684 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2687 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2690 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2693 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2695 case 'subjectspace':
2696 $value = $this->mTitle
->getSubjectNsText();
2698 case 'subjectspacee':
2699 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2701 case 'currentdayname':
2702 $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2705 $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2708 $value = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2711 $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2714 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2715 # int to remove the padding
2716 $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2719 $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2721 case 'localdayname':
2722 $value = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2725 $value = $wgContLang->formatNum( $localYear, true );
2728 $value = $wgContLang->time( $localTimestamp, false, false );
2731 $value = $wgContLang->formatNum( $localHour, true );
2734 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2735 # int to remove the padding
2736 $value = $wgContLang->formatNum( (int)$localWeek );
2739 $value = $wgContLang->formatNum( $localDayOfWeek );
2741 case 'numberofarticles':
2742 $value = $wgContLang->formatNum( SiteStats
::articles() );
2744 case 'numberoffiles':
2745 $value = $wgContLang->formatNum( SiteStats
::images() );
2747 case 'numberofusers':
2748 $value = $wgContLang->formatNum( SiteStats
::users() );
2750 case 'numberofactiveusers':
2751 $value = $wgContLang->formatNum( SiteStats
::activeUsers() );
2753 case 'numberofpages':
2754 $value = $wgContLang->formatNum( SiteStats
::pages() );
2756 case 'numberofadmins':
2757 $value = $wgContLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2759 case 'numberofedits':
2760 $value = $wgContLang->formatNum( SiteStats
::edits() );
2762 case 'numberofviews':
2763 $value = $wgContLang->formatNum( SiteStats
::views() );
2765 case 'currenttimestamp':
2766 $value = wfTimestamp( TS_MW
, $ts );
2768 case 'localtimestamp':
2769 $value = $localTimestamp;
2771 case 'currentversion':
2772 $value = SpecialVersion
::getVersion();
2779 return $wgServerName;
2781 return $wgScriptPath;
2783 return $wgStylePath;
2784 case 'directionmark':
2785 return $wgContLang->getDirMark();
2786 case 'contentlanguage':
2787 global $wgContLanguageCode;
2788 return $wgContLanguageCode;
2791 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2799 $this->mVarCache
[$index] = $value;
2805 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2809 function initialiseVariables() {
2810 wfProfileIn( __METHOD__
);
2811 $variableIDs = MagicWord
::getVariableIDs();
2812 $substIDs = MagicWord
::getSubstIDs();
2814 $this->mVariables
= new MagicWordArray( $variableIDs );
2815 $this->mSubstWords
= new MagicWordArray( $substIDs );
2816 wfProfileOut( __METHOD__
);
2820 * Preprocess some wikitext and return the document tree.
2821 * This is the ghost of replace_variables().
2823 * @param $text String: The text to parse
2824 * @param $flags Integer: bitwise combination of:
2825 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2826 * included. Default is to assume a direct page view.
2828 * The generated DOM tree must depend only on the input text and the flags.
2829 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2831 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2832 * change in the DOM tree for a given text, must be passed through the section identifier
2833 * in the section edit link and thus back to extractSections().
2835 * The output of this function is currently only cached in process memory, but a persistent
2836 * cache may be implemented at a later date which takes further advantage of these strict
2837 * dependency requirements.
2841 function preprocessToDom( $text, $flags = 0 ) {
2842 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2847 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2849 public static function splitWhitespace( $s ) {
2850 $ltrimmed = ltrim( $s );
2851 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2852 $trimmed = rtrim( $ltrimmed );
2853 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2855 $w2 = substr( $ltrimmed, -$diff );
2859 return array( $w1, $trimmed, $w2 );
2863 * Replace magic variables, templates, and template arguments
2864 * with the appropriate text. Templates are substituted recursively,
2865 * taking care to avoid infinite loops.
2867 * Note that the substitution depends on value of $mOutputType:
2868 * self::OT_WIKI: only {{subst:}} templates
2869 * self::OT_PREPROCESS: templates but not extension tags
2870 * self::OT_HTML: all templates and extension tags
2872 * @param $text String: the text to transform
2873 * @param $frame PPFrame Object describing the arguments passed to the template.
2874 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2875 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2876 * @param $argsOnly Boolean: only do argument (triple-brace) expansion, not double-brace expansion
2879 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2880 # Is there any text? Also, Prevent too big inclusions!
2881 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2884 wfProfileIn( __METHOD__
);
2886 if ( $frame === false ) {
2887 $frame = $this->getPreprocessor()->newFrame();
2888 } elseif ( !( $frame instanceof PPFrame
) ) {
2889 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2890 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2893 $dom = $this->preprocessToDom( $text );
2894 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2895 $text = $frame->expand( $dom, $flags );
2897 wfProfileOut( __METHOD__
);
2901 # Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2902 static function createAssocArgs( $args ) {
2903 $assocArgs = array();
2905 foreach ( $args as $arg ) {
2906 $eqpos = strpos( $arg, '=' );
2907 if ( $eqpos === false ) {
2908 $assocArgs[$index++
] = $arg;
2910 $name = trim( substr( $arg, 0, $eqpos ) );
2911 $value = trim( substr( $arg, $eqpos+
1 ) );
2912 if ( $value === false ) {
2915 if ( $name !== false ) {
2916 $assocArgs[$name] = $value;
2925 * Warn the user when a parser limitation is reached
2926 * Will warn at most once the user per limitation type
2928 * @param $limitationType String: should be one of:
2929 * 'expensive-parserfunction' (corresponding messages:
2930 * 'expensive-parserfunction-warning',
2931 * 'expensive-parserfunction-category')
2932 * 'post-expand-template-argument' (corresponding messages:
2933 * 'post-expand-template-argument-warning',
2934 * 'post-expand-template-argument-category')
2935 * 'post-expand-template-inclusion' (corresponding messages:
2936 * 'post-expand-template-inclusion-warning',
2937 * 'post-expand-template-inclusion-category')
2938 * @param $current Current value
2939 * @param $max Maximum allowed, when an explicit limit has been
2940 * exceeded, provide the values (optional)
2942 function limitationWarn( $limitationType, $current=null, $max=null) {
2943 # does no harm if $current and $max are present but are unnecessary for the message
2944 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
2945 $this->mOutput
->addWarning( $warning );
2946 $this->addTrackingCategory( "$limitationType-category" );
2950 * Return the text of a template, after recursively
2951 * replacing any variables or templates within the template.
2953 * @param $piece Array: the parts of the template
2954 * $piece['title']: the title, i.e. the part before the |
2955 * $piece['parts']: the parameter array
2956 * $piece['lineStart']: whether the brace was at the start of a line
2957 * @param $frame PPFrame The current frame, contains template arguments
2958 * @return String: the text of the template
2961 function braceSubstitution( $piece, $frame ) {
2962 global $wgContLang, $wgNonincludableNamespaces;
2963 wfProfileIn( __METHOD__
);
2964 wfProfileIn( __METHOD__
.'-setup' );
2967 $found = false; # $text has been filled
2968 $nowiki = false; # wiki markup in $text should be escaped
2969 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2970 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2971 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2972 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2974 # Title object, where $text came from
2977 # $part1 is the bit before the first |, and must contain only title characters.
2978 # Various prefixes will be stripped from it later.
2979 $titleWithSpaces = $frame->expand( $piece['title'] );
2980 $part1 = trim( $titleWithSpaces );
2983 # Original title text preserved for various purposes
2984 $originalTitle = $part1;
2986 # $args is a list of argument nodes, starting from index 0, not including $part1
2987 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
2988 wfProfileOut( __METHOD__
.'-setup' );
2991 wfProfileIn( __METHOD__
.'-modifiers' );
2994 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
2996 # Possibilities for substMatch: "subst", "safesubst" or FALSE
2997 # Decide whether to expand template or keep wikitext as-is.
2998 if ( $this->ot
['wiki'] ) {
2999 if ( $substMatch === false ) {
3000 $literal = true; # literal when in PST with no prefix
3002 $literal = false; # expand when in PST with subst: or safesubst:
3005 if ( $substMatch == 'subst' ) {
3006 $literal = true; # literal when not in PST with plain subst:
3008 $literal = false; # expand when not in PST with safesubst: or no prefix
3012 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3019 if ( !$found && $args->getLength() == 0 ) {
3020 $id = $this->mVariables
->matchStartToEnd( $part1 );
3021 if ( $id !== false ) {
3022 $text = $this->getVariableValue( $id, $frame );
3023 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
3024 $this->mOutput
->updateCacheExpiry( MagicWord
::getCacheTTL( $id ) );
3030 # MSG, MSGNW and RAW
3033 $mwMsgnw = MagicWord
::get( 'msgnw' );
3034 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
3037 # Remove obsolete MSG:
3038 $mwMsg = MagicWord
::get( 'msg' );
3039 $mwMsg->matchStartAndRemove( $part1 );
3043 $mwRaw = MagicWord
::get( 'raw' );
3044 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
3045 $forceRawInterwiki = true;
3048 wfProfileOut( __METHOD__
.'-modifiers' );
3052 wfProfileIn( __METHOD__
. '-pfunc' );
3054 $colonPos = strpos( $part1, ':' );
3055 if ( $colonPos !== false ) {
3056 # Case sensitive functions
3057 $function = substr( $part1, 0, $colonPos );
3058 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
3059 $function = $this->mFunctionSynonyms
[1][$function];
3061 # Case insensitive functions
3062 $function = $wgContLang->lc( $function );
3063 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
3064 $function = $this->mFunctionSynonyms
[0][$function];
3070 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
3071 $initialArgs = array( &$this );
3072 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
3073 if ( $flags & SFH_OBJECT_ARGS
) {
3074 # Add a frame parameter, and pass the arguments as an array
3075 $allArgs = $initialArgs;
3076 $allArgs[] = $frame;
3077 for ( $i = 0; $i < $args->getLength(); $i++
) {
3078 $funcArgs[] = $args->item( $i );
3080 $allArgs[] = $funcArgs;
3082 # Convert arguments to plain text
3083 for ( $i = 0; $i < $args->getLength(); $i++
) {
3084 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
3086 $allArgs = array_merge( $initialArgs, $funcArgs );
3089 # Workaround for PHP bug 35229 and similar
3090 if ( !is_callable( $callback ) ) {
3091 wfProfileOut( __METHOD__
. '-pfunc' );
3092 wfProfileOut( __METHOD__
);
3093 throw new MWException( "Tag hook for $function is not callable\n" );
3095 $result = call_user_func_array( $callback, $allArgs );
3098 $preprocessFlags = 0;
3100 if ( is_array( $result ) ) {
3101 if ( isset( $result[0] ) ) {
3103 unset( $result[0] );
3106 # Extract flags into the local scope
3107 # This allows callers to set flags such as nowiki, found, etc.
3113 $text = $this->preprocessToDom( $text, $preprocessFlags );
3118 wfProfileOut( __METHOD__
. '-pfunc' );
3121 # Finish mangling title and then check for loops.
3122 # Set $title to a Title object and $titleText to the PDBK
3125 # Split the title into page and subpage
3127 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3128 if ( $subpage !== '' ) {
3129 $ns = $this->mTitle
->getNamespace();
3131 $title = Title
::newFromText( $part1, $ns );
3133 $titleText = $title->getPrefixedText();
3134 # Check for language variants if the template is not found
3135 if ( $wgContLang->hasVariants() && $title->getArticleID() == 0 ) {
3136 $wgContLang->findVariantLink( $part1, $title, true );
3138 # Do recursion depth check
3139 $limit = $this->mOptions
->getMaxTemplateDepth();
3140 if ( $frame->depth
>= $limit ) {
3142 $text = '<span class="error">'
3143 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
3149 # Load from database
3150 if ( !$found && $title ) {
3151 wfProfileIn( __METHOD__
. '-loadtpl' );
3152 if ( !$title->isExternal() ) {
3153 if ( $title->getNamespace() == NS_SPECIAL
3154 && $this->mOptions
->getAllowSpecialInclusion()
3155 && $this->ot
['html'] )
3157 $text = SpecialPage
::capturePath( $title );
3158 if ( is_string( $text ) ) {
3161 $this->disableCache();
3163 } elseif ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3164 $found = false; # access denied
3165 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3167 list( $text, $title ) = $this->getTemplateDom( $title );
3168 if ( $text !== false ) {
3174 # If the title is valid but undisplayable, make a link to it
3175 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3176 $text = "[[:$titleText]]";
3179 } elseif ( $title->isTrans() ) {
3180 # Interwiki transclusion
3181 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3182 $text = $this->interwikiTransclude( $title, 'render' );
3185 $text = $this->interwikiTransclude( $title, 'raw' );
3186 # Preprocess it like a template
3187 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3193 # Do infinite loop check
3194 # This has to be done after redirect resolution to avoid infinite loops via redirects
3195 if ( !$frame->loopCheck( $title ) ) {
3197 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3198 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3200 wfProfileOut( __METHOD__
. '-loadtpl' );
3203 # If we haven't found text to substitute by now, we're done
3204 # Recover the source wikitext and return it
3206 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3207 wfProfileOut( __METHOD__
);
3208 return array( 'object' => $text );
3211 # Expand DOM-style return values in a child frame
3212 if ( $isChildObj ) {
3213 # Clean up argument array
3214 $newFrame = $frame->newChild( $args, $title );
3217 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3218 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3219 # Expansion is eligible for the empty-frame cache
3220 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3221 $text = $this->mTplExpandCache
[$titleText];
3223 $text = $newFrame->expand( $text );
3224 $this->mTplExpandCache
[$titleText] = $text;
3227 # Uncached expansion
3228 $text = $newFrame->expand( $text );
3231 if ( $isLocalObj && $nowiki ) {
3232 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3233 $isLocalObj = false;
3236 # Replace raw HTML by a placeholder
3237 # Add a blank line preceding, to prevent it from mucking up
3238 # immediately preceding headings
3240 $text = "\n\n" . $this->insertStripItem( $text );
3241 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3242 # Escape nowiki-style return values
3243 $text = wfEscapeWikiText( $text );
3244 } elseif ( is_string( $text )
3245 && !$piece['lineStart']
3246 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3248 # Bug 529: if the template begins with a table or block-level
3249 # element, it should be treated as beginning a new line.
3250 # This behaviour is somewhat controversial.
3251 $text = "\n" . $text;
3254 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3255 # Error, oversize inclusion
3256 if ( $titleText !== false ) {
3257 # Make a working, properly escaped link if possible (bug 23588)
3258 $text = "[[:$titleText]]";
3260 # This will probably not be a working link, but at least it may
3261 # provide some hint of where the problem is
3262 preg_replace( '/^:/', '', $originalTitle );
3263 $text = "[[:$originalTitle]]";
3265 $text .= $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3266 $this->limitationWarn( 'post-expand-template-inclusion' );
3269 if ( $isLocalObj ) {
3270 $ret = array( 'object' => $text );
3272 $ret = array( 'text' => $text );
3275 wfProfileOut( __METHOD__
);
3280 * Get the semi-parsed DOM representation of a template with a given title,
3281 * and its redirect destination title. Cached.
3283 function getTemplateDom( $title ) {
3284 $cacheTitle = $title;
3285 $titleText = $title->getPrefixedDBkey();
3287 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3288 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3289 $title = Title
::makeTitle( $ns, $dbk );
3290 $titleText = $title->getPrefixedDBkey();
3292 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3293 return array( $this->mTplDomCache
[$titleText], $title );
3296 # Cache miss, go to the database
3297 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3299 if ( $text === false ) {
3300 $this->mTplDomCache
[$titleText] = false;
3301 return array( false, $title );
3304 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3305 $this->mTplDomCache
[ $titleText ] = $dom;
3307 if ( !$title->equals( $cacheTitle ) ) {
3308 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3309 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3312 return array( $dom, $title );
3316 * Fetch the unparsed text of a template and register a reference to it.
3318 function fetchTemplateAndTitle( $title ) {
3319 $templateCb = $this->mOptions
->getTemplateCallback();
3320 $stuff = call_user_func( $templateCb, $title, $this );
3321 $text = $stuff['text'];
3322 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3323 if ( isset( $stuff['deps'] ) ) {
3324 foreach ( $stuff['deps'] as $dep ) {
3325 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3328 return array( $text, $finalTitle );
3331 function fetchTemplate( $title ) {
3332 $rv = $this->fetchTemplateAndTitle( $title );
3337 * Static function to get a template
3338 * Can be overridden via ParserOptions::setTemplateCallback().
3340 static function statelessFetchTemplate( $title, $parser=false ) {
3341 $text = $skip = false;
3342 $finalTitle = $title;
3345 # Loop to fetch the article, with up to 1 redirect
3346 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3347 # Give extensions a chance to select the revision instead
3348 $id = false; # Assume current
3349 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3355 'page_id' => $title->getArticleID(),
3359 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3360 $rev_id = $rev ?
$rev->getId() : 0;
3361 # If there is no current revision, there is no page
3362 if ( $id === false && !$rev ) {
3363 $linkCache = LinkCache
::singleton();
3364 $linkCache->addBadLinkObj( $title );
3369 'page_id' => $title->getArticleID(),
3370 'rev_id' => $rev_id );
3373 $text = $rev->getText();
3374 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3376 $message = $wgContLang->lcfirst( $title->getText() );
3377 $text = wfMsgForContentNoTrans( $message );
3378 if ( wfEmptyMsg( $message, $text ) ) {
3385 if ( $text === false ) {
3389 $finalTitle = $title;
3390 $title = Title
::newFromRedirect( $text );
3394 'finalTitle' => $finalTitle,
3399 * Transclude an interwiki link.
3401 function interwikiTransclude( $title, $action ) {
3402 global $wgEnableScaryTranscluding;
3404 if ( !$wgEnableScaryTranscluding ) {
3405 return wfMsg('scarytranscludedisabled');
3408 $url = $title->getFullUrl( "action=$action" );
3410 if ( strlen( $url ) > 255 ) {
3411 return wfMsg( 'scarytranscludetoolong' );
3413 return $this->fetchScaryTemplateMaybeFromCache( $url );
3416 function fetchScaryTemplateMaybeFromCache( $url ) {
3417 global $wgTranscludeCacheExpiry;
3418 $dbr = wfGetDB( DB_SLAVE
);
3419 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3420 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3421 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3423 return $obj->tc_contents
;
3426 $text = Http
::get( $url );
3428 return wfMsg( 'scarytranscludefailed', $url );
3431 $dbw = wfGetDB( DB_MASTER
);
3432 $dbw->replace( 'transcache', array('tc_url'), array(
3434 'tc_time' => $dbw->timestamp( time() ),
3435 'tc_contents' => $text)
3442 * Triple brace replacement -- used for template arguments
3445 function argSubstitution( $piece, $frame ) {
3446 wfProfileIn( __METHOD__
);
3449 $parts = $piece['parts'];
3450 $nameWithSpaces = $frame->expand( $piece['title'] );
3451 $argName = trim( $nameWithSpaces );
3453 $text = $frame->getArgument( $argName );
3454 if ( $text === false && $parts->getLength() > 0
3458 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3461 # No match in frame, use the supplied default
3462 $object = $parts->item( 0 )->getChildren();
3464 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3465 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3466 $this->limitationWarn( 'post-expand-template-argument' );
3469 if ( $text === false && $object === false ) {
3471 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3473 if ( $error !== false ) {
3476 if ( $object !== false ) {
3477 $ret = array( 'object' => $object );
3479 $ret = array( 'text' => $text );
3482 wfProfileOut( __METHOD__
);
3487 * Return the text to be used for a given extension tag.
3488 * This is the ghost of strip().
3490 * @param $params Associative array of parameters:
3491 * name PPNode for the tag name
3492 * attr PPNode for unparsed text where tag attributes are thought to be
3493 * attributes Optional associative array of parsed attributes
3494 * inner Contents of extension element
3495 * noClose Original text did not have a close tag
3496 * @param $frame PPFrame
3498 function extensionSubstitution( $params, $frame ) {
3499 global $wgRawHtml, $wgContLang;
3501 $name = $frame->expand( $params['name'] );
3502 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3503 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3504 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3506 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3507 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3508 if ( $isFunctionTag ) {
3509 $markerType = 'none';
3511 $markerType = 'general';
3513 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3514 $name = strtolower( $name );
3515 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3516 if ( isset( $params['attributes'] ) ) {
3517 $attributes = $attributes +
$params['attributes'];
3520 if ( isset( $this->mTagHooks
[$name] ) ) {
3521 # Workaround for PHP bug 35229 and similar
3522 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3523 throw new MWException( "Tag hook for $name is not callable\n" );
3525 $output = call_user_func_array( $this->mTagHooks
[$name],
3526 array( $content, $attributes, $this, $frame ) );
3527 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3528 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3529 if ( !is_callable( $callback ) ) {
3530 throw new MWException( "Tag hook for $name is not callable\n" );
3533 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3535 $output = '<span class="error">Invalid tag extension name: ' .
3536 htmlspecialchars( $name ) . '</span>';
3539 if ( is_array( $output ) ) {
3540 # Extract flags to local scope (to override $markerType)
3542 $output = $flags[0];
3547 if ( is_null( $attrText ) ) {
3550 if ( isset( $params['attributes'] ) ) {
3551 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3552 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3553 htmlspecialchars( $attrValue ) . '"';
3556 if ( $content === null ) {
3557 $output = "<$name$attrText/>";
3559 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3560 $output = "<$name$attrText>$content$close";
3564 if ( $markerType === 'none' ) {
3566 } elseif ( $markerType === 'nowiki' ) {
3567 $this->mStripState
->nowiki
->setPair( $marker, $output );
3568 } elseif ( $markerType === 'general' ) {
3569 $this->mStripState
->general
->setPair( $marker, $output );
3571 throw new MWException( __METHOD__
.': invalid marker type' );
3577 * Increment an include size counter
3579 * @param $type String: the type of expansion
3580 * @param $size Integer: the size of the text
3581 * @return Boolean: false if this inclusion would take it over the maximum, true otherwise
3583 function incrementIncludeSize( $type, $size ) {
3584 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3587 $this->mIncludeSizes
[$type] +
= $size;
3593 * Increment the expensive function count
3595 * @return Boolean: false if the limit has been exceeded
3597 function incrementExpensiveFunctionCount() {
3598 global $wgExpensiveParserFunctionLimit;
3599 $this->mExpensiveFunctionCount++
;
3600 if ( $this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit ) {
3607 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3608 * Fills $this->mDoubleUnderscores, returns the modified text
3610 function doDoubleUnderscore( $text ) {
3611 wfProfileIn( __METHOD__
);
3613 # The position of __TOC__ needs to be recorded
3614 $mw = MagicWord
::get( 'toc' );
3615 if ( $mw->match( $text ) ) {
3616 $this->mShowToc
= true;
3617 $this->mForceTocPosition
= true;
3619 # Set a placeholder. At the end we'll fill it in with the TOC.
3620 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3622 # Only keep the first one.
3623 $text = $mw->replace( '', $text );
3626 # Now match and remove the rest of them
3627 $mwa = MagicWord
::getDoubleUnderscoreArray();
3628 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3630 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3631 $this->mOutput
->mNoGallery
= true;
3633 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3634 $this->mShowToc
= false;
3636 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3637 $this->addTrackingCategory( 'hidden-category-category' );
3639 # (bug 8068) Allow control over whether robots index a page.
3641 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3642 # is not desirable, the last one on the page should win.
3643 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3644 $this->mOutput
->setIndexPolicy( 'noindex' );
3645 $this->addTrackingCategory( 'noindex-category' );
3647 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3648 $this->mOutput
->setIndexPolicy( 'index' );
3649 $this->addTrackingCategory( 'index-category' );
3652 # Cache all double underscores in the database
3653 foreach ( $this->mDoubleUnderscores
as $key => $val ) {
3654 $this->mOutput
->setProperty( $key, '' );
3657 wfProfileOut( __METHOD__
);
3662 * Add a tracking category, getting the title from a system message,
3663 * or print a debug message if the title is invalid.
3665 * @param $msg String: message key
3666 * @return Boolean: whether the addition was successful
3668 protected function addTrackingCategory( $msg ) {
3669 $cat = wfMsgForContent( $msg );
3671 # Allow tracking categories to be disabled by setting them to "-"
3672 if ( $cat === '-' ) {
3676 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3677 if ( $containerCategory ) {
3678 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3681 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3687 * This function accomplishes several tasks:
3688 * 1) Auto-number headings if that option is enabled
3689 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3690 * 3) Add a Table of contents on the top for users who have enabled the option
3691 * 4) Auto-anchor headings
3693 * It loops through all headlines, collects the necessary data, then splits up the
3694 * string and re-inserts the newly formatted headlines.
3696 * @param $text String
3697 * @param $origText String: original, untouched wikitext
3698 * @param $isMain Boolean
3701 function formatHeadings( $text, $origText, $isMain=true ) {
3702 global $wgMaxTocLevel, $wgContLang, $wgHtml5, $wgExperimentalHtmlIds;
3704 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3705 $showEditLink = $this->mOptions
->getEditSection();
3707 # Do not call quickUserCan unless necessary
3708 if ( $showEditLink && !$this->mTitle
->quickUserCan( 'edit' ) ) {
3712 # Inhibit editsection links if requested in the page
3713 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ||
$this->mOptions
->getIsPrintable() ) {
3717 # Get all headlines for numbering them and adding funky stuff like [edit]
3718 # links - this is for later, but we need the number of headlines right now
3720 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3722 # if there are fewer than 4 headlines in the article, do not show TOC
3723 # unless it's been explicitly enabled.
3724 $enoughToc = $this->mShowToc
&&
3725 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
3727 # Allow user to stipulate that a page should have a "new section"
3728 # link added via __NEWSECTIONLINK__
3729 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3730 $this->mOutput
->setNewSection( true );
3733 # Allow user to remove the "new section"
3734 # link via __NONEWSECTIONLINK__
3735 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3736 $this->mOutput
->hideNewSection( true );
3739 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3740 # override above conditions and always show TOC above first header
3741 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3742 $this->mShowToc
= true;
3746 # We need this to perform operations on the HTML
3747 $sk = $this->mOptions
->getSkin();
3753 # Ugh .. the TOC should have neat indentation levels which can be
3754 # passed to the skin functions. These are determined here
3758 $sublevelCount = array();
3759 $levelCount = array();
3765 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3766 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3767 $oldType = $this->mOutputType
;
3768 $this->setOutputType( self
::OT_WIKI
);
3769 $frame = $this->getPreprocessor()->newFrame();
3770 $root = $this->preprocessToDom( $origText );
3771 $node = $root->getFirstChild();
3775 foreach ( $matches[3] as $headline ) {
3776 $isTemplate = false;
3778 $sectionIndex = false;
3780 $markerMatches = array();
3781 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
3782 $serial = $markerMatches[1];
3783 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3784 $isTemplate = ( $titleText != $baseTitleText );
3785 $headline = preg_replace( "/^$markerRegex/", "", $headline );
3789 $prevlevel = $level;
3790 $prevtoclevel = $toclevel;
3792 $level = $matches[1][$headlineCount];
3794 if ( $level > $prevlevel ) {
3795 # Increase TOC level
3797 $sublevelCount[$toclevel] = 0;
3798 if ( $toclevel<$wgMaxTocLevel ) {
3799 $prevtoclevel = $toclevel;
3800 $toc .= $sk->tocIndent();
3803 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
3804 # Decrease TOC level, find level to jump to
3806 for ( $i = $toclevel; $i > 0; $i-- ) {
3807 if ( $levelCount[$i] == $level ) {
3808 # Found last matching level
3811 } elseif ( $levelCount[$i] < $level ) {
3812 # Found first matching level below current level
3820 if ( $toclevel<$wgMaxTocLevel ) {
3821 if ( $prevtoclevel < $wgMaxTocLevel ) {
3822 # Unindent only if the previous toc level was shown :p
3823 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3824 $prevtoclevel = $toclevel;
3826 $toc .= $sk->tocLineEnd();
3830 # No change in level, end TOC line
3831 if ( $toclevel<$wgMaxTocLevel ) {
3832 $toc .= $sk->tocLineEnd();
3836 $levelCount[$toclevel] = $level;
3838 # count number of headlines for each level
3839 @$sublevelCount[$toclevel]++
;
3841 for( $i = 1; $i <= $toclevel; $i++
) {
3842 if ( !empty( $sublevelCount[$i] ) ) {
3846 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3851 # The safe header is a version of the header text safe to use for links
3852 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3853 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3855 # Remove link placeholders by the link text.
3856 # <!--LINK number-->
3858 # link text with suffix
3859 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3861 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3862 $tocline = preg_replace(
3863 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3864 array( '', '<$1>' ),
3867 $tocline = trim( $tocline );
3869 # For the anchor, strip out HTML-y stuff period
3870 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3871 $safeHeadline = Sanitizer
::normalizeSectionNameWhitespace( $safeHeadline );
3873 # Save headline for section edit hint before it's escaped
3874 $headlineHint = $safeHeadline;
3876 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
3877 # For reverse compatibility, provide an id that's
3878 # HTML4-compatible, like we used to.
3880 # It may be worth noting, academically, that it's possible for
3881 # the legacy anchor to conflict with a non-legacy headline
3882 # anchor on the page. In this case likely the "correct" thing
3883 # would be to either drop the legacy anchors or make sure
3884 # they're numbered first. However, this would require people
3885 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3886 # manually, so let's not bother worrying about it.
3887 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
3888 array( 'noninitial', 'legacy' ) );
3889 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3891 if ( $legacyHeadline == $safeHeadline ) {
3892 # No reason to have both (in fact, we can't)
3893 $legacyHeadline = false;
3896 $legacyHeadline = false;
3897 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
3901 # HTML names must be case-insensitively unique (bug 10721). FIXME:
3902 # Does this apply to Unicode characters? Because we aren't
3903 # handling those here.
3904 $arrayKey = strtolower( $safeHeadline );
3905 if ( $legacyHeadline === false ) {
3906 $legacyArrayKey = false;
3908 $legacyArrayKey = strtolower( $legacyHeadline );
3911 # count how many in assoc. array so we can track dupes in anchors
3912 if ( isset( $refers[$arrayKey] ) ) {
3913 $refers[$arrayKey]++
;
3915 $refers[$arrayKey] = 1;
3917 if ( isset( $refers[$legacyArrayKey] ) ) {
3918 $refers[$legacyArrayKey]++
;
3920 $refers[$legacyArrayKey] = 1;
3923 # Don't number the heading if it is the only one (looks silly)
3924 if ( $doNumberHeadings && count( $matches[3] ) > 1) {
3925 # the two are different if the line contains a link
3926 $headline = $numbering . ' ' . $headline;
3929 # Create the anchor for linking from the TOC to the section
3930 $anchor = $safeHeadline;
3931 $legacyAnchor = $legacyHeadline;
3932 if ( $refers[$arrayKey] > 1 ) {
3933 $anchor .= '_' . $refers[$arrayKey];
3935 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3936 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3938 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
3939 $toc .= $sk->tocLine( $anchor, $tocline,
3940 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
3943 # Add the section to the section tree
3944 # Find the DOM node for this header
3945 while ( $node && !$isTemplate ) {
3946 if ( $node->getName() === 'h' ) {
3947 $bits = $node->splitHeading();
3948 if ( $bits['i'] == $sectionIndex )
3951 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
3952 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
3953 $node = $node->getNextSibling();
3956 'toclevel' => $toclevel,
3959 'number' => $numbering,
3960 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
3961 'fromtitle' => $titleText,
3962 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
3963 'anchor' => $anchor,
3966 # give headline the correct <h#> tag
3967 if ( $showEditLink && $sectionIndex !== false ) {
3968 if ( $isTemplate ) {
3969 # Put a T flag in the section identifier, to indicate to extractSections()
3970 # that sections inside <includeonly> should be counted.
3971 $editlink = $sk->doEditSectionLink( Title
::newFromText( $titleText ), "T-$sectionIndex" );
3973 $editlink = $sk->doEditSectionLink( $this->mTitle
, $sectionIndex, $headlineHint );
3978 $head[$headlineCount] = $sk->makeHeadline( $level,
3979 $matches['attrib'][$headlineCount], $anchor, $headline,
3980 $editlink, $legacyAnchor );
3985 $this->setOutputType( $oldType );
3987 # Never ever show TOC if no headers
3988 if ( $numVisible < 1 ) {
3993 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3994 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3996 $toc = $sk->tocList( $toc );
3997 $this->mOutput
->setTOCHTML( $toc );
4001 $this->mOutput
->setSections( $tocraw );
4004 # split up and insert constructed headlines
4006 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
4009 foreach ( $blocks as $block ) {
4010 if ( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
4011 # This is the [edit] link that appears for the top block of text when
4012 # section editing is enabled
4014 # Disabled because it broke block formatting
4015 # For example, a bullet point in the top line
4016 # $full .= $sk->editSectionLink(0);
4019 if ( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
4020 # Top anchor now in skin
4024 if ( !empty( $head[$i] ) ) {
4029 if ( $this->mForceTocPosition
) {
4030 return str_replace( '<!--MWTOC-->', $toc, $full );
4037 * Merge $tree2 into $tree1 by replacing the section with index
4038 * $section in $tree1 and its descendants with the sections in $tree2.
4039 * Note that in the returned section tree, only the 'index' and
4040 * 'byteoffset' fields are guaranteed to be correct.
4042 * @param $tree1 Array: section tree from ParserOutput::getSectons()
4043 * @param $tree2 Array: section tree
4044 * @param $section Integer: section index
4045 * @param $title Title: Title both section trees come from
4046 * @param $len2 Integer: length of the original wikitext for $tree2
4047 * @return Array: merged section tree
4049 public static function mergeSectionTrees( $tree1, $tree2, $section, $title, $len2 ) {
4052 $targetLevel = false;
4056 $numbering = array( 0 );
4057 $titletext = $title->getPrefixedDBkey();
4058 foreach ( $tree1 as $s ) {
4059 if ( $targetLevel !== false ) {
4060 if ( $s['level'] <= $targetLevel ) {
4061 # We've skipped enough
4062 $targetLevel = false;
4067 if ( $s['index'] != $section ||
4068 $s['fromtitle'] != $titletext ) {
4069 self
::incrementNumbering( $numbering,
4070 $s['toclevel'], $lastLevel );
4072 # Rewrite index, byteoffset and number
4073 if ( $s['fromtitle'] == $titletext ) {
4074 $s['index'] = $nextIndex++
;
4076 $s['byteoffset'] +
= $len2;
4079 $s['number'] = implode( '.', array_map(
4080 array( $wgContLang, 'formatnum' ),
4082 $lastLevel = $s['toclevel'];
4086 # Insert sections from $tree2 here
4087 foreach ( $tree2 as $s2 ) {
4088 # Rewrite the fields in $s2
4089 # before inserting it
4090 $s2['toclevel'] +
= $s['toclevel'] - 1;
4091 $s2['level'] +
= $s['level'] - 1;
4092 $s2['index'] = $nextIndex++
;
4093 $s2['byteoffset'] +
= $s['byteoffset'];
4095 self
::incrementNumbering( $numbering,
4096 $s2['toclevel'], $lastLevel );
4097 $s2['number'] = implode( '.', array_map(
4098 array( $wgContLang, 'formatnum' ),
4100 $lastLevel = $s2['toclevel'];
4103 # Skip all descendants of $section in $tree1
4104 $targetLevel = $s['level'];
4112 * Increment a section number. Helper function for mergeSectionTrees()
4114 * @param $number Array representing a section number
4115 * @param $level Integer: current TOC level (depth)
4116 * @param $lastLevel Integer: level of previous TOC entry
4118 private static function incrementNumbering( &$number, $level, $lastLevel ) {
4119 if ( $level > $lastLevel ) {
4120 $number[$level - 1] = 1;
4121 } elseif ( $level < $lastLevel ) {
4122 foreach ( $number as $key => $unused )
4123 if ( $key >= $level ) {
4124 unset( $number[$key] );
4126 $number[$level - 1]++
;
4128 $number[$level - 1]++
;
4133 * Transform wiki markup when saving a page by doing \r\n -> \n
4134 * conversion, substitting signatures, {{subst:}} templates, etc.
4136 * @param $text String: the text to transform
4137 * @param &$title Title: the Title object for the current article
4138 * @param $user User: the User object describing the current user
4139 * @param $options ParserOptions: parsing options
4140 * @param $clearState Boolean: whether to clear the parser state first
4141 * @return String: the altered wiki markup
4143 public function preSaveTransform( $text, Title
$title, $user, $options, $clearState = true ) {
4144 $this->mOptions
= $options;
4145 $this->setTitle( $title );
4146 $this->setOutputType( self
::OT_WIKI
);
4148 if ( $clearState ) {
4149 $this->clearState();
4155 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4156 $text = $this->pstPass2( $text, $user );
4157 $text = $this->mStripState
->unstripBoth( $text );
4162 * Pre-save transform helper function
4165 function pstPass2( $text, $user ) {
4166 global $wgContLang, $wgLocaltimezone;
4168 # Note: This is the timestamp saved as hardcoded wikitext to
4169 # the database, we use $wgContLang here in order to give
4170 # everyone the same signature and use the default one rather
4171 # than the one selected in each user's preferences.
4172 # (see also bug 12815)
4173 $ts = $this->mOptions
->getTimestamp();
4174 if ( isset( $wgLocaltimezone ) ) {
4175 $tz = $wgLocaltimezone;
4177 $tz = date_default_timezone_get();
4180 $unixts = wfTimestamp( TS_UNIX
, $ts );
4181 $oldtz = date_default_timezone_get();
4182 date_default_timezone_set( $tz );
4183 $ts = date( 'YmdHis', $unixts );
4184 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4186 # Allow translation of timezones through wiki. date() can return
4187 # whatever crap the system uses, localised or not, so we cannot
4188 # ship premade translations.
4189 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4190 $value = wfMsgForContent( $key );
4191 if ( !wfEmptyMsg( $key, $value ) ) {
4195 date_default_timezone_set( $oldtz );
4197 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4199 # Variable replacement
4200 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4201 $text = $this->replaceVariables( $text );
4204 $sigText = $this->getUserSig( $user );
4205 $text = strtr( $text, array(
4207 '~~~~' => "$sigText $d",
4211 # Context links: [[|name]] and [[name (context)|]]
4212 global $wgLegalTitleChars;
4213 $tc = "[$wgLegalTitleChars]";
4214 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4216 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4217 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
4218 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4219 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4221 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4222 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4223 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4224 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4226 $t = $this->mTitle
->getText();
4228 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4229 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4230 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4231 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4233 # if there's no context, don't bother duplicating the title
4234 $text = preg_replace( $p2, '[[\\1]]', $text );
4237 # Trim trailing whitespace
4238 $text = rtrim( $text );
4244 * Fetch the user's signature text, if any, and normalize to
4245 * validated, ready-to-insert wikitext.
4246 * If you have pre-fetched the nickname or the fancySig option, you can
4247 * specify them here to save a database query.
4250 * @param $nickname String: nickname to use or false to use user's default nickname
4251 * @param $fancySig Boolean: whether the nicknname is the complete signature
4252 * or null to use default value
4255 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4256 global $wgMaxSigChars;
4258 $username = $user->getName();
4260 # If not given, retrieve from the user object.
4261 if ( $nickname === false )
4262 $nickname = $user->getOption( 'nickname' );
4264 if ( is_null( $fancySig ) ) {
4265 $fancySig = $user->getBoolOption( 'fancysig' );
4268 $nickname = $nickname == null ?
$username : $nickname;
4270 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4271 $nickname = $username;
4272 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4273 } elseif ( $fancySig !== false ) {
4274 # Sig. might contain markup; validate this
4275 if ( $this->validateSig( $nickname ) !== false ) {
4276 # Validated; clean up (if needed) and return it
4277 return $this->cleanSig( $nickname, true );
4279 # Failed to validate; fall back to the default
4280 $nickname = $username;
4281 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4285 # Make sure nickname doesnt get a sig in a sig
4286 $nickname = $this->cleanSigInSig( $nickname );
4288 # If we're still here, make it a link to the user page
4289 $userText = wfEscapeWikiText( $username );
4290 $nickText = wfEscapeWikiText( $nickname );
4291 if ( $user->isAnon() ) {
4292 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4294 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4299 * Check that the user's signature contains no bad XML
4301 * @param $text String
4302 * @return mixed An expanded string, or false if invalid.
4304 function validateSig( $text ) {
4305 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4309 * Clean up signature text
4311 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4312 * 2) Substitute all transclusions
4314 * @param $text String
4315 * @param $parsing Whether we're cleaning (preferences save) or parsing
4316 * @return String: signature text
4318 function cleanSig( $text, $parsing = false ) {
4321 $this->clearState();
4322 $this->setTitle( $wgTitle );
4323 $this->mOptions
= new ParserOptions
;
4324 $this->setOutputType
= self
::OT_PREPROCESS
;
4327 # Option to disable this feature
4328 if ( !$this->mOptions
->getCleanSignatures() ) {
4332 # FIXME: regex doesn't respect extension tags or nowiki
4333 # => Move this logic to braceSubstitution()
4334 $substWord = MagicWord
::get( 'subst' );
4335 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4336 $substText = '{{' . $substWord->getSynonym( 0 );
4338 $text = preg_replace( $substRegex, $substText, $text );
4339 $text = $this->cleanSigInSig( $text );
4340 $dom = $this->preprocessToDom( $text );
4341 $frame = $this->getPreprocessor()->newFrame();
4342 $text = $frame->expand( $dom );
4345 $text = $this->mStripState
->unstripBoth( $text );
4352 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4354 * @param $text String
4355 * @return String: signature text with /~{3,5}/ removed
4357 function cleanSigInSig( $text ) {
4358 $text = preg_replace( '/~{3,5}/', '', $text );
4363 * Set up some variables which are usually set up in parse()
4364 * so that an external function can call some class members with confidence
4366 public function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
4367 $this->setTitle( $title );
4368 $this->mOptions
= $options;
4369 $this->setOutputType( $outputType );
4370 if ( $clearState ) {
4371 $this->clearState();
4376 * Wrapper for preprocess()
4378 * @param $text String: the text to preprocess
4379 * @param $options ParserOptions: options
4382 public function transformMsg( $text, $options ) {
4384 static $executing = false;
4386 # Guard against infinite recursion
4392 wfProfileIn( __METHOD__
);
4393 $text = $this->preprocess( $text, $wgTitle, $options );
4396 wfProfileOut( __METHOD__
);
4401 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4402 * The callback should have the following form:
4403 * function myParserHook( $text, $params, $parser ) { ... }
4405 * Transform and return $text. Use $parser for any required context, e.g. use
4406 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4408 * @param $tag Mixed: the tag to use, e.g. 'hook' for <hook>
4409 * @param $callback Mixed: the callback function (and object) to use for the tag
4410 * @return The old value of the mTagHooks array associated with the hook
4412 public function setHook( $tag, $callback ) {
4413 $tag = strtolower( $tag );
4414 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4415 $this->mTagHooks
[$tag] = $callback;
4416 if ( !in_array( $tag, $this->mStripList
) ) {
4417 $this->mStripList
[] = $tag;
4423 function setTransparentTagHook( $tag, $callback ) {
4424 $tag = strtolower( $tag );
4425 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4426 $this->mTransparentTagHooks
[$tag] = $callback;
4432 * Remove all tag hooks
4434 function clearTagHooks() {
4435 $this->mTagHooks
= array();
4436 $this->mStripList
= $this->mDefaultStripList
;
4440 * Create a function, e.g. {{sum:1|2|3}}
4441 * The callback function should have the form:
4442 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4444 * Or with SFH_OBJECT_ARGS:
4445 * function myParserFunction( $parser, $frame, $args ) { ... }
4447 * The callback may either return the text result of the function, or an array with the text
4448 * in element 0, and a number of flags in the other elements. The names of the flags are
4449 * specified in the keys. Valid flags are:
4450 * found The text returned is valid, stop processing the template. This
4452 * nowiki Wiki markup in the return value should be escaped
4453 * isHTML The returned text is HTML, armour it against wikitext transformation
4455 * @param $id String: The magic word ID
4456 * @param $callback Mixed: the callback function (and object) to use
4457 * @param $flags Integer: a combination of the following flags:
4458 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4460 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4461 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4462 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4463 * the arguments, and to control the way they are expanded.
4465 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4466 * arguments, for instance:
4467 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4469 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4470 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4471 * working if/when this is changed.
4473 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4476 * Please read the documentation in includes/parser/Preprocessor.php for more information
4477 * about the methods available in PPFrame and PPNode.
4479 * @return The old callback function for this name, if any
4481 public function setFunctionHook( $id, $callback, $flags = 0 ) {
4484 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4485 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4487 # Add to function cache
4488 $mw = MagicWord
::get( $id );
4490 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4492 $synonyms = $mw->getSynonyms();
4493 $sensitive = intval( $mw->isCaseSensitive() );
4495 foreach ( $synonyms as $syn ) {
4497 if ( !$sensitive ) {
4498 $syn = $wgContLang->lc( $syn );
4501 if ( !( $flags & SFH_NO_HASH
) ) {
4504 # Remove trailing colon
4505 if ( substr( $syn, -1, 1 ) === ':' ) {
4506 $syn = substr( $syn, 0, -1 );
4508 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4514 * Get all registered function hook identifiers
4518 function getFunctionHooks() {
4519 return array_keys( $this->mFunctionHooks
);
4523 * Create a tag function, e.g. <test>some stuff</test>.
4524 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4525 * Unlike parser functions, their content is not preprocessed.
4527 function setFunctionTagHook( $tag, $callback, $flags ) {
4528 $tag = strtolower( $tag );
4529 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4530 $this->mFunctionTagHooks
[$tag] : null;
4531 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4533 if ( !in_array( $tag, $this->mStripList
) ) {
4534 $this->mStripList
[] = $tag;
4541 * FIXME: update documentation. makeLinkObj() is deprecated.
4542 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4543 * Placeholders created in Skin::makeLinkObj()
4544 * Returns an array of link CSS classes, indexed by PDBK.
4546 function replaceLinkHolders( &$text, $options = 0 ) {
4547 return $this->mLinkHolders
->replace( $text );
4551 * Replace <!--LINK--> link placeholders with plain text of links
4552 * (not HTML-formatted).
4554 * @param $text String
4557 function replaceLinkHoldersText( $text ) {
4558 return $this->mLinkHolders
->replaceText( $text );
4562 * Renders an image gallery from a text with one line per image.
4563 * text labels may be given by using |-style alternative text. E.g.
4564 * Image:one.jpg|The number "1"
4565 * Image:tree.jpg|A tree
4566 * given as text will return the HTML of a gallery with two images,
4567 * labeled 'The number "1"' and
4570 function renderImageGallery( $text, $params ) {
4571 $ig = new ImageGallery();
4572 $ig->setContextTitle( $this->mTitle
);
4573 $ig->setShowBytes( false );
4574 $ig->setShowFilename( false );
4575 $ig->setParser( $this );
4576 $ig->setHideBadImages();
4577 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4578 $ig->useSkin( $this->mOptions
->getSkin() );
4579 $ig->mRevisionId
= $this->mRevisionId
;
4581 if ( isset( $params['showfilename'] ) ) {
4582 $ig->setShowFilename( true );
4584 $ig->setShowFilename( false );
4586 if ( isset( $params['caption'] ) ) {
4587 $caption = $params['caption'];
4588 $caption = htmlspecialchars( $caption );
4589 $caption = $this->replaceInternalLinks( $caption );
4590 $ig->setCaptionHtml( $caption );
4592 if ( isset( $params['perrow'] ) ) {
4593 $ig->setPerRow( $params['perrow'] );
4595 if ( isset( $params['widths'] ) ) {
4596 $ig->setWidths( $params['widths'] );
4598 if ( isset( $params['heights'] ) ) {
4599 $ig->setHeights( $params['heights'] );
4602 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4604 $lines = StringUtils
::explode( "\n", $text );
4605 foreach ( $lines as $line ) {
4606 # match lines like these:
4607 # Image:someimage.jpg|This is some image
4609 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4611 if ( count( $matches ) == 0 ) {
4615 if ( strpos( $matches[0], '%' ) !== false ) {
4616 $matches[1] = urldecode( $matches[1] );
4618 $tp = Title
::newFromText( $matches[1] );
4620 if ( is_null( $nt ) ) {
4621 # Bogus title. Ignore these so we don't bomb out later.
4624 if ( isset( $matches[3] ) ) {
4625 $label = $matches[3];
4630 $html = $this->recursiveTagParse( trim( $label ) );
4632 $ig->add( $nt, $html );
4634 # Only add real images (bug #5586)
4635 if ( $nt->getNamespace() == NS_FILE
) {
4636 $this->mOutput
->addImage( $nt->getDBkey() );
4639 return $ig->toHTML();
4642 function getImageParams( $handler ) {
4644 $handlerClass = get_class( $handler );
4648 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4649 # Initialise static lists
4650 static $internalParamNames = array(
4651 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4652 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4653 'bottom', 'text-bottom' ),
4654 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4655 'upright', 'border', 'link', 'alt' ),
4657 static $internalParamMap;
4658 if ( !$internalParamMap ) {
4659 $internalParamMap = array();
4660 foreach ( $internalParamNames as $type => $names ) {
4661 foreach ( $names as $name ) {
4662 $magicName = str_replace( '-', '_', "img_$name" );
4663 $internalParamMap[$magicName] = array( $type, $name );
4668 # Add handler params
4669 $paramMap = $internalParamMap;
4671 $handlerParamMap = $handler->getParamMap();
4672 foreach ( $handlerParamMap as $magic => $paramName ) {
4673 $paramMap[$magic] = array( 'handler', $paramName );
4676 $this->mImageParams
[$handlerClass] = $paramMap;
4677 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4679 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4683 * Parse image options text and use it to make an image
4685 * @param $title Title
4686 * @param $options String
4687 * @param $holders LinkHolderArray
4689 function makeImage( $title, $options, $holders = false ) {
4690 # Check if the options text is of the form "options|alt text"
4692 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4693 # * left no resizing, just left align. label is used for alt= only
4694 # * right same, but right aligned
4695 # * none same, but not aligned
4696 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4697 # * center center the image
4698 # * frame Keep original image size, no magnify-button.
4699 # * framed Same as "frame"
4700 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4701 # * upright reduce width for upright images, rounded to full __0 px
4702 # * border draw a 1px border around the image
4703 # * alt Text for HTML alt attribute (defaults to empty)
4704 # * link Set the target of the image link. Can be external, interwiki, or local
4705 # vertical-align values (no % or length right now):
4715 $parts = StringUtils
::explode( "|", $options );
4716 $sk = $this->mOptions
->getSkin();
4718 # Give extensions a chance to select the file revision for us
4719 $skip = $time = $descQuery = false;
4720 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4723 return $sk->link( $title );
4727 $imagename = $title->getDBkey();
4728 $file = wfFindFile( $title, array( 'time' => $time ) );
4730 $handler = $file ?
$file->getHandler() : false;
4732 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4734 # Process the input parameters
4736 $params = array( 'frame' => array(), 'handler' => array(),
4737 'horizAlign' => array(), 'vertAlign' => array() );
4738 foreach ( $parts as $part ) {
4739 $part = trim( $part );
4740 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4742 if ( isset( $paramMap[$magicName] ) ) {
4743 list( $type, $paramName ) = $paramMap[$magicName];
4745 # Special case; width and height come in one variable together
4746 if ( $type === 'handler' && $paramName === 'width' ) {
4748 # (bug 13500) In both cases (width/height and width only),
4749 # permit trailing "px" for backward compatibility.
4750 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4751 $width = intval( $m[1] );
4752 $height = intval( $m[2] );
4753 if ( $handler->validateParam( 'width', $width ) ) {
4754 $params[$type]['width'] = $width;
4757 if ( $handler->validateParam( 'height', $height ) ) {
4758 $params[$type]['height'] = $height;
4761 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4762 $width = intval( $value );
4763 if ( $handler->validateParam( 'width', $width ) ) {
4764 $params[$type]['width'] = $width;
4767 } # else no validation -- bug 13436
4769 if ( $type === 'handler' ) {
4770 # Validate handler parameter
4771 $validated = $handler->validateParam( $paramName, $value );
4773 # Validate internal parameters
4774 switch( $paramName ) {
4777 # @todo Fixme: possibly check validity here for
4778 # manualthumb? downstream behavior seems odd with
4779 # missing manual thumbs.
4781 $value = $this->stripAltText( $value, $holders );
4784 $chars = self
::EXT_LINK_URL_CLASS
;
4785 $prots = $this->mUrlProtocols
;
4786 if ( $value === '' ) {
4787 $paramName = 'no-link';
4790 } elseif ( preg_match( "/^$prots/", $value ) ) {
4791 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4792 $paramName = 'link-url';
4793 $this->mOutput
->addExternalLink( $value );
4797 $linkTitle = Title
::newFromText( $value );
4799 $paramName = 'link-title';
4800 $value = $linkTitle;
4801 $this->mOutput
->addLink( $linkTitle );
4807 # Most other things appear to be empty or numeric...
4808 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4813 $params[$type][$paramName] = $value;
4817 if ( !$validated ) {
4822 # Process alignment parameters
4823 if ( $params['horizAlign'] ) {
4824 $params['frame']['align'] = key( $params['horizAlign'] );
4826 if ( $params['vertAlign'] ) {
4827 $params['frame']['valign'] = key( $params['vertAlign'] );
4830 $params['frame']['caption'] = $caption;
4832 # Will the image be presented in a frame, with the caption below?
4833 $imageIsFramed = isset( $params['frame']['frame'] ) ||
4834 isset( $params['frame']['framed'] ) ||
4835 isset( $params['frame']['thumbnail'] ) ||
4836 isset( $params['frame']['manualthumb'] );
4838 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4839 # came to also set the caption, ordinary text after the image -- which
4840 # makes no sense, because that just repeats the text multiple times in
4841 # screen readers. It *also* came to set the title attribute.
4843 # Now that we have an alt attribute, we should not set the alt text to
4844 # equal the caption: that's worse than useless, it just repeats the
4845 # text. This is the framed/thumbnail case. If there's no caption, we
4846 # use the unnamed parameter for alt text as well, just for the time be-
4847 # ing, if the unnamed param is set and the alt param is not.
4849 # For the future, we need to figure out if we want to tweak this more,
4850 # e.g., introducing a title= parameter for the title; ignoring the un-
4851 # named parameter entirely for images without a caption; adding an ex-
4852 # plicit caption= parameter and preserving the old magic unnamed para-
4854 if ( $imageIsFramed ) { # Framed image
4855 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
4856 # No caption or alt text, add the filename as the alt text so
4857 # that screen readers at least get some description of the image
4858 $params['frame']['alt'] = $title->getText();
4860 # Do not set $params['frame']['title'] because tooltips don't make sense
4862 } else { # Inline image
4863 if ( !isset( $params['frame']['alt'] ) ) {
4864 # No alt text, use the "caption" for the alt text
4865 if ( $caption !== '') {
4866 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
4868 # No caption, fall back to using the filename for the
4870 $params['frame']['alt'] = $title->getText();
4873 # Use the "caption" for the tooltip text
4874 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4877 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4879 # Linker does the rest
4880 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4882 # Give the handler a chance to modify the parser object
4884 $handler->parserTransformHook( $this, $file );
4890 protected function stripAltText( $caption, $holders ) {
4891 # Strip bad stuff out of the title (tooltip). We can't just use
4892 # replaceLinkHoldersText() here, because if this function is called
4893 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4895 $tooltip = $holders->replaceText( $caption );
4897 $tooltip = $this->replaceLinkHoldersText( $caption );
4900 # make sure there are no placeholders in thumbnail attributes
4901 # that are later expanded to html- so expand them now and
4903 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
4904 $tooltip = Sanitizer
::stripAllTags( $tooltip );
4910 * Set a flag in the output object indicating that the content is dynamic and
4911 * shouldn't be cached.
4913 function disableCache() {
4914 wfDebug( "Parser output marked as uncacheable.\n" );
4915 $this->mOutput
->setCacheTime( -1 ); // old style, for compatibility
4916 $this->mOutput
->updateCacheExpiry( 0 ); // new style, for consistency
4920 * Callback from the Sanitizer for expanding items found in HTML attribute
4921 * values, so they can be safely tested and escaped.
4923 * @param $text String
4924 * @param $frame PPFrame
4928 function attributeStripCallback( &$text, $frame = false ) {
4929 $text = $this->replaceVariables( $text, $frame );
4930 $text = $this->mStripState
->unstripBoth( $text );
4937 function getTags() {
4938 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) );
4942 * Break wikitext input into sections, and either pull or replace
4943 * some particular section's text.
4945 * External callers should use the getSection and replaceSection methods.
4947 * @param $text String: Page wikitext
4948 * @param $section String: a section identifier string of the form:
4949 * <flag1> - <flag2> - ... - <section number>
4951 * Currently the only recognised flag is "T", which means the target section number
4952 * was derived during a template inclusion parse, in other words this is a template
4953 * section edit link. If no flags are given, it was an ordinary section edit link.
4954 * This flag is required to avoid a section numbering mismatch when a section is
4955 * enclosed by <includeonly> (bug 6563).
4957 * The section number 0 pulls the text before the first heading; other numbers will
4958 * pull the given section along with its lower-level subsections. If the section is
4959 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4961 * @param $mode String: one of "get" or "replace"
4962 * @param $newText String: replacement text for section data.
4963 * @return String: for "get", the extracted section text.
4964 * for "replace", the whole page with the section replaced.
4966 private function extractSections( $text, $section, $mode, $newText='' ) {
4968 $this->clearState();
4969 $this->setTitle( $wgTitle ); # not generally used but removes an ugly failure mode
4970 $this->mOptions
= new ParserOptions
;
4971 $this->setOutputType( self
::OT_PLAIN
);
4973 $frame = $this->getPreprocessor()->newFrame();
4975 # Process section extraction flags
4977 $sectionParts = explode( '-', $section );
4978 $sectionIndex = array_pop( $sectionParts );
4979 foreach ( $sectionParts as $part ) {
4980 if ( $part === 'T' ) {
4981 $flags |
= self
::PTD_FOR_INCLUSION
;
4984 # Preprocess the text
4985 $root = $this->preprocessToDom( $text, $flags );
4987 # <h> nodes indicate section breaks
4988 # They can only occur at the top level, so we can find them by iterating the root's children
4989 $node = $root->getFirstChild();
4991 # Find the target section
4992 if ( $sectionIndex == 0 ) {
4993 # Section zero doesn't nest, level=big
4994 $targetLevel = 1000;
4997 if ( $node->getName() === 'h' ) {
4998 $bits = $node->splitHeading();
4999 if ( $bits['i'] == $sectionIndex ) {
5000 $targetLevel = $bits['level'];
5004 if ( $mode === 'replace' ) {
5005 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5007 $node = $node->getNextSibling();
5013 if ( $mode === 'get' ) {
5020 # Find the end of the section, including nested sections
5022 if ( $node->getName() === 'h' ) {
5023 $bits = $node->splitHeading();
5024 $curLevel = $bits['level'];
5025 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
5029 if ( $mode === 'get' ) {
5030 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5032 $node = $node->getNextSibling();
5035 # Write out the remainder (in replace mode only)
5036 if ( $mode === 'replace' ) {
5037 # Output the replacement text
5038 # Add two newlines on -- trailing whitespace in $newText is conventionally
5039 # stripped by the editor, so we need both newlines to restore the paragraph gap
5040 # Only add trailing whitespace if there is newText
5041 if ( $newText != "" ) {
5042 $outText .= $newText . "\n\n";
5046 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
5047 $node = $node->getNextSibling();
5051 if ( is_string( $outText ) ) {
5052 # Re-insert stripped tags
5053 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
5060 * This function returns the text of a section, specified by a number ($section).
5061 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
5062 * the first section before any such heading (section 0).
5064 * If a section contains subsections, these are also returned.
5066 * @param $text String: text to look in
5067 * @param $section String: section identifier
5068 * @param $deftext String: default to return if section is not found
5069 * @return string text of the requested section
5071 public function getSection( $text, $section, $deftext='' ) {
5072 return $this->extractSections( $text, $section, "get", $deftext );
5075 public function replaceSection( $oldtext, $section, $text ) {
5076 return $this->extractSections( $oldtext, $section, "replace", $text );
5080 * Get the ID of the revision we are parsing
5082 * @return Mixed: integer or null
5084 function getRevisionId() {
5085 return $this->mRevisionId
;
5089 * Get the timestamp associated with the current revision, adjusted for
5090 * the default server-local timestamp
5092 function getRevisionTimestamp() {
5093 if ( is_null( $this->mRevisionTimestamp
) ) {
5094 wfProfileIn( __METHOD__
);
5096 $dbr = wfGetDB( DB_SLAVE
);
5097 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
5098 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
5100 # Normalize timestamp to internal MW format for timezone processing.
5101 # This has the added side-effect of replacing a null value with
5102 # the current time, which gives us more sensible behavior for
5104 $timestamp = wfTimestamp( TS_MW
, $timestamp );
5106 # The cryptic '' timezone parameter tells to use the site-default
5107 # timezone offset instead of the user settings.
5109 # Since this value will be saved into the parser cache, served
5110 # to other users, and potentially even used inside links and such,
5111 # it needs to be consistent for all visitors.
5112 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
5114 wfProfileOut( __METHOD__
);
5116 return $this->mRevisionTimestamp
;
5120 * Get the name of the user that edited the last revision
5122 * @return String: user name
5124 function getRevisionUser() {
5125 # if this template is subst: the revision id will be blank,
5126 # so just use the current user's name
5127 if ( $this->mRevisionId
) {
5128 $revision = Revision
::newFromId( $this->mRevisionId
);
5129 $revuser = $revision->getUserText();
5132 $revuser = $wgUser->getName();
5138 * Mutator for $mDefaultSort
5140 * @param $sort New value
5142 public function setDefaultSort( $sort ) {
5143 $this->mDefaultSort
= $sort;
5144 $this->mOutput
->setProperty( 'defaultsort', $sort );
5148 * Accessor for $mDefaultSort
5149 * Will use the title/prefixed title if none is set
5153 public function getDefaultSort() {
5154 global $wgCategoryPrefixedDefaultSortkey;
5155 if ( $this->mDefaultSort
!== false ) {
5156 return $this->mDefaultSort
;
5157 } elseif ( $this->mTitle
->getNamespace() == NS_CATEGORY ||
5158 !$wgCategoryPrefixedDefaultSortkey )
5160 return $this->mTitle
->getText();
5162 return $this->mTitle
->getPrefixedText();
5167 * Accessor for $mDefaultSort
5168 * Unlike getDefaultSort(), will return false if none is set
5170 * @return string or false
5172 public function getCustomDefaultSort() {
5173 return $this->mDefaultSort
;
5177 * Try to guess the section anchor name based on a wikitext fragment
5178 * presumably extracted from a heading, for example "Header" from
5181 public function guessSectionNameFromWikiText( $text ) {
5182 # Strip out wikitext links(they break the anchor)
5183 $text = $this->stripSectionName( $text );
5184 $text = Sanitizer
::normalizeSectionNameWhitespace( $text );
5185 return '#' . Sanitizer
::escapeId( $text, 'noninitial' );
5189 * Strips a text string of wikitext for use in a section anchor
5191 * Accepts a text string and then removes all wikitext from the
5192 * string and leaves only the resultant text (i.e. the result of
5193 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5194 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5195 * to create valid section anchors by mimicing the output of the
5196 * parser when headings are parsed.
5198 * @param $text String: text string to be stripped of wikitext
5199 * for use in a Section anchor
5200 * @return Filtered text string
5202 public function stripSectionName( $text ) {
5203 # Strip internal link markup
5204 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5205 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5207 # Strip external link markup (FIXME: Not Tolerant to blank link text
5208 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5209 # on how many empty links there are on the page - need to figure that out.
5210 $text = preg_replace( '/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5212 # Parse wikitext quotes (italics & bold)
5213 $text = $this->doQuotes( $text );
5216 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5220 function srvus( $text ) {
5221 return $this->testSrvus( $text, $this->mOutputType
);
5225 * strip/replaceVariables/unstrip for preprocessor regression testing
5227 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
5228 $this->clearState();
5229 if ( !$title instanceof Title
) {
5230 $title = Title
::newFromText( $title );
5232 $this->mTitle
= $title;
5233 $this->mOptions
= $options;
5234 $this->setOutputType( $outputType );
5235 $text = $this->replaceVariables( $text );
5236 $text = $this->mStripState
->unstripBoth( $text );
5237 $text = Sanitizer
::removeHTMLtags( $text );
5241 function testPst( $text, $title, $options ) {
5243 if ( !$title instanceof Title
) {
5244 $title = Title
::newFromText( $title );
5246 return $this->preSaveTransform( $text, $title, $wgUser, $options );
5249 function testPreprocess( $text, $title, $options ) {
5250 if ( !$title instanceof Title
) {
5251 $title = Title
::newFromText( $title );
5253 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5256 function markerSkipCallback( $s, $callback ) {
5259 while ( $i < strlen( $s ) ) {
5260 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5261 if ( $markerStart === false ) {
5262 $out .= call_user_func( $callback, substr( $s, $i ) );
5265 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5266 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5267 if ( $markerEnd === false ) {
5268 $out .= substr( $s, $markerStart );
5271 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5272 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5280 function serialiseHalfParsedText( $text ) {
5282 $data['text'] = $text;
5284 # First, find all strip markers, and store their
5286 $stripState = new StripState
;
5288 while ( ( $start_pos = strpos( $text, $this->mUniqPrefix
, $pos ) )
5289 && ( $end_pos = strpos( $text, self
::MARKER_SUFFIX
, $pos ) ) )
5291 $end_pos +
= strlen( self
::MARKER_SUFFIX
);
5292 $marker = substr( $text, $start_pos, $end_pos-$start_pos );
5294 if ( !empty( $this->mStripState
->general
->data
[$marker] ) ) {
5295 $replaceArray = $stripState->general
;
5296 $stripText = $this->mStripState
->general
->data
[$marker];
5297 } elseif ( !empty( $this->mStripState
->nowiki
->data
[$marker] ) ) {
5298 $replaceArray = $stripState->nowiki
;
5299 $stripText = $this->mStripState
->nowiki
->data
[$marker];
5301 throw new MWException( "Hanging strip marker: '$marker'." );
5304 $replaceArray->setPair( $marker, $stripText );
5307 $data['stripstate'] = $stripState;
5309 # Now, find all of our links, and store THEIR
5310 # data in an array! :)
5311 $links = array( 'internal' => array(), 'interwiki' => array() );
5315 while ( ( $start_pos = strpos( $text, '<!--LINK ', $pos ) ) ) {
5316 list( $ns, $trail ) = explode( ':', substr( $text, $start_pos +
strlen( '<!--LINK ' ) ), 2 );
5319 if ( empty( $links['internal'][$ns] ) ) {
5320 $links['internal'][$ns] = array();
5323 $key = trim( substr( $trail, 0, strpos( $trail, '-->' ) ) );
5324 $links['internal'][$ns][] = $this->mLinkHolders
->internals
[$ns][$key];
5325 $pos = $start_pos +
strlen( "<!--LINK $ns:$key-->" );
5331 while ( ( $start_pos = strpos( $text, '<!--IWLINK ', $pos ) ) ) {
5332 $data = substr( $text, $start_pos );
5333 $key = trim( substr( $data, 0, strpos( $data, '-->' ) ) );
5334 $links['interwiki'][] = $this->mLinkHolders
->interwiki
[$key];
5335 $pos = $start_pos +
strlen( "<!--IWLINK $key-->" );
5338 $data['linkholder'] = $links;
5345 * @param $data Array
5346 * @param $intPrefix String unique identifying prefix
5349 function unserialiseHalfParsedText( $data, $intPrefix = null ) {
5350 if ( !$intPrefix ) {
5351 $intPrefix = $this->getRandomString();
5354 # First, extract the strip state.
5355 $stripState = $data['stripstate'];
5356 $this->mStripState
->general
->merge( $stripState->general
);
5357 $this->mStripState
->nowiki
->merge( $stripState->nowiki
);
5359 # Now, extract the text, and renumber links
5360 $text = $data['text'];
5361 $links = $data['linkholder'];
5364 foreach ( $links['internal'] as $ns => $nsLinks ) {
5365 foreach ( $nsLinks as $key => $entry ) {
5366 $newKey = $intPrefix . '-' . $key;
5367 $this->mLinkHolders
->internals
[$ns][$newKey] = $entry;
5369 $text = str_replace( "<!--LINK $ns:$key-->", "<!--LINK $ns:$newKey-->", $text );
5374 foreach ( $links['interwiki'] as $key => $entry ) {
5375 $newKey = "$intPrefix-$key";
5376 $this->mLinkHolders
->interwikis
[$newKey] = $entry;
5378 $text = str_replace( "<!--IWLINK $key-->", "<!--IWLINK $newKey-->", $text );
5381 # Should be good to go.
5387 * @todo document, briefly.
5391 var $general, $nowiki;
5393 function __construct() {
5394 $this->general
= new ReplacementArray
;
5395 $this->nowiki
= new ReplacementArray
;
5398 function unstripGeneral( $text ) {
5399 wfProfileIn( __METHOD__
);
5402 $text = $this->general
->replace( $text );
5403 } while ( $text !== $oldText );
5404 wfProfileOut( __METHOD__
);
5408 function unstripNoWiki( $text ) {
5409 wfProfileIn( __METHOD__
);
5412 $text = $this->nowiki
->replace( $text );
5413 } while ( $text !== $oldText );
5414 wfProfileOut( __METHOD__
);
5418 function unstripBoth( $text ) {
5419 wfProfileIn( __METHOD__
);
5422 $text = $this->general
->replace( $text );
5423 $text = $this->nowiki
->replace( $text );
5424 } while ( $text !== $oldText );
5425 wfProfileOut( __METHOD__
);
5431 * @todo document, briefly.
5434 class OnlyIncludeReplacer
{
5437 function replace( $matches ) {
5438 if ( substr( $matches[1], -1 ) === "\n" ) {
5439 $this->output
.= substr( $matches[1], 0, -1 );
5441 $this->output
.= $matches[1];