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__
);
242 function setOutputType( $ot ) {
243 $this->mOutputType
= $ot;
246 'html' => $ot == self
::OT_HTML
,
247 'wiki' => $ot == self
::OT_WIKI
,
248 'pre' => $ot == self
::OT_PREPROCESS
,
249 'plain' => $ot == self
::OT_PLAIN
,
254 * Set the context title
256 function setTitle( $t ) {
257 if ( !$t ||
$t instanceof FakeTitle
) {
258 $t = Title
::newFromText( 'NO TITLE' );
261 if ( strval( $t->getFragment() ) !== '' ) {
262 # Strip the fragment to avoid various odd effects
263 $this->mTitle
= clone $t;
264 $this->mTitle
->setFragment( '' );
271 * Accessor for mUniqPrefix.
275 function uniqPrefix() {
276 if ( !isset( $this->mUniqPrefix
) ) {
277 # @todo Fixme: this is probably *horribly wrong*
278 # LanguageConverter seems to want $wgParser's uniqPrefix, however
279 # if this is called for a parser cache hit, the parser may not
280 # have ever been initialized in the first place.
281 # Not really sure what the heck is supposed to be going on here.
283 # throw new MWException( "Accessing uninitialized mUniqPrefix" );
285 return $this->mUniqPrefix
;
289 * Convert wikitext to HTML
290 * Do not call this function recursively.
292 * @param $text String: text we want to parse
293 * @param $title A title object
294 * @param $options ParserOptions
295 * @param $linestart boolean
296 * @param $clearState boolean
297 * @param $revid Int: number to pass in {{REVISIONID}}
298 * @return ParserOutput a ParserOutput
300 public function parse( $text, Title
$title, ParserOptions
$options, $linestart = true, $clearState = true, $revid = null ) {
302 * First pass--just handle <nowiki> sections, pass the rest off
303 * to internalParse() which does all the real work.
306 global $wgUseTidy, $wgAlwaysUseTidy, $wgContLang, $wgDisableLangConversion, $wgDisableTitleConversion;
307 $fname = __METHOD__
.'-' . wfGetCaller();
308 wfProfileIn( __METHOD__
);
309 wfProfileIn( $fname );
315 $this->mOptions
= $options;
316 $this->setTitle( $title ); # Page title has to be set for the pre-processor
318 $oldRevisionId = $this->mRevisionId
;
319 $oldRevisionTimestamp = $this->mRevisionTimestamp
;
320 if ( $revid !== null ) {
321 $this->mRevisionId
= $revid;
322 $this->mRevisionTimestamp
= null;
324 $this->setOutputType( self
::OT_HTML
);
325 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
327 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
328 $text = $this->internalParse( $text );
330 $text = $this->mStripState
->unstripGeneral( $text );
332 # Clean up special characters, only run once, next-to-last before doBlockLevels
334 # french spaces, last one Guillemet-left
335 # only if there is something before the space
336 '/(.) (?=\\?|:|;|!|%|\\302\\273)/' => '\\1 \\2',
337 # french spaces, Guillemet-right
338 '/(\\302\\253) /' => '\\1 ',
339 '/ (!\s*important)/' => ' \\1', # Beware of CSS magic word !important, bug #11874.
341 $text = preg_replace( array_keys( $fixtags ), array_values( $fixtags ), $text );
343 $text = $this->doBlockLevels( $text, $linestart );
345 $this->replaceLinkHolders( $text );
348 * The page doesn't get language converted if
350 * b) Content isn't converted
351 * c) It's a conversion table
353 if ( !( $wgDisableLangConversion
354 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
355 ||
$this->mTitle
->isConversionTable() ) ) {
357 # The position of the convert() call should not be changed. it
358 # assumes that the links are all replaced and the only thing left
359 # is the <nowiki> mark.
361 $text = $wgContLang->convert( $text );
365 * A page get its title converted except:
366 * a) Language conversion is globally disabled
367 * b) Title convert is globally disabled
368 * c) The page is a redirect page
369 * d) User request with a "linkconvert" set to "no"
370 * e) A "nocontentconvert" magic word has been set
371 * f) A "notitleconvert" magic word has been set
372 * g) User sets "noconvertlink" in his/her preference
374 * Note that if a user tries to set a title in a conversion
375 * rule but content conversion was not done, then the parser
376 * won't pick it up. This is probably expected behavior.
378 if ( !( $wgDisableLangConversion
379 ||
$wgDisableTitleConversion
380 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
381 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
382 ||
$this->mOutput
->getDisplayTitle() !== false ) )
384 $convruletitle = $wgContLang->getConvRuleTitle();
385 if ( $convruletitle ) {
386 $this->mOutput
->setTitleText( $convruletitle );
388 $titleText = $wgContLang->convertTitle( $title );
389 $this->mOutput
->setTitleText( $titleText );
393 $text = $this->mStripState
->unstripNoWiki( $text );
395 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
397 //!JF Move to its own function
399 $uniq_prefix = $this->mUniqPrefix
;
401 $elements = array_keys( $this->mTransparentTagHooks
);
402 $text = self
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
404 foreach ( $matches as $marker => $data ) {
405 list( $element, $content, $params, $tag ) = $data;
406 $tagName = strtolower( $element );
407 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
408 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
412 $this->mStripState
->general
->setPair( $marker, $output );
414 $text = $this->mStripState
->unstripGeneral( $text );
416 $text = Sanitizer
::normalizeCharReferences( $text );
418 if ( ( $wgUseTidy && $this->mOptions
->mTidy
) ||
$wgAlwaysUseTidy ) {
419 $text = MWTidy
::tidy( $text );
421 # attempt to sanitize at least some nesting problems
422 # (bug #2702 and quite a few others)
424 # ''Something [http://www.cool.com cool''] -->
425 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
426 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
427 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
428 # fix up an anchor inside another anchor, only
429 # at least for a single single nested link (bug 3695)
430 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
431 '\\1\\2</a>\\3</a>\\1\\4</a>',
432 # fix div inside inline elements- doBlockLevels won't wrap a line which
433 # contains a div, so fix it up here; replace
434 # div with escaped text
435 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
436 '\\1\\3<div\\5>\\6</div>\\8\\9',
437 # remove empty italic or bold tag pairs, some
438 # introduced by rules above
439 '/<([bi])><\/\\1>/' => '',
442 $text = preg_replace(
443 array_keys( $tidyregs ),
444 array_values( $tidyregs ),
447 global $wgExpensiveParserFunctionLimit;
448 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
449 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
452 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
454 # Information on include size limits, for the benefit of users who try to skirt them
455 if ( $this->mOptions
->getEnableLimitReport() ) {
456 $max = $this->mOptions
->getMaxIncludeSize();
457 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
459 "NewPP limit report\n" .
460 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
461 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
462 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
464 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
465 $text .= "\n<!-- \n$limitReport-->\n";
467 $this->mOutput
->setText( $text );
469 $this->mRevisionId
= $oldRevisionId;
470 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
471 wfProfileOut( $fname );
472 wfProfileOut( __METHOD__
);
474 return $this->mOutput
;
478 * Recursive parser entry point that can be called from an extension tag
481 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
483 * @param $text String: text extension wants to have parsed
484 * @param PPFrame $frame: The frame to use for expanding any template variables
486 function recursiveTagParse( $text, $frame=false ) {
487 wfProfileIn( __METHOD__
);
488 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
489 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
490 $text = $this->internalParse( $text, false, $frame );
491 wfProfileOut( __METHOD__
);
496 * Expand templates and variables in the text, producing valid, static wikitext.
497 * Also removes comments.
499 function preprocess( $text, $title, $options, $revid = null ) {
500 wfProfileIn( __METHOD__
);
502 $this->setOutputType( self
::OT_PREPROCESS
);
503 $this->mOptions
= $options;
504 $this->setTitle( $title );
505 if ( $revid !== null ) {
506 $this->mRevisionId
= $revid;
508 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
509 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
510 $text = $this->replaceVariables( $text );
511 $text = $this->mStripState
->unstripBoth( $text );
512 wfProfileOut( __METHOD__
);
517 * Process the wikitext for the ?preload= feature. (bug 5210)
519 * <noinclude>, <includeonly> etc. are parsed as for template transclusion,
520 * comments, templates, arguments, tags hooks and parser functions are untouched.
522 public function getPreloadText( $text, $title, $options ) {
523 # Parser (re)initialisation
525 $this->setOutputType( self
::OT_PLAIN
);
526 $this->mOptions
= $options;
527 $this->setTitle( $title );
529 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
530 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
531 return $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
535 * Get a random string
540 function getRandomString() {
541 return dechex( mt_rand( 0, 0x7fffffff ) ) . dechex( mt_rand( 0, 0x7fffffff ) );
544 function &getTitle() { return $this->mTitle
; }
545 function getOptions() { return $this->mOptions
; }
546 function getRevisionId() { return $this->mRevisionId
; }
547 function getOutput() { return $this->mOutput
; }
548 function nextLinkID() { return $this->mLinkID++
; }
550 function getFunctionLang() {
551 global $wgLang, $wgContLang;
553 $target = $this->mOptions
->getTargetLanguage();
554 if ( $target !== null ) {
557 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
562 * Get a preprocessor object
564 function getPreprocessor() {
565 if ( !isset( $this->mPreprocessor
) ) {
566 $class = $this->mPreprocessorClass
;
567 $this->mPreprocessor
= new $class( $this );
569 return $this->mPreprocessor
;
573 * Replaces all occurrences of HTML-style comments and the given tags
574 * in the text with a random marker and returns the next text. The output
575 * parameter $matches will be an associative array filled with data in
577 * 'UNIQ-xxxxx' => array(
580 * array( 'param' => 'x' ),
581 * '<element param="x">tag content</element>' ) )
583 * @param $elements list of element names. Comments are always extracted.
584 * @param $text Source text string.
585 * @param $uniq_prefix
590 function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
595 $taglist = implode( '|', $elements );
596 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
598 while ( $text != '' ) {
599 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
601 if ( count( $p ) < 5 ) {
604 if ( count( $p ) > 5 ) {
618 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
619 $stripped .= $marker;
621 if ( $close === '/>' ) {
622 # Empty element tag, <tag />
627 if ( $element === '!--' ) {
630 $end = "/(<\\/$element\\s*>)/i";
632 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
634 if ( count( $q ) < 3 ) {
635 # No end tag -- let it run out to the end of the text.
644 $matches[$marker] = array( $element,
646 Sanitizer
::decodeTagAttributes( $attributes ),
647 "<$element$attributes$close$content$tail" );
653 * Get a list of strippable XML-like elements
655 function getStripList() {
656 return $this->mStripList
;
660 * @deprecated use replaceVariables
662 function strip( $text, $state, $stripcomments = false , $dontstrip = array() ) {
667 * Restores pre, math, and other extensions removed by strip()
669 * always call unstripNoWiki() after this one
671 * @deprecated use $this->mStripState->unstrip()
673 function unstrip( $text, $state ) {
674 return $state->unstripGeneral( $text );
678 * Always call this after unstrip() to preserve the order
681 * @deprecated use $this->mStripState->unstrip()
683 function unstripNoWiki( $text, $state ) {
684 return $state->unstripNoWiki( $text );
688 * @deprecated use $this->mStripState->unstripBoth()
690 function unstripForHTML( $text ) {
691 return $this->mStripState
->unstripBoth( $text );
695 * Add an item to the strip state
696 * Returns the unique tag which must be inserted into the stripped text
697 * The tag will be replaced with the original text in unstrip()
701 function insertStripItem( $text ) {
702 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
703 $this->mMarkerIndex++
;
704 $this->mStripState
->general
->setPair( $rnd, $text );
709 * Interface with html tidy
710 * @deprecated Use MWTidy::tidy()
712 public static function tidy( $text ) {
713 wfDeprecated( __METHOD__
);
714 return MWTidy
::tidy( $text );
718 * parse the wiki syntax used to render tables
722 function doTableStuff( $text ) {
723 wfProfileIn( __METHOD__
);
725 $lines = StringUtils
::explode( "\n", $text );
727 $td_history = array(); # Is currently a td tag open?
728 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
729 $tr_history = array(); # Is currently a tr tag open?
730 $tr_attributes = array(); # history of tr attributes
731 $has_opened_tr = array(); # Did this table open a <tr> element?
732 $indent_level = 0; # indent level of the table
734 foreach ( $lines as $outLine ) {
735 $line = trim( $outLine );
737 if ( $line == '' ) { # empty line, go to next line
738 $out .= $outLine."\n";
741 $first_character = $line[0];
744 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
745 # First check if we are starting a new table
746 $indent_level = strlen( $matches[1] );
748 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
749 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
751 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
752 array_push( $td_history , false );
753 array_push( $last_tag_history , '' );
754 array_push( $tr_history , false );
755 array_push( $tr_attributes , '' );
756 array_push( $has_opened_tr , false );
757 } elseif ( count( $td_history ) == 0 ) {
758 # Don't do any of the following
759 $out .= $outLine."\n";
761 } elseif ( substr( $line , 0 , 2 ) === '|}' ) {
762 # We are ending a table
763 $line = '</table>' . substr( $line , 2 );
764 $last_tag = array_pop( $last_tag_history );
766 if ( !array_pop( $has_opened_tr ) ) {
767 $line = "<tr><td></td></tr>{$line}";
770 if ( array_pop( $tr_history ) ) {
771 $line = "</tr>{$line}";
774 if ( array_pop( $td_history ) ) {
775 $line = "</{$last_tag}>{$line}";
777 array_pop( $tr_attributes );
778 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
779 } elseif ( substr( $line , 0 , 2 ) === '|-' ) {
780 # Now we have a table row
781 $line = preg_replace( '#^\|-+#', '', $line );
783 # Whats after the tag is now only attributes
784 $attributes = $this->mStripState
->unstripBoth( $line );
785 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
786 array_pop( $tr_attributes );
787 array_push( $tr_attributes, $attributes );
790 $last_tag = array_pop( $last_tag_history );
791 array_pop( $has_opened_tr );
792 array_push( $has_opened_tr , true );
794 if ( array_pop( $tr_history ) ) {
798 if ( array_pop( $td_history ) ) {
799 $line = "</{$last_tag}>{$line}";
803 array_push( $tr_history , false );
804 array_push( $td_history , false );
805 array_push( $last_tag_history , '' );
806 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line , 0 , 2 ) === '|+' ) {
807 # This might be cell elements, td, th or captions
808 if ( substr( $line , 0 , 2 ) === '|+' ) {
809 $first_character = '+';
810 $line = substr( $line , 1 );
813 $line = substr( $line , 1 );
815 if ( $first_character === '!' ) {
816 $line = str_replace( '!!' , '||' , $line );
819 # Split up multiple cells on the same line.
820 # FIXME : This can result in improper nesting of tags processed
821 # by earlier parser steps, but should avoid splitting up eg
822 # attribute values containing literal "||".
823 $cells = StringUtils
::explodeMarkup( '||' , $line );
827 # Loop through each table cell
828 foreach ( $cells as $cell ) {
830 if ( $first_character !== '+' ) {
831 $tr_after = array_pop( $tr_attributes );
832 if ( !array_pop( $tr_history ) ) {
833 $previous = "<tr{$tr_after}>\n";
835 array_push( $tr_history , true );
836 array_push( $tr_attributes , '' );
837 array_pop( $has_opened_tr );
838 array_push( $has_opened_tr , true );
841 $last_tag = array_pop( $last_tag_history );
843 if ( array_pop( $td_history ) ) {
844 $previous = "</{$last_tag}>{$previous}";
847 if ( $first_character === '|' ) {
849 } elseif ( $first_character === '!' ) {
851 } elseif ( $first_character === '+' ) {
852 $last_tag = 'caption';
857 array_push( $last_tag_history , $last_tag );
859 # A cell could contain both parameters and data
860 $cell_data = explode( '|' , $cell , 2 );
862 # Bug 553: Note that a '|' inside an invalid link should not
863 # be mistaken as delimiting cell parameters
864 if ( strpos( $cell_data[0], '[[' ) !== false ) {
865 $cell = "{$previous}<{$last_tag}>{$cell}";
866 } elseif ( count( $cell_data ) == 1 ) {
867 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
869 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
870 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
871 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
875 array_push( $td_history , true );
878 $out .= $outLine . "\n";
881 # Closing open td, tr && table
882 while ( count( $td_history ) > 0 ) {
883 if ( array_pop( $td_history ) ) {
886 if ( array_pop( $tr_history ) ) {
889 if ( !array_pop( $has_opened_tr ) ) {
890 $out .= "<tr><td></td></tr>\n" ;
893 $out .= "</table>\n";
896 # Remove trailing line-ending (b/c)
897 if ( substr( $out, -1 ) === "\n" ) {
898 $out = substr( $out, 0, -1 );
901 # special case: don't return empty table
902 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
906 wfProfileOut( __METHOD__
);
912 * Helper function for parse() that transforms wiki markup into
913 * HTML. Only called for $mOutputType == self::OT_HTML.
917 function internalParse( $text, $isMain = true, $frame=false ) {
918 wfProfileIn( __METHOD__
);
922 # Hook to suspend the parser in this state
923 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
924 wfProfileOut( __METHOD__
);
928 # if $frame is provided, then use $frame for replacing any variables
930 # use frame depth to infer how include/noinclude tags should be handled
931 # depth=0 means this is the top-level document; otherwise it's an included document
932 if ( !$frame->depth
) {
935 $flag = Parser
::PTD_FOR_INCLUSION
;
937 $dom = $this->preprocessToDom( $text, $flag );
938 $text = $frame->expand( $dom );
940 # if $frame is not provided, then use old-style replaceVariables
941 $text = $this->replaceVariables( $text );
944 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
945 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
947 # Tables need to come after variable replacement for things to work
948 # properly; putting them before other transformations should keep
949 # exciting things like link expansions from showing up in surprising
951 $text = $this->doTableStuff( $text );
953 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
955 $text = $this->doDoubleUnderscore( $text );
957 $text = $this->doHeadings( $text );
958 if ( $this->mOptions
->getUseDynamicDates() ) {
959 $df = DateFormatter
::getInstance();
960 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
962 $text = $this->doAllQuotes( $text );
963 $text = $this->replaceInternalLinks( $text );
964 $text = $this->replaceExternalLinks( $text );
966 # replaceInternalLinks may sometimes leave behind
967 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
968 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
970 $text = $this->doMagicLinks( $text );
971 $text = $this->formatHeadings( $text, $origText, $isMain );
973 wfProfileOut( __METHOD__
);
978 * Replace special strings like "ISBN xxx" and "RFC xxx" with
979 * magic external links.
984 function doMagicLinks( $text ) {
985 wfProfileIn( __METHOD__
);
986 $prots = $this->mUrlProtocols
;
987 $urlChar = self
::EXT_LINK_URL_CLASS
;
988 $text = preg_replace_callback(
990 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
991 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
992 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
993 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
994 ISBN\s+(\b # m[5]: ISBN, capture number
995 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
996 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
997 [0-9Xx] # check digit
999 )!x', array( &$this, 'magicLinkCallback' ), $text );
1000 wfProfileOut( __METHOD__
);
1004 function magicLinkCallback( $m ) {
1005 if ( isset( $m[1] ) && $m[1] !== '' ) {
1008 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1011 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1012 # Free external link
1013 return $this->makeFreeExternalLink( $m[0] );
1014 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1017 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1020 $CssClass = 'mw-magiclink-rfc';
1022 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1024 $urlmsg = 'pubmedurl';
1025 $CssClass = 'mw-magiclink-pmid';
1028 throw new MWException( __METHOD__
.': unrecognised match type "' .
1029 substr( $m[0], 0, 20 ) . '"' );
1031 $url = wfMsg( $urlmsg, $id);
1032 $sk = $this->mOptions
->getSkin();
1033 $la = $sk->getExternalLinkAttributes( "external $CssClass" );
1034 return "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1035 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1038 $num = strtr( $isbn, array(
1043 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1045 $titleObj->escapeLocalUrl() .
1046 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1053 * Make a free external link, given a user-supplied URL
1057 function makeFreeExternalLink( $url ) {
1059 wfProfileIn( __METHOD__
);
1061 $sk = $this->mOptions
->getSkin();
1064 # The characters '<' and '>' (which were escaped by
1065 # removeHTMLtags()) should not be included in
1066 # URLs, per RFC 2396.
1068 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1069 $trail = substr( $url, $m2[0][1] ) . $trail;
1070 $url = substr( $url, 0, $m2[0][1] );
1073 # Move trailing punctuation to $trail
1075 # If there is no left bracket, then consider right brackets fair game too
1076 if ( strpos( $url, '(' ) === false ) {
1080 $numSepChars = strspn( strrev( $url ), $sep );
1081 if ( $numSepChars ) {
1082 $trail = substr( $url, -$numSepChars ) . $trail;
1083 $url = substr( $url, 0, -$numSepChars );
1086 $url = Sanitizer
::cleanUrl( $url );
1088 # Is this an external image?
1089 $text = $this->maybeMakeExternalImage( $url );
1090 if ( $text === false ) {
1091 # Not an image, make a link
1092 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1093 $this->getExternalLinkAttribs( $url ) );
1094 # Register it in the output object...
1095 # Replace unnecessary URL escape codes with their equivalent characters
1096 $pasteurized = self
::replaceUnusualEscapes( $url );
1097 $this->mOutput
->addExternalLink( $pasteurized );
1099 wfProfileOut( __METHOD__
);
1100 return $text . $trail;
1105 * Parse headers and return html
1109 function doHeadings( $text ) {
1110 wfProfileIn( __METHOD__
);
1111 for ( $i = 6; $i >= 1; --$i ) {
1112 $h = str_repeat( '=', $i );
1113 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1114 "<h$i>\\1</h$i>", $text );
1116 wfProfileOut( __METHOD__
);
1121 * Replace single quotes with HTML markup
1123 * @return string the altered text
1125 function doAllQuotes( $text ) {
1126 wfProfileIn( __METHOD__
);
1128 $lines = StringUtils
::explode( "\n", $text );
1129 foreach ( $lines as $line ) {
1130 $outtext .= $this->doQuotes( $line ) . "\n";
1132 $outtext = substr( $outtext, 0,-1 );
1133 wfProfileOut( __METHOD__
);
1138 * Helper function for doAllQuotes()
1140 public function doQuotes( $text ) {
1141 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1142 if ( count( $arr ) == 1 ) {
1145 # First, do some preliminary work. This may shift some apostrophes from
1146 # being mark-up to being text. It also counts the number of occurrences
1147 # of bold and italics mark-ups.
1151 foreach ( $arr as $r ) {
1152 if ( ( $i %
2 ) == 1 ) {
1153 # If there are ever four apostrophes, assume the first is supposed to
1154 # be text, and the remaining three constitute mark-up for bold text.
1155 if ( strlen( $arr[$i] ) == 4 ) {
1158 } elseif ( strlen( $arr[$i] ) > 5 ) {
1159 # If there are more than 5 apostrophes in a row, assume they're all
1160 # text except for the last 5.
1161 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1164 # Count the number of occurrences of bold and italics mark-ups.
1165 # We are not counting sequences of five apostrophes.
1166 if ( strlen( $arr[$i] ) == 2 ) {
1168 } elseif ( strlen( $arr[$i] ) == 3 ) {
1170 } elseif ( strlen( $arr[$i] ) == 5 ) {
1178 # If there is an odd number of both bold and italics, it is likely
1179 # that one of the bold ones was meant to be an apostrophe followed
1180 # by italics. Which one we cannot know for certain, but it is more
1181 # likely to be one that has a single-letter word before it.
1182 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1184 $firstsingleletterword = -1;
1185 $firstmultiletterword = -1;
1187 foreach ( $arr as $r ) {
1188 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1189 $x1 = substr( $arr[$i-1], -1 );
1190 $x2 = substr( $arr[$i-1], -2, 1 );
1191 if ( $x1 === ' ' ) {
1192 if ( $firstspace == -1 ) {
1195 } elseif ( $x2 === ' ') {
1196 if ( $firstsingleletterword == -1 ) {
1197 $firstsingleletterword = $i;
1200 if ( $firstmultiletterword == -1 ) {
1201 $firstmultiletterword = $i;
1208 # If there is a single-letter word, use it!
1209 if ( $firstsingleletterword > -1 ) {
1210 $arr[$firstsingleletterword] = "''";
1211 $arr[$firstsingleletterword-1] .= "'";
1212 } elseif ( $firstmultiletterword > -1 ) {
1213 # If not, but there's a multi-letter word, use that one.
1214 $arr[$firstmultiletterword] = "''";
1215 $arr[$firstmultiletterword-1] .= "'";
1216 } elseif ( $firstspace > -1 ) {
1217 # ... otherwise use the first one that has neither.
1218 # (notice that it is possible for all three to be -1 if, for example,
1219 # there is only one pentuple-apostrophe in the line)
1220 $arr[$firstspace] = "''";
1221 $arr[$firstspace-1] .= "'";
1225 # Now let's actually convert our apostrophic mush to HTML!
1230 foreach ( $arr as $r ) {
1231 if ( ( $i %
2 ) == 0 ) {
1232 if ( $state === 'both' ) {
1238 if ( strlen( $r ) == 2 ) {
1239 if ( $state === 'i' ) {
1240 $output .= '</i>'; $state = '';
1241 } elseif ( $state === 'bi' ) {
1242 $output .= '</i>'; $state = 'b';
1243 } elseif ( $state === 'ib' ) {
1244 $output .= '</b></i><b>'; $state = 'b';
1245 } elseif ( $state === 'both' ) {
1246 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1247 } else { # $state can be 'b' or ''
1248 $output .= '<i>'; $state .= 'i';
1250 } elseif ( strlen( $r ) == 3 ) {
1251 if ( $state === 'b' ) {
1252 $output .= '</b>'; $state = '';
1253 } elseif ( $state === 'bi' ) {
1254 $output .= '</i></b><i>'; $state = 'i';
1255 } elseif ( $state === 'ib' ) {
1256 $output .= '</b>'; $state = 'i';
1257 } elseif ( $state === 'both' ) {
1258 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1259 } else { # $state can be 'i' or ''
1260 $output .= '<b>'; $state .= 'b';
1262 } elseif ( strlen( $r ) == 5 ) {
1263 if ( $state === 'b' ) {
1264 $output .= '</b><i>'; $state = 'i';
1265 } elseif ( $state === 'i' ) {
1266 $output .= '</i><b>'; $state = 'b';
1267 } elseif ( $state === 'bi' ) {
1268 $output .= '</i></b>'; $state = '';
1269 } elseif ( $state === 'ib' ) {
1270 $output .= '</b></i>'; $state = '';
1271 } elseif ( $state === 'both' ) {
1272 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1273 } else { # ($state == '')
1274 $buffer = ''; $state = 'both';
1280 # Now close all remaining tags. Notice that the order is important.
1281 if ( $state === 'b' ||
$state === 'ib' ) {
1284 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1287 if ( $state === 'bi' ) {
1290 # There might be lonely ''''', so make sure we have a buffer
1291 if ( $state === 'both' && $buffer ) {
1292 $output .= '<b><i>'.$buffer.'</i></b>';
1299 * Replace external links (REL)
1301 * Note: this is all very hackish and the order of execution matters a lot.
1302 * Make sure to run maintenance/parserTests.php if you change this code.
1306 function replaceExternalLinks( $text ) {
1308 wfProfileIn( __METHOD__
);
1310 $sk = $this->mOptions
->getSkin();
1312 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1313 $s = array_shift( $bits );
1316 while ( $i<count( $bits ) ) {
1318 $protocol = $bits[$i++
];
1319 $text = $bits[$i++
];
1320 $trail = $bits[$i++
];
1322 # The characters '<' and '>' (which were escaped by
1323 # removeHTMLtags()) should not be included in
1324 # URLs, per RFC 2396.
1326 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1327 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1328 $url = substr( $url, 0, $m2[0][1] );
1331 # If the link text is an image URL, replace it with an <img> tag
1332 # This happened by accident in the original parser, but some people used it extensively
1333 $img = $this->maybeMakeExternalImage( $text );
1334 if ( $img !== false ) {
1340 # Set linktype for CSS - if URL==text, link is essentially free
1341 $linktype = ( $text === $url ) ?
'free' : 'text';
1343 # No link text, e.g. [http://domain.tld/some.link]
1344 if ( $text == '' ) {
1345 # Autonumber if allowed. See bug #5918
1346 if ( strpos( wfUrlProtocols(), substr( $protocol, 0, strpos( $protocol, ':' ) ) ) !== false ) {
1347 $langObj = $this->getFunctionLang();
1348 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1349 $linktype = 'autonumber';
1351 # Otherwise just use the URL
1352 $text = htmlspecialchars( $url );
1356 # Have link text, e.g. [http://domain.tld/some.link text]s
1358 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1361 $text = $wgContLang->markNoConversion( $text );
1363 $url = Sanitizer
::cleanUrl( $url );
1365 # Use the encoded URL
1366 # This means that users can paste URLs directly into the text
1367 # Funny characters like ö aren't valid in URLs anyway
1368 # This was changed in August 2004
1369 $s .= $sk->makeExternalLink( $url, $text, false, $linktype,
1370 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1372 # Register link in the output object.
1373 # Replace unnecessary URL escape codes with the referenced character
1374 # This prevents spammers from hiding links from the filters
1375 $pasteurized = self
::replaceUnusualEscapes( $url );
1376 $this->mOutput
->addExternalLink( $pasteurized );
1379 wfProfileOut( __METHOD__
);
1384 * Get an associative array of additional HTML attributes appropriate for a
1385 * particular external link. This currently may include rel => nofollow
1386 * (depending on configuration, namespace, and the URL's domain) and/or a
1387 * target attribute (depending on configuration).
1389 * @param string $url Optional URL, to extract the domain from for rel =>
1390 * nofollow if appropriate
1391 * @return array Associative array of HTML attributes
1393 function getExternalLinkAttribs( $url = false ) {
1395 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1396 $ns = $this->mTitle
->getNamespace();
1397 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) ) {
1398 $attribs['rel'] = 'nofollow';
1400 global $wgNoFollowDomainExceptions;
1401 if ( $wgNoFollowDomainExceptions ) {
1402 $bits = wfParseUrl( $url );
1403 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1404 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1405 if ( substr( $bits['host'], -strlen( $domain ) ) == $domain ) {
1406 unset( $attribs['rel'] );
1413 if ( $this->mOptions
->getExternalLinkTarget() ) {
1414 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1421 * Replace unusual URL escape codes with their equivalent characters
1425 * @todo This can merge genuinely required bits in the path or query string,
1426 * breaking legit URLs. A proper fix would treat the various parts of
1427 * the URL differently; as a workaround, just use the output for
1428 * statistical records, not for actual linking/output.
1430 static function replaceUnusualEscapes( $url ) {
1431 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1432 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1436 * Callback function used in replaceUnusualEscapes().
1437 * Replaces unusual URL escape codes with their equivalent character
1441 private static function replaceUnusualEscapesCallback( $matches ) {
1442 $char = urldecode( $matches[0] );
1443 $ord = ord( $char );
1444 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1445 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1446 # No, shouldn't be escaped
1449 # Yes, leave it escaped
1455 * make an image if it's allowed, either through the global
1456 * option, through the exception, or through the on-wiki whitelist
1459 function maybeMakeExternalImage( $url ) {
1460 $sk = $this->mOptions
->getSkin();
1461 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1462 $imagesexception = !empty( $imagesfrom );
1464 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1465 if ( $imagesexception && is_array( $imagesfrom ) ) {
1466 $imagematch = false;
1467 foreach ( $imagesfrom as $match ) {
1468 if ( strpos( $url, $match ) === 0 ) {
1473 } elseif ( $imagesexception ) {
1474 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1476 $imagematch = false;
1478 if ( $this->mOptions
->getAllowExternalImages()
1479 ||
( $imagesexception && $imagematch ) ) {
1480 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1482 $text = $sk->makeExternalImage( $url );
1485 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1486 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1487 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1488 foreach ( $whitelist as $entry ) {
1489 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1490 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1493 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1494 # Image matches a whitelist entry
1495 $text = $sk->makeExternalImage( $url );
1504 * Process [[ ]] wikilinks
1505 * @return processed text
1509 function replaceInternalLinks( $s ) {
1510 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1515 * Process [[ ]] wikilinks (RIL)
1516 * @return LinkHolderArray
1520 function replaceInternalLinks2( &$s ) {
1523 wfProfileIn( __METHOD__
);
1525 wfProfileIn( __METHOD__
.'-setup' );
1526 static $tc = FALSE, $e1, $e1_img;
1527 # the % is needed to support urlencoded titles as well
1529 $tc = Title
::legalChars() . '#%';
1530 # Match a link having the form [[namespace:link|alternate]]trail
1531 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1532 # Match cases where there is no "]]", which might still be images
1533 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1536 $sk = $this->mOptions
->getSkin();
1537 $holders = new LinkHolderArray( $this );
1539 # split the entire text string on occurences of [[
1540 $a = StringUtils
::explode( '[[', ' ' . $s );
1541 # get the first element (all text up to first [[), and remove the space we added
1544 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1545 $s = substr( $s, 1 );
1547 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1549 if ( $useLinkPrefixExtension ) {
1550 # Match the end of a line for a word that's not followed by whitespace,
1551 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1552 $e2 = wfMsgForContent( 'linkprefix' );
1555 if ( is_null( $this->mTitle
) ) {
1556 wfProfileOut( __METHOD__
.'-setup' );
1557 wfProfileOut( __METHOD__
);
1558 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1560 $nottalk = !$this->mTitle
->isTalkPage();
1562 if ( $useLinkPrefixExtension ) {
1564 if ( preg_match( $e2, $s, $m ) ) {
1565 $first_prefix = $m[2];
1567 $first_prefix = false;
1573 if ( $wgContLang->hasVariants() ) {
1574 $selflink = $wgContLang->convertLinkToAllVariants( $this->mTitle
->getPrefixedText() );
1576 $selflink = array( $this->mTitle
->getPrefixedText() );
1578 $useSubpages = $this->areSubpagesAllowed();
1579 wfProfileOut( __METHOD__
.'-setup' );
1581 # Loop for each link
1582 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1583 # Check for excessive memory usage
1584 if ( $holders->isBig() ) {
1586 # Do the existence check, replace the link holders and clear the array
1587 $holders->replace( $s );
1591 if ( $useLinkPrefixExtension ) {
1592 wfProfileIn( __METHOD__
.'-prefixhandling' );
1593 if ( preg_match( $e2, $s, $m ) ) {
1600 if ( $first_prefix ) {
1601 $prefix = $first_prefix;
1602 $first_prefix = false;
1604 wfProfileOut( __METHOD__
.'-prefixhandling' );
1607 $might_be_img = false;
1609 wfProfileIn( __METHOD__
."-e1" );
1610 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1612 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1613 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1614 # the real problem is with the $e1 regex
1617 # Still some problems for cases where the ] is meant to be outside punctuation,
1618 # and no image is in sight. See bug 2095.
1620 if ( $text !== '' &&
1621 substr( $m[3], 0, 1 ) === ']' &&
1622 strpos( $text, '[' ) !== false
1625 $text .= ']'; # so that replaceExternalLinks($text) works later
1626 $m[3] = substr( $m[3], 1 );
1628 # fix up urlencoded title texts
1629 if ( strpos( $m[1], '%' ) !== false ) {
1630 # Should anchors '#' also be rejected?
1631 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode( $m[1] ) );
1634 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1635 $might_be_img = true;
1637 if ( strpos( $m[1], '%' ) !== false ) {
1638 $m[1] = urldecode( $m[1] );
1641 } else { # Invalid form; output directly
1642 $s .= $prefix . '[[' . $line ;
1643 wfProfileOut( __METHOD__
."-e1" );
1646 wfProfileOut( __METHOD__
."-e1" );
1647 wfProfileIn( __METHOD__
."-misc" );
1649 # Don't allow internal links to pages containing
1650 # PROTO: where PROTO is a valid URL protocol; these
1651 # should be external links.
1652 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1653 $s .= $prefix . '[[' . $line ;
1654 wfProfileOut( __METHOD__
."-misc" );
1658 # Make subpage if necessary
1659 if ( $useSubpages ) {
1660 $link = $this->maybeDoSubpageLink( $m[1], $text );
1665 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1667 # Strip off leading ':'
1668 $link = substr( $link, 1 );
1671 wfProfileOut( __METHOD__
."-misc" );
1672 wfProfileIn( __METHOD__
."-title" );
1673 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1674 if ( $nt === null ) {
1675 $s .= $prefix . '[[' . $line;
1676 wfProfileOut( __METHOD__
."-title" );
1680 $ns = $nt->getNamespace();
1681 $iw = $nt->getInterWiki();
1682 wfProfileOut( __METHOD__
."-title" );
1684 if ( $might_be_img ) { # if this is actually an invalid link
1685 wfProfileIn( __METHOD__
."-might_be_img" );
1686 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1689 # look at the next 'line' to see if we can close it there
1691 $next_line = $a->current();
1692 if ( $next_line === false ||
$next_line === null ) {
1695 $m = explode( ']]', $next_line, 3 );
1696 if ( count( $m ) == 3 ) {
1697 # the first ]] closes the inner link, the second the image
1699 $text .= "[[{$m[0]}]]{$m[1]}";
1702 } elseif ( count( $m ) == 2 ) {
1703 # if there's exactly one ]] that's fine, we'll keep looking
1704 $text .= "[[{$m[0]}]]{$m[1]}";
1706 # if $next_line is invalid too, we need look no further
1707 $text .= '[[' . $next_line;
1712 # we couldn't find the end of this imageLink, so output it raw
1713 # but don't ignore what might be perfectly normal links in the text we've examined
1714 $holders->merge( $this->replaceInternalLinks2( $text ) );
1715 $s .= "{$prefix}[[$link|$text";
1716 # note: no $trail, because without an end, there *is* no trail
1717 wfProfileOut( __METHOD__
."-might_be_img" );
1720 } else { # it's not an image, so output it raw
1721 $s .= "{$prefix}[[$link|$text";
1722 # note: no $trail, because without an end, there *is* no trail
1723 wfProfileOut( __METHOD__
."-might_be_img" );
1726 wfProfileOut( __METHOD__
."-might_be_img" );
1729 $wasblank = ( $text == '' );
1734 # Link not escaped by : , create the various objects
1738 wfProfileIn( __METHOD__
."-interwiki" );
1739 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1740 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1741 $s = rtrim( $s . $prefix );
1742 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1743 wfProfileOut( __METHOD__
."-interwiki" );
1746 wfProfileOut( __METHOD__
."-interwiki" );
1748 if ( $ns == NS_FILE
) {
1749 wfProfileIn( __METHOD__
."-image" );
1750 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1752 # if no parameters were passed, $text
1753 # becomes something like "File:Foo.png",
1754 # which we don't want to pass on to the
1758 # recursively parse links inside the image caption
1759 # actually, this will parse them in any other parameters, too,
1760 # but it might be hard to fix that, and it doesn't matter ATM
1761 $text = $this->replaceExternalLinks( $text );
1762 $holders->merge( $this->replaceInternalLinks2( $text ) );
1764 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1765 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1767 $s .= $prefix . $trail;
1769 $this->mOutput
->addImage( $nt->getDBkey() );
1770 wfProfileOut( __METHOD__
."-image" );
1775 if ( $ns == NS_CATEGORY
) {
1776 wfProfileIn( __METHOD__
."-category" );
1777 $s = rtrim( $s . "\n" ); # bug 87
1780 $sortkey = $this->getDefaultSort();
1784 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1785 $sortkey = str_replace( "\n", '', $sortkey );
1786 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1787 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1790 * Strip the whitespace Category links produce, see bug 87
1791 * @todo We might want to use trim($tmp, "\n") here.
1793 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'': $prefix . $trail;
1795 wfProfileOut( __METHOD__
."-category" );
1800 # Self-link checking
1801 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1802 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1803 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1808 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1809 # FIXME: Should do batch file existence checks, see comment below
1810 if ( $ns == NS_MEDIA
) {
1811 wfProfileIn( __METHOD__
."-media" );
1812 # Give extensions a chance to select the file revision for us
1813 $skip = $time = false;
1814 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1816 $link = $sk->link( $nt );
1818 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1820 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1821 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1822 $this->mOutput
->addImage( $nt->getDBkey() );
1823 wfProfileOut( __METHOD__
."-media" );
1827 wfProfileIn( __METHOD__
."-always_known" );
1828 # Some titles, such as valid special pages or files in foreign repos, should
1829 # be shown as bluelinks even though they're not included in the page table
1831 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1832 # batch file existence checks for NS_FILE and NS_MEDIA
1833 if ( $iw == '' && $nt->isAlwaysKnown() ) {
1834 $this->mOutput
->addLink( $nt );
1835 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1837 # Links will be added to the output link list after checking
1838 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1840 wfProfileOut( __METHOD__
."-always_known" );
1842 wfProfileOut( __METHOD__
);
1847 * Make a link placeholder. The text returned can be later resolved to a real link with
1848 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1849 * parsing of interwiki links, and secondly to allow all existence checks and
1850 * article length checks (for stub links) to be bundled into a single query.
1854 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1855 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1859 * Render a forced-blue link inline; protect against double expansion of
1860 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1861 * Since this little disaster has to split off the trail text to avoid
1862 * breaking URLs in the following text without breaking trails on the
1863 * wiki links, it's been made into a horrible function.
1866 * @param string $text
1867 * @param string $query
1868 * @param string $trail
1869 * @param string $prefix
1870 * @return string HTML-wikitext mix oh yuck
1872 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1873 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1874 $sk = $this->mOptions
->getSkin();
1875 # FIXME: use link() instead of deprecated makeKnownLinkObj()
1876 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1877 return $this->armorLinks( $link ) . $trail;
1881 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1882 * going to go through further parsing steps before inline URL expansion.
1884 * Not needed quite as much as it used to be since free links are a bit
1885 * more sensible these days. But bracketed links are still an issue.
1887 * @param string more-or-less HTML
1888 * @return string less-or-more HTML with NOPARSE bits
1890 function armorLinks( $text ) {
1891 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1892 "{$this->mUniqPrefix}NOPARSE$1", $text );
1896 * Return true if subpage links should be expanded on this page.
1899 function areSubpagesAllowed() {
1900 # Some namespaces don't allow subpages
1901 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
1905 * Handle link to subpage if necessary
1906 * @param string $target the source of the link
1907 * @param string &$text the link text, modified as necessary
1908 * @return string the full name of the link
1911 function maybeDoSubpageLink( $target, &$text ) {
1912 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
1916 * Used by doBlockLevels()
1919 function closeParagraph() {
1921 if ( $this->mLastSection
!= '' ) {
1922 $result = '</' . $this->mLastSection
. ">\n";
1924 $this->mInPre
= false;
1925 $this->mLastSection
= '';
1929 * getCommon() returns the length of the longest common substring
1930 * of both arguments, starting at the beginning of both.
1933 function getCommon( $st1, $st2 ) {
1934 $fl = strlen( $st1 );
1935 $shorter = strlen( $st2 );
1936 if ( $fl < $shorter ) {
1940 for ( $i = 0; $i < $shorter; ++
$i ) {
1941 if ( $st1{$i} != $st2{$i} ) {
1948 * These next three functions open, continue, and close the list
1949 * element appropriate to the prefix character passed into them.
1952 function openList( $char ) {
1953 $result = $this->closeParagraph();
1955 if ( '*' === $char ) {
1956 $result .= '<ul><li>';
1957 } elseif ( '#' === $char ) {
1958 $result .= '<ol><li>';
1959 } elseif ( ':' === $char ) {
1960 $result .= '<dl><dd>';
1961 } elseif ( ';' === $char ) {
1962 $result .= '<dl><dt>';
1963 $this->mDTopen
= true;
1965 $result = '<!-- ERR 1 -->';
1973 * @param $char String
1976 function nextItem( $char ) {
1977 if ( '*' === $char ||
'#' === $char ) {
1979 } elseif ( ':' === $char ||
';' === $char ) {
1981 if ( $this->mDTopen
) {
1984 if ( ';' === $char ) {
1985 $this->mDTopen
= true;
1986 return $close . '<dt>';
1988 $this->mDTopen
= false;
1989 return $close . '<dd>';
1992 return '<!-- ERR 2 -->';
1997 * @param $char String
2000 function closeList( $char ) {
2001 if ( '*' === $char ) {
2002 $text = '</li></ul>';
2003 } elseif ( '#' === $char ) {
2004 $text = '</li></ol>';
2005 } elseif ( ':' === $char ) {
2006 if ( $this->mDTopen
) {
2007 $this->mDTopen
= false;
2008 $text = '</dt></dl>';
2010 $text = '</dd></dl>';
2013 return '<!-- ERR 3 -->';
2020 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2022 * @param $linestart bool whether or not this is at the start of a line.
2024 * @return string the lists rendered as HTML
2026 function doBlockLevels( $text, $linestart ) {
2027 wfProfileIn( __METHOD__
);
2029 # Parsing through the text line by line. The main thing
2030 # happening here is handling of block-level elements p, pre,
2031 # and making lists from lines starting with * # : etc.
2033 $textLines = StringUtils
::explode( "\n", $text );
2035 $lastPrefix = $output = '';
2036 $this->mDTopen
= $inBlockElem = false;
2038 $paragraphStack = false;
2040 foreach ( $textLines as $oLine ) {
2042 if ( !$linestart ) {
2052 $lastPrefixLength = strlen( $lastPrefix );
2053 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2054 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2055 # If not in a <pre> element, scan for and figure out what prefixes are there.
2056 if ( !$this->mInPre
) {
2057 # Multiple prefixes may abut each other for nested lists.
2058 $prefixLength = strspn( $oLine, '*#:;' );
2059 $prefix = substr( $oLine, 0, $prefixLength );
2062 # ; and : are both from definition-lists, so they're equivalent
2063 # for the purposes of determining whether or not we need to open/close
2065 $prefix2 = str_replace( ';', ':', $prefix );
2066 $t = substr( $oLine, $prefixLength );
2067 $this->mInPre
= (bool)$preOpenMatch;
2069 # Don't interpret any other prefixes in preformatted text
2071 $prefix = $prefix2 = '';
2076 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2077 # Same as the last item, so no need to deal with nesting or opening stuff
2078 $output .= $this->nextItem( substr( $prefix, -1 ) );
2079 $paragraphStack = false;
2081 if ( substr( $prefix, -1 ) === ';') {
2082 # The one nasty exception: definition lists work like this:
2083 # ; title : definition text
2084 # So we check for : in the remainder text to split up the
2085 # title and definition, without b0rking links.
2087 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2089 $output .= $term . $this->nextItem( ':' );
2092 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2093 # We need to open or close prefixes, or both.
2095 # Either open or close a level...
2096 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2097 $paragraphStack = false;
2099 # Close all the prefixes which aren't shared.
2100 while ( $commonPrefixLength < $lastPrefixLength ) {
2101 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2102 --$lastPrefixLength;
2105 # Continue the current prefix if appropriate.
2106 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2107 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2110 # Open prefixes where appropriate.
2111 while ( $prefixLength > $commonPrefixLength ) {
2112 $char = substr( $prefix, $commonPrefixLength, 1 );
2113 $output .= $this->openList( $char );
2115 if ( ';' === $char ) {
2116 # FIXME: This is dupe of code above
2117 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2119 $output .= $term . $this->nextItem( ':' );
2122 ++
$commonPrefixLength;
2124 $lastPrefix = $prefix2;
2127 # If we have no prefixes, go to paragraph mode.
2128 if ( 0 == $prefixLength ) {
2129 wfProfileIn( __METHOD__
."-paragraph" );
2130 # No prefix (not in list)--go to paragraph mode
2131 # XXX: use a stack for nestable elements like span, table and div
2132 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2133 $closematch = preg_match(
2134 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2135 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2136 if ( $openmatch or $closematch ) {
2137 $paragraphStack = false;
2138 #Â TODO bug 5718: paragraph closed
2139 $output .= $this->closeParagraph();
2140 if ( $preOpenMatch and !$preCloseMatch ) {
2141 $this->mInPre
= true;
2143 if ( $closematch ) {
2144 $inBlockElem = false;
2146 $inBlockElem = true;
2148 } elseif ( !$inBlockElem && !$this->mInPre
) {
2149 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2151 if ( $this->mLastSection
!== 'pre' ) {
2152 $paragraphStack = false;
2153 $output .= $this->closeParagraph().'<pre>';
2154 $this->mLastSection
= 'pre';
2156 $t = substr( $t, 1 );
2159 if ( trim( $t ) == '' ) {
2160 if ( $paragraphStack ) {
2161 $output .= $paragraphStack.'<br />';
2162 $paragraphStack = false;
2163 $this->mLastSection
= 'p';
2165 if ( $this->mLastSection
!== 'p' ) {
2166 $output .= $this->closeParagraph();
2167 $this->mLastSection
= '';
2168 $paragraphStack = '<p>';
2170 $paragraphStack = '</p><p>';
2174 if ( $paragraphStack ) {
2175 $output .= $paragraphStack;
2176 $paragraphStack = false;
2177 $this->mLastSection
= 'p';
2178 } elseif ( $this->mLastSection
!== 'p' ) {
2179 $output .= $this->closeParagraph().'<p>';
2180 $this->mLastSection
= 'p';
2185 wfProfileOut( __METHOD__
."-paragraph" );
2187 # somewhere above we forget to get out of pre block (bug 785)
2188 if ( $preCloseMatch && $this->mInPre
) {
2189 $this->mInPre
= false;
2191 if ( $paragraphStack === false ) {
2195 while ( $prefixLength ) {
2196 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2199 if ( $this->mLastSection
!= '' ) {
2200 $output .= '</' . $this->mLastSection
. '>';
2201 $this->mLastSection
= '';
2204 wfProfileOut( __METHOD__
);
2209 * Split up a string on ':', ignoring any occurences inside tags
2210 * to prevent illegal overlapping.
2211 * @param string $str the string to split
2212 * @param string &$before set to everything before the ':'
2213 * @param string &$after set to everything after the ':'
2214 * return string the position of the ':', or false if none found
2216 function findColonNoLinks( $str, &$before, &$after ) {
2217 wfProfileIn( __METHOD__
);
2219 $pos = strpos( $str, ':' );
2220 if ( $pos === false ) {
2222 wfProfileOut( __METHOD__
);
2226 $lt = strpos( $str, '<' );
2227 if ( $lt === false ||
$lt > $pos ) {
2228 # Easy; no tag nesting to worry about
2229 $before = substr( $str, 0, $pos );
2230 $after = substr( $str, $pos+
1 );
2231 wfProfileOut( __METHOD__
);
2235 # Ugly state machine to walk through avoiding tags.
2236 $state = self
::COLON_STATE_TEXT
;
2238 $len = strlen( $str );
2239 for( $i = 0; $i < $len; $i++
) {
2243 # (Using the number is a performance hack for common cases)
2244 case 0: # self::COLON_STATE_TEXT:
2247 # Could be either a <start> tag or an </end> tag
2248 $state = self
::COLON_STATE_TAGSTART
;
2251 if ( $stack == 0 ) {
2253 $before = substr( $str, 0, $i );
2254 $after = substr( $str, $i +
1 );
2255 wfProfileOut( __METHOD__
);
2258 # Embedded in a tag; don't break it.
2261 # Skip ahead looking for something interesting
2262 $colon = strpos( $str, ':', $i );
2263 if ( $colon === false ) {
2264 # Nothing else interesting
2265 wfProfileOut( __METHOD__
);
2268 $lt = strpos( $str, '<', $i );
2269 if ( $stack === 0 ) {
2270 if ( $lt === false ||
$colon < $lt ) {
2272 $before = substr( $str, 0, $colon );
2273 $after = substr( $str, $colon +
1 );
2274 wfProfileOut( __METHOD__
);
2278 if ( $lt === false ) {
2279 # Nothing else interesting to find; abort!
2280 # We're nested, but there's no close tags left. Abort!
2283 # Skip ahead to next tag start
2285 $state = self
::COLON_STATE_TAGSTART
;
2288 case 1: # self::COLON_STATE_TAG:
2293 $state = self
::COLON_STATE_TEXT
;
2296 # Slash may be followed by >?
2297 $state = self
::COLON_STATE_TAGSLASH
;
2303 case 2: # self::COLON_STATE_TAGSTART:
2306 $state = self
::COLON_STATE_CLOSETAG
;
2309 $state = self
::COLON_STATE_COMMENT
;
2312 # Illegal early close? This shouldn't happen D:
2313 $state = self
::COLON_STATE_TEXT
;
2316 $state = self
::COLON_STATE_TAG
;
2319 case 3: # self::COLON_STATE_CLOSETAG:
2324 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2325 wfProfileOut( __METHOD__
);
2328 $state = self
::COLON_STATE_TEXT
;
2331 case self
::COLON_STATE_TAGSLASH
:
2333 # Yes, a self-closed tag <blah/>
2334 $state = self
::COLON_STATE_TEXT
;
2336 # Probably we're jumping the gun, and this is an attribute
2337 $state = self
::COLON_STATE_TAG
;
2340 case 5: # self::COLON_STATE_COMMENT:
2342 $state = self
::COLON_STATE_COMMENTDASH
;
2345 case self
::COLON_STATE_COMMENTDASH
:
2347 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2349 $state = self
::COLON_STATE_COMMENT
;
2352 case self
::COLON_STATE_COMMENTDASHDASH
:
2354 $state = self
::COLON_STATE_TEXT
;
2356 $state = self
::COLON_STATE_COMMENT
;
2360 throw new MWException( "State machine error in " . __METHOD__
);
2364 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2367 wfProfileOut( __METHOD__
);
2372 * Return value of a magic variable (like PAGENAME)
2376 function getVariableValue( $index, $frame=false ) {
2377 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2378 global $wgScriptPath, $wgStylePath;
2381 * Some of these require message or data lookups and can be
2382 * expensive to check many times.
2384 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2385 if ( isset( $this->mVarCache
[$index] ) ) {
2386 return $this->mVarCache
[$index];
2390 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2391 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2394 global $wgLocaltimezone;
2395 if ( isset( $wgLocaltimezone ) ) {
2396 $oldtz = date_default_timezone_get();
2397 date_default_timezone_set( $wgLocaltimezone );
2400 $localTimestamp = date( 'YmdHis', $ts );
2401 $localMonth = date( 'm', $ts );
2402 $localMonth1 = date( 'n', $ts );
2403 $localMonthName = date( 'n', $ts );
2404 $localDay = date( 'j', $ts );
2405 $localDay2 = date( 'd', $ts );
2406 $localDayOfWeek = date( 'w', $ts );
2407 $localWeek = date( 'W', $ts );
2408 $localYear = date( 'Y', $ts );
2409 $localHour = date( 'H', $ts );
2410 if ( isset( $wgLocaltimezone ) ) {
2411 date_default_timezone_set( $oldtz );
2415 case 'currentmonth':
2416 $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2418 case 'currentmonth1':
2419 $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2421 case 'currentmonthname':
2422 $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2424 case 'currentmonthnamegen':
2425 $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2427 case 'currentmonthabbrev':
2428 $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2431 $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2434 $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2437 $value = $wgContLang->formatNum( $localMonth );
2440 $value = $wgContLang->formatNum( $localMonth1 );
2442 case 'localmonthname':
2443 $value = $wgContLang->getMonthName( $localMonthName );
2445 case 'localmonthnamegen':
2446 $value = $wgContLang->getMonthNameGen( $localMonthName );
2448 case 'localmonthabbrev':
2449 $value = $wgContLang->getMonthAbbreviation( $localMonthName );
2452 $value = $wgContLang->formatNum( $localDay );
2455 $value = $wgContLang->formatNum( $localDay2 );
2458 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2461 $value = $this->mTitle
->getPartialURL();
2463 case 'fullpagename':
2464 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2466 case 'fullpagenamee':
2467 $value = $this->mTitle
->getPrefixedURL();
2470 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2472 case 'subpagenamee':
2473 $value = $this->mTitle
->getSubpageUrlForm();
2475 case 'basepagename':
2476 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2478 case 'basepagenamee':
2479 $value = wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2481 case 'talkpagename':
2482 if ( $this->mTitle
->canTalk() ) {
2483 $talkPage = $this->mTitle
->getTalkPage();
2484 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2489 case 'talkpagenamee':
2490 if ( $this->mTitle
->canTalk() ) {
2491 $talkPage = $this->mTitle
->getTalkPage();
2492 $value = $talkPage->getPrefixedUrl();
2497 case 'subjectpagename':
2498 $subjPage = $this->mTitle
->getSubjectPage();
2499 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2501 case 'subjectpagenamee':
2502 $subjPage = $this->mTitle
->getSubjectPage();
2503 $value = $subjPage->getPrefixedUrl();
2506 # Let the edit saving system know we should parse the page
2507 # *after* a revision ID has been assigned.
2508 $this->mOutput
->setFlag( 'vary-revision' );
2509 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2510 $value = $this->mRevisionId
;
2513 # Let the edit saving system know we should parse the page
2514 # *after* a revision ID has been assigned. This is for null edits.
2515 $this->mOutput
->setFlag( 'vary-revision' );
2516 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2517 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2519 case 'revisionday2':
2520 # Let the edit saving system know we should parse the page
2521 # *after* a revision ID has been assigned. This is for null edits.
2522 $this->mOutput
->setFlag( 'vary-revision' );
2523 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2524 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2526 case 'revisionmonth':
2527 # Let the edit saving system know we should parse the page
2528 # *after* a revision ID has been assigned. This is for null edits.
2529 $this->mOutput
->setFlag( 'vary-revision' );
2530 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2531 $value = substr( $this->getRevisionTimestamp(), 4, 2 );
2533 case 'revisionmonth1':
2534 # Let the edit saving system know we should parse the page
2535 # *after* a revision ID has been assigned. This is for null edits.
2536 $this->mOutput
->setFlag( 'vary-revision' );
2537 wfDebug( __METHOD__
. ": {{REVISIONMONTH1}} used, setting vary-revision...\n" );
2538 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2540 case 'revisionyear':
2541 # Let the edit saving system know we should parse the page
2542 # *after* a revision ID has been assigned. This is for null edits.
2543 $this->mOutput
->setFlag( 'vary-revision' );
2544 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2545 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2547 case 'revisiontimestamp':
2548 # Let the edit saving system know we should parse the page
2549 # *after* a revision ID has been assigned. This is for null edits.
2550 $this->mOutput
->setFlag( 'vary-revision' );
2551 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2552 $value = $this->getRevisionTimestamp();
2554 case 'revisionuser':
2555 # Let the edit saving system know we should parse the page
2556 # *after* a revision ID has been assigned. This is for null edits.
2557 $this->mOutput
->setFlag( 'vary-revision' );
2558 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2559 $value = $this->getRevisionUser();
2562 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2565 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2568 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2571 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2573 case 'subjectspace':
2574 $value = $this->mTitle
->getSubjectNsText();
2576 case 'subjectspacee':
2577 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2579 case 'currentdayname':
2580 $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2583 $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2586 $value = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2589 $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2592 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2593 # int to remove the padding
2594 $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2597 $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2599 case 'localdayname':
2600 $value = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2603 $value = $wgContLang->formatNum( $localYear, true );
2606 $value = $wgContLang->time( $localTimestamp, false, false );
2609 $value = $wgContLang->formatNum( $localHour, true );
2612 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2613 # int to remove the padding
2614 $value = $wgContLang->formatNum( (int)$localWeek );
2617 $value = $wgContLang->formatNum( $localDayOfWeek );
2619 case 'numberofarticles':
2620 $value = $wgContLang->formatNum( SiteStats
::articles() );
2622 case 'numberoffiles':
2623 $value = $wgContLang->formatNum( SiteStats
::images() );
2625 case 'numberofusers':
2626 $value = $wgContLang->formatNum( SiteStats
::users() );
2628 case 'numberofactiveusers':
2629 $value = $wgContLang->formatNum( SiteStats
::activeUsers() );
2631 case 'numberofpages':
2632 $value = $wgContLang->formatNum( SiteStats
::pages() );
2634 case 'numberofadmins':
2635 $value = $wgContLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2637 case 'numberofedits':
2638 $value = $wgContLang->formatNum( SiteStats
::edits() );
2640 case 'numberofviews':
2641 $value = $wgContLang->formatNum( SiteStats
::views() );
2643 case 'currenttimestamp':
2644 $value = wfTimestamp( TS_MW
, $ts );
2646 case 'localtimestamp':
2647 $value = $localTimestamp;
2649 case 'currentversion':
2650 $value = SpecialVersion
::getVersion();
2657 return $wgServerName;
2659 return $wgScriptPath;
2661 return $wgStylePath;
2662 case 'directionmark':
2663 return $wgContLang->getDirMark();
2664 case 'contentlanguage':
2665 global $wgContLanguageCode;
2666 return $wgContLanguageCode;
2669 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2677 $this->mVarCache
[$index] = $value;
2683 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2687 function initialiseVariables() {
2688 wfProfileIn( __METHOD__
);
2689 $variableIDs = MagicWord
::getVariableIDs();
2690 $substIDs = MagicWord
::getSubstIDs();
2692 $this->mVariables
= new MagicWordArray( $variableIDs );
2693 $this->mSubstWords
= new MagicWordArray( $substIDs );
2694 wfProfileOut( __METHOD__
);
2698 * Preprocess some wikitext and return the document tree.
2699 * This is the ghost of replace_variables().
2701 * @param string $text The text to parse
2702 * @param integer flags Bitwise combination of:
2703 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2704 * included. Default is to assume a direct page view.
2706 * The generated DOM tree must depend only on the input text and the flags.
2707 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2709 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2710 * change in the DOM tree for a given text, must be passed through the section identifier
2711 * in the section edit link and thus back to extractSections().
2713 * The output of this function is currently only cached in process memory, but a persistent
2714 * cache may be implemented at a later date which takes further advantage of these strict
2715 * dependency requirements.
2719 function preprocessToDom( $text, $flags = 0 ) {
2720 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2725 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2727 public static function splitWhitespace( $s ) {
2728 $ltrimmed = ltrim( $s );
2729 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2730 $trimmed = rtrim( $ltrimmed );
2731 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2733 $w2 = substr( $ltrimmed, -$diff );
2737 return array( $w1, $trimmed, $w2 );
2741 * Replace magic variables, templates, and template arguments
2742 * with the appropriate text. Templates are substituted recursively,
2743 * taking care to avoid infinite loops.
2745 * Note that the substitution depends on value of $mOutputType:
2746 * self::OT_WIKI: only {{subst:}} templates
2747 * self::OT_PREPROCESS: templates but not extension tags
2748 * self::OT_HTML: all templates and extension tags
2750 * @param string $tex The text to transform
2751 * @param PPFrame $frame Object describing the arguments passed to the template.
2752 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2753 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2754 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2757 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2758 # Is there any text? Also, Prevent too big inclusions!
2759 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2762 wfProfileIn( __METHOD__
);
2764 if ( $frame === false ) {
2765 $frame = $this->getPreprocessor()->newFrame();
2766 } elseif ( !( $frame instanceof PPFrame
) ) {
2767 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2768 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2771 $dom = $this->preprocessToDom( $text );
2772 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2773 $text = $frame->expand( $dom, $flags );
2775 wfProfileOut( __METHOD__
);
2779 # Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2780 static function createAssocArgs( $args ) {
2781 $assocArgs = array();
2783 foreach ( $args as $arg ) {
2784 $eqpos = strpos( $arg, '=' );
2785 if ( $eqpos === false ) {
2786 $assocArgs[$index++
] = $arg;
2788 $name = trim( substr( $arg, 0, $eqpos ) );
2789 $value = trim( substr( $arg, $eqpos+
1 ) );
2790 if ( $value === false ) {
2793 if ( $name !== false ) {
2794 $assocArgs[$name] = $value;
2803 * Warn the user when a parser limitation is reached
2804 * Will warn at most once the user per limitation type
2806 * @param string $limitationType, should be one of:
2807 * 'expensive-parserfunction' (corresponding messages:
2808 * 'expensive-parserfunction-warning',
2809 * 'expensive-parserfunction-category')
2810 * 'post-expand-template-argument' (corresponding messages:
2811 * 'post-expand-template-argument-warning',
2812 * 'post-expand-template-argument-category')
2813 * 'post-expand-template-inclusion' (corresponding messages:
2814 * 'post-expand-template-inclusion-warning',
2815 * 'post-expand-template-inclusion-category')
2816 * @params int $current, $max When an explicit limit has been
2817 * exceeded, provide the values (optional)
2819 function limitationWarn( $limitationType, $current=null, $max=null) {
2820 # does no harm if $current and $max are present but are unnecessary for the message
2821 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
2822 $this->mOutput
->addWarning( $warning );
2823 $this->addTrackingCategory( "$limitationType-category" );
2827 * Return the text of a template, after recursively
2828 * replacing any variables or templates within the template.
2830 * @param array $piece The parts of the template
2831 * $piece['title']: the title, i.e. the part before the |
2832 * $piece['parts']: the parameter array
2833 * $piece['lineStart']: whether the brace was at the start of a line
2834 * @param PPFrame The current frame, contains template arguments
2835 * @return string the text of the template
2838 function braceSubstitution( $piece, $frame ) {
2839 global $wgContLang, $wgNonincludableNamespaces;
2840 wfProfileIn( __METHOD__
);
2841 wfProfileIn( __METHOD__
.'-setup' );
2844 $found = false; # $text has been filled
2845 $nowiki = false; # wiki markup in $text should be escaped
2846 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2847 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2848 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2849 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2851 # Title object, where $text came from
2854 # $part1 is the bit before the first |, and must contain only title characters.
2855 # Various prefixes will be stripped from it later.
2856 $titleWithSpaces = $frame->expand( $piece['title'] );
2857 $part1 = trim( $titleWithSpaces );
2860 # Original title text preserved for various purposes
2861 $originalTitle = $part1;
2863 # $args is a list of argument nodes, starting from index 0, not including $part1
2864 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
2865 wfProfileOut( __METHOD__
.'-setup' );
2868 wfProfileIn( __METHOD__
.'-modifiers' );
2871 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
2873 # Possibilities for substMatch: "subst", "safesubst" or FALSE
2874 # Decide whether to expand template or keep wikitext as-is.
2875 if ( $this->ot
['wiki'] ) {
2876 if ( $substMatch === false ) {
2877 $literal = true; # literal when in PST with no prefix
2879 $literal = false; # expand when in PST with subst: or safesubst:
2882 if ( $substMatch == 'subst' ) {
2883 $literal = true; # literal when not in PST with plain subst:
2885 $literal = false; # expand when not in PST with safesubst: or no prefix
2889 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2896 if ( !$found && $args->getLength() == 0 ) {
2897 $id = $this->mVariables
->matchStartToEnd( $part1 );
2898 if ( $id !== false ) {
2899 $text = $this->getVariableValue( $id, $frame );
2900 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
2901 $this->mOutput
->mContainsOldMagic
= true;
2907 # MSG, MSGNW and RAW
2910 $mwMsgnw = MagicWord
::get( 'msgnw' );
2911 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2914 # Remove obsolete MSG:
2915 $mwMsg = MagicWord
::get( 'msg' );
2916 $mwMsg->matchStartAndRemove( $part1 );
2920 $mwRaw = MagicWord
::get( 'raw' );
2921 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2922 $forceRawInterwiki = true;
2925 wfProfileOut( __METHOD__
.'-modifiers' );
2929 wfProfileIn( __METHOD__
. '-pfunc' );
2931 $colonPos = strpos( $part1, ':' );
2932 if ( $colonPos !== false ) {
2933 # Case sensitive functions
2934 $function = substr( $part1, 0, $colonPos );
2935 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2936 $function = $this->mFunctionSynonyms
[1][$function];
2938 # Case insensitive functions
2939 $function = $wgContLang->lc( $function );
2940 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2941 $function = $this->mFunctionSynonyms
[0][$function];
2947 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2948 $initialArgs = array( &$this );
2949 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2950 if ( $flags & SFH_OBJECT_ARGS
) {
2951 # Add a frame parameter, and pass the arguments as an array
2952 $allArgs = $initialArgs;
2953 $allArgs[] = $frame;
2954 for ( $i = 0; $i < $args->getLength(); $i++
) {
2955 $funcArgs[] = $args->item( $i );
2957 $allArgs[] = $funcArgs;
2959 # Convert arguments to plain text
2960 for ( $i = 0; $i < $args->getLength(); $i++
) {
2961 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2963 $allArgs = array_merge( $initialArgs, $funcArgs );
2966 # Workaround for PHP bug 35229 and similar
2967 if ( !is_callable( $callback ) ) {
2968 wfProfileOut( __METHOD__
. '-pfunc' );
2969 wfProfileOut( __METHOD__
);
2970 throw new MWException( "Tag hook for $function is not callable\n" );
2972 $result = call_user_func_array( $callback, $allArgs );
2975 $preprocessFlags = 0;
2977 if ( is_array( $result ) ) {
2978 if ( isset( $result[0] ) ) {
2980 unset( $result[0] );
2983 # Extract flags into the local scope
2984 # This allows callers to set flags such as nowiki, found, etc.
2990 $text = $this->preprocessToDom( $text, $preprocessFlags );
2995 wfProfileOut( __METHOD__
. '-pfunc' );
2998 # Finish mangling title and then check for loops.
2999 # Set $title to a Title object and $titleText to the PDBK
3002 # Split the title into page and subpage
3004 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
3005 if ( $subpage !== '' ) {
3006 $ns = $this->mTitle
->getNamespace();
3008 $title = Title
::newFromText( $part1, $ns );
3010 $titleText = $title->getPrefixedText();
3011 # Check for language variants if the template is not found
3012 if ( $wgContLang->hasVariants() && $title->getArticleID() == 0 ) {
3013 $wgContLang->findVariantLink( $part1, $title, true );
3015 # Do recursion depth check
3016 $limit = $this->mOptions
->getMaxTemplateDepth();
3017 if ( $frame->depth
>= $limit ) {
3019 $text = '<span class="error">'
3020 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
3026 # Load from database
3027 if ( !$found && $title ) {
3028 wfProfileIn( __METHOD__
. '-loadtpl' );
3029 if ( !$title->isExternal() ) {
3030 if ( $title->getNamespace() == NS_SPECIAL
3031 && $this->mOptions
->getAllowSpecialInclusion()
3032 && $this->ot
['html'] )
3034 $text = SpecialPage
::capturePath( $title );
3035 if ( is_string( $text ) ) {
3038 $this->disableCache();
3040 } elseif ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3041 $found = false; # access denied
3042 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3044 list( $text, $title ) = $this->getTemplateDom( $title );
3045 if ( $text !== false ) {
3051 # If the title is valid but undisplayable, make a link to it
3052 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3053 $text = "[[:$titleText]]";
3056 } elseif ( $title->isTrans() ) {
3057 # Interwiki transclusion
3058 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3059 $text = $this->interwikiTransclude( $title, 'render' );
3062 $text = $this->interwikiTransclude( $title, 'raw' );
3063 # Preprocess it like a template
3064 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3070 # Do infinite loop check
3071 # This has to be done after redirect resolution to avoid infinite loops via redirects
3072 if ( !$frame->loopCheck( $title ) ) {
3074 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3075 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3077 wfProfileOut( __METHOD__
. '-loadtpl' );
3080 # If we haven't found text to substitute by now, we're done
3081 # Recover the source wikitext and return it
3083 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3084 wfProfileOut( __METHOD__
);
3085 return array( 'object' => $text );
3088 # Expand DOM-style return values in a child frame
3089 if ( $isChildObj ) {
3090 # Clean up argument array
3091 $newFrame = $frame->newChild( $args, $title );
3094 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3095 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3096 # Expansion is eligible for the empty-frame cache
3097 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3098 $text = $this->mTplExpandCache
[$titleText];
3100 $text = $newFrame->expand( $text );
3101 $this->mTplExpandCache
[$titleText] = $text;
3104 # Uncached expansion
3105 $text = $newFrame->expand( $text );
3108 if ( $isLocalObj && $nowiki ) {
3109 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3110 $isLocalObj = false;
3113 # Replace raw HTML by a placeholder
3114 # Add a blank line preceding, to prevent it from mucking up
3115 # immediately preceding headings
3117 $text = "\n\n" . $this->insertStripItem( $text );
3118 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3119 # Escape nowiki-style return values
3120 $text = wfEscapeWikiText( $text );
3121 } elseif ( is_string( $text )
3122 && !$piece['lineStart']
3123 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3125 # Bug 529: if the template begins with a table or block-level
3126 # element, it should be treated as beginning a new line.
3127 # This behaviour is somewhat controversial.
3128 $text = "\n" . $text;
3131 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3132 # Error, oversize inclusion
3133 $text = "[[$originalTitle]]" .
3134 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3135 $this->limitationWarn( 'post-expand-template-inclusion' );
3138 if ( $isLocalObj ) {
3139 $ret = array( 'object' => $text );
3141 $ret = array( 'text' => $text );
3144 wfProfileOut( __METHOD__
);
3149 * Get the semi-parsed DOM representation of a template with a given title,
3150 * and its redirect destination title. Cached.
3152 function getTemplateDom( $title ) {
3153 $cacheTitle = $title;
3154 $titleText = $title->getPrefixedDBkey();
3156 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3157 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3158 $title = Title
::makeTitle( $ns, $dbk );
3159 $titleText = $title->getPrefixedDBkey();
3161 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3162 return array( $this->mTplDomCache
[$titleText], $title );
3165 # Cache miss, go to the database
3166 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3168 if ( $text === false ) {
3169 $this->mTplDomCache
[$titleText] = false;
3170 return array( false, $title );
3173 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3174 $this->mTplDomCache
[ $titleText ] = $dom;
3176 if ( !$title->equals( $cacheTitle ) ) {
3177 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3178 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3181 return array( $dom, $title );
3185 * Fetch the unparsed text of a template and register a reference to it.
3187 function fetchTemplateAndTitle( $title ) {
3188 $templateCb = $this->mOptions
->getTemplateCallback();
3189 $stuff = call_user_func( $templateCb, $title, $this );
3190 $text = $stuff['text'];
3191 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3192 if ( isset( $stuff['deps'] ) ) {
3193 foreach ( $stuff['deps'] as $dep ) {
3194 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3197 return array( $text, $finalTitle );
3200 function fetchTemplate( $title ) {
3201 $rv = $this->fetchTemplateAndTitle( $title );
3206 * Static function to get a template
3207 * Can be overridden via ParserOptions::setTemplateCallback().
3209 static function statelessFetchTemplate( $title, $parser=false ) {
3210 $text = $skip = false;
3211 $finalTitle = $title;
3214 # Loop to fetch the article, with up to 1 redirect
3215 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3216 # Give extensions a chance to select the revision instead
3217 $id = false; # Assume current
3218 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3224 'page_id' => $title->getArticleID(),
3228 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3229 $rev_id = $rev ?
$rev->getId() : 0;
3230 # If there is no current revision, there is no page
3231 if ( $id === false && !$rev ) {
3232 $linkCache = LinkCache
::singleton();
3233 $linkCache->addBadLinkObj( $title );
3238 'page_id' => $title->getArticleID(),
3239 'rev_id' => $rev_id );
3242 $text = $rev->getText();
3243 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3245 $message = $wgContLang->lcfirst( $title->getText() );
3246 $text = wfMsgForContentNoTrans( $message );
3247 if ( wfEmptyMsg( $message, $text ) ) {
3254 if ( $text === false ) {
3258 $finalTitle = $title;
3259 $title = Title
::newFromRedirect( $text );
3263 'finalTitle' => $finalTitle,
3268 * Transclude an interwiki link.
3270 function interwikiTransclude( $title, $action ) {
3271 global $wgEnableScaryTranscluding;
3273 if ( !$wgEnableScaryTranscluding ) {
3274 return wfMsg('scarytranscludedisabled');
3277 $url = $title->getFullUrl( "action=$action" );
3279 if ( strlen( $url ) > 255 ) {
3280 return wfMsg( 'scarytranscludetoolong' );
3282 return $this->fetchScaryTemplateMaybeFromCache( $url );
3285 function fetchScaryTemplateMaybeFromCache( $url ) {
3286 global $wgTranscludeCacheExpiry;
3287 $dbr = wfGetDB( DB_SLAVE
);
3288 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3289 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3290 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3292 return $obj->tc_contents
;
3295 $text = Http
::get( $url );
3297 return wfMsg( 'scarytranscludefailed', $url );
3300 $dbw = wfGetDB( DB_MASTER
);
3301 $dbw->replace( 'transcache', array('tc_url'), array(
3303 'tc_time' => $dbw->timestamp( time() ),
3304 'tc_contents' => $text)
3311 * Triple brace replacement -- used for template arguments
3314 function argSubstitution( $piece, $frame ) {
3315 wfProfileIn( __METHOD__
);
3318 $parts = $piece['parts'];
3319 $nameWithSpaces = $frame->expand( $piece['title'] );
3320 $argName = trim( $nameWithSpaces );
3322 $text = $frame->getArgument( $argName );
3323 if ( $text === false && $parts->getLength() > 0
3327 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3330 # No match in frame, use the supplied default
3331 $object = $parts->item( 0 )->getChildren();
3333 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3334 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3335 $this->limitationWarn( 'post-expand-template-argument' );
3338 if ( $text === false && $object === false ) {
3340 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3342 if ( $error !== false ) {
3345 if ( $object !== false ) {
3346 $ret = array( 'object' => $object );
3348 $ret = array( 'text' => $text );
3351 wfProfileOut( __METHOD__
);
3356 * Return the text to be used for a given extension tag.
3357 * This is the ghost of strip().
3359 * @param array $params Associative array of parameters:
3360 * name PPNode for the tag name
3361 * attr PPNode for unparsed text where tag attributes are thought to be
3362 * attributes Optional associative array of parsed attributes
3363 * inner Contents of extension element
3364 * noClose Original text did not have a close tag
3365 * @param PPFrame $frame
3367 function extensionSubstitution( $params, $frame ) {
3368 global $wgRawHtml, $wgContLang;
3370 $name = $frame->expand( $params['name'] );
3371 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3372 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3373 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3375 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3376 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3377 if ( $isFunctionTag ) {
3378 $markerType = 'none';
3380 $markerType = 'general';
3382 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3383 $name = strtolower( $name );
3384 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3385 if ( isset( $params['attributes'] ) ) {
3386 $attributes = $attributes +
$params['attributes'];
3389 if ( isset( $this->mTagHooks
[$name] ) ) {
3390 # Workaround for PHP bug 35229 and similar
3391 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3392 throw new MWException( "Tag hook for $name is not callable\n" );
3394 $output = call_user_func_array( $this->mTagHooks
[$name],
3395 array( $content, $attributes, $this, $frame ) );
3396 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3397 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3398 if ( !is_callable( $callback ) ) {
3399 throw new MWException( "Tag hook for $name is not callable\n" );
3402 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3404 $output = '<span class="error">Invalid tag extension name: ' .
3405 htmlspecialchars( $name ) . '</span>';
3408 if ( is_array( $output ) ) {
3409 # Extract flags to local scope (to override $markerType)
3411 $output = $flags[0];
3416 if ( is_null( $attrText ) ) {
3419 if ( isset( $params['attributes'] ) ) {
3420 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3421 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3422 htmlspecialchars( $attrValue ) . '"';
3425 if ( $content === null ) {
3426 $output = "<$name$attrText/>";
3428 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3429 $output = "<$name$attrText>$content$close";
3433 if ( $markerType === 'none' ) {
3435 } elseif ( $markerType === 'nowiki' ) {
3436 $this->mStripState
->nowiki
->setPair( $marker, $output );
3437 } elseif ( $markerType === 'general' ) {
3438 $this->mStripState
->general
->setPair( $marker, $output );
3440 throw new MWException( __METHOD__
.': invalid marker type' );
3446 * Increment an include size counter
3448 * @param string $type The type of expansion
3449 * @param integer $size The size of the text
3450 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3452 function incrementIncludeSize( $type, $size ) {
3453 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3456 $this->mIncludeSizes
[$type] +
= $size;
3462 * Increment the expensive function count
3464 * @return boolean False if the limit has been exceeded
3466 function incrementExpensiveFunctionCount() {
3467 global $wgExpensiveParserFunctionLimit;
3468 $this->mExpensiveFunctionCount++
;
3469 if ( $this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit ) {
3476 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3477 * Fills $this->mDoubleUnderscores, returns the modified text
3479 function doDoubleUnderscore( $text ) {
3480 wfProfileIn( __METHOD__
);
3482 # The position of __TOC__ needs to be recorded
3483 $mw = MagicWord
::get( 'toc' );
3484 if ( $mw->match( $text ) ) {
3485 $this->mShowToc
= true;
3486 $this->mForceTocPosition
= true;
3488 # Set a placeholder. At the end we'll fill it in with the TOC.
3489 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3491 # Only keep the first one.
3492 $text = $mw->replace( '', $text );
3495 # Now match and remove the rest of them
3496 $mwa = MagicWord
::getDoubleUnderscoreArray();
3497 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3499 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3500 $this->mOutput
->mNoGallery
= true;
3502 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3503 $this->mShowToc
= false;
3505 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3506 $this->mOutput
->setProperty( 'hiddencat', 'y' );
3507 $this->addTrackingCategory( 'hidden-category-category' );
3509 # (bug 8068) Allow control over whether robots index a page.
3511 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3512 # is not desirable, the last one on the page should win.
3513 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3514 $this->mOutput
->setIndexPolicy( 'noindex' );
3515 $this->addTrackingCategory( 'noindex-category' );
3517 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3518 $this->mOutput
->setIndexPolicy( 'index' );
3519 $this->addTrackingCategory( 'index-category' );
3522 wfProfileOut( __METHOD__
);
3527 * Add a tracking category, getting the title from a system message,
3528 * or print a debug message if the title is invalid.
3529 * @param $msg String message key
3530 * @return Bool whether the addition was successful
3532 protected function addTrackingCategory( $msg ) {
3533 $cat = wfMsgForContent( $msg );
3535 # Allow tracking categories to be disabled by setting them to "-"
3536 if ( $cat === '-' ) {
3540 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3541 if ( $containerCategory ) {
3542 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3545 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3551 * This function accomplishes several tasks:
3552 * 1) Auto-number headings if that option is enabled
3553 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3554 * 3) Add a Table of contents on the top for users who have enabled the option
3555 * 4) Auto-anchor headings
3557 * It loops through all headlines, collects the necessary data, then splits up the
3558 * string and re-inserts the newly formatted headlines.
3560 * @param string $text
3561 * @param string $origText Original, untouched wikitext
3562 * @param boolean $isMain
3565 function formatHeadings( $text, $origText, $isMain=true ) {
3566 global $wgMaxTocLevel, $wgContLang, $wgHtml5, $wgExperimentalHtmlIds;
3568 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3569 $showEditLink = $this->mOptions
->getEditSection();
3571 # Do not call quickUserCan unless necessary
3572 if ( $showEditLink && !$this->mTitle
->quickUserCan( 'edit' ) ) {
3576 # Inhibit editsection links if requested in the page
3577 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ||
$this->mOptions
->getIsPrintable() ) {
3581 # Get all headlines for numbering them and adding funky stuff like [edit]
3582 # links - this is for later, but we need the number of headlines right now
3584 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3586 # if there are fewer than 4 headlines in the article, do not show TOC
3587 # unless it's been explicitly enabled.
3588 $enoughToc = $this->mShowToc
&&
3589 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
3591 # Allow user to stipulate that a page should have a "new section"
3592 # link added via __NEWSECTIONLINK__
3593 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3594 $this->mOutput
->setNewSection( true );
3597 # Allow user to remove the "new section"
3598 # link via __NONEWSECTIONLINK__
3599 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3600 $this->mOutput
->hideNewSection( true );
3603 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3604 # override above conditions and always show TOC above first header
3605 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3606 $this->mShowToc
= true;
3610 # We need this to perform operations on the HTML
3611 $sk = $this->mOptions
->getSkin();
3617 # Ugh .. the TOC should have neat indentation levels which can be
3618 # passed to the skin functions. These are determined here
3622 $sublevelCount = array();
3623 $levelCount = array();
3629 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3630 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3631 $oldType = $this->mOutputType
;
3632 $this->setOutputType( self
::OT_WIKI
);
3633 $frame = $this->getPreprocessor()->newFrame();
3634 $root = $this->preprocessToDom( $origText );
3635 $node = $root->getFirstChild();
3639 foreach ( $matches[3] as $headline ) {
3640 $isTemplate = false;
3642 $sectionIndex = false;
3644 $markerMatches = array();
3645 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
3646 $serial = $markerMatches[1];
3647 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3648 $isTemplate = ( $titleText != $baseTitleText );
3649 $headline = preg_replace( "/^$markerRegex/", "", $headline );
3653 $prevlevel = $level;
3654 $prevtoclevel = $toclevel;
3656 $level = $matches[1][$headlineCount];
3658 if ( $level > $prevlevel ) {
3659 # Increase TOC level
3661 $sublevelCount[$toclevel] = 0;
3662 if ( $toclevel<$wgMaxTocLevel ) {
3663 $prevtoclevel = $toclevel;
3664 $toc .= $sk->tocIndent();
3667 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
3668 # Decrease TOC level, find level to jump to
3670 for ( $i = $toclevel; $i > 0; $i-- ) {
3671 if ( $levelCount[$i] == $level ) {
3672 # Found last matching level
3675 } elseif ( $levelCount[$i] < $level ) {
3676 # Found first matching level below current level
3684 if ( $toclevel<$wgMaxTocLevel ) {
3685 if ( $prevtoclevel < $wgMaxTocLevel ) {
3686 # Unindent only if the previous toc level was shown :p
3687 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3688 $prevtoclevel = $toclevel;
3690 $toc .= $sk->tocLineEnd();
3694 # No change in level, end TOC line
3695 if ( $toclevel<$wgMaxTocLevel ) {
3696 $toc .= $sk->tocLineEnd();
3700 $levelCount[$toclevel] = $level;
3702 # count number of headlines for each level
3703 @$sublevelCount[$toclevel]++
;
3705 for( $i = 1; $i <= $toclevel; $i++
) {
3706 if ( !empty( $sublevelCount[$i] ) ) {
3710 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3715 # The safe header is a version of the header text safe to use for links
3716 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3717 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3719 # Remove link placeholders by the link text.
3720 # <!--LINK number-->
3722 # link text with suffix
3723 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3725 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3726 $tocline = preg_replace(
3727 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3728 array( '', '<$1>' ),
3731 $tocline = trim( $tocline );
3733 # For the anchor, strip out HTML-y stuff period
3734 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3735 $safeHeadline = preg_replace( '/[ _]+/', ' ', $safeHeadline );
3736 $safeHeadline = trim( $safeHeadline );
3738 # Save headline for section edit hint before it's escaped
3739 $headlineHint = $safeHeadline;
3741 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
3742 # For reverse compatibility, provide an id that's
3743 # HTML4-compatible, like we used to.
3745 # It may be worth noting, academically, that it's possible for
3746 # the legacy anchor to conflict with a non-legacy headline
3747 # anchor on the page. In this case likely the "correct" thing
3748 # would be to either drop the legacy anchors or make sure
3749 # they're numbered first. However, this would require people
3750 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3751 # manually, so let's not bother worrying about it.
3752 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
3753 array( 'noninitial', 'legacy' ) );
3754 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3756 if ( $legacyHeadline == $safeHeadline ) {
3757 # No reason to have both (in fact, we can't)
3758 $legacyHeadline = false;
3761 $legacyHeadline = false;
3762 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
3766 # HTML names must be case-insensitively unique (bug 10721). FIXME:
3767 # Does this apply to Unicode characters? Because we aren't
3768 # handling those here.
3769 $arrayKey = strtolower( $safeHeadline );
3770 if ( $legacyHeadline === false ) {
3771 $legacyArrayKey = false;
3773 $legacyArrayKey = strtolower( $legacyHeadline );
3776 # count how many in assoc. array so we can track dupes in anchors
3777 if ( isset( $refers[$arrayKey] ) ) {
3778 $refers[$arrayKey]++
;
3780 $refers[$arrayKey] = 1;
3782 if ( isset( $refers[$legacyArrayKey] ) ) {
3783 $refers[$legacyArrayKey]++
;
3785 $refers[$legacyArrayKey] = 1;
3788 # Don't number the heading if it is the only one (looks silly)
3789 if ( $doNumberHeadings && count( $matches[3] ) > 1) {
3790 # the two are different if the line contains a link
3791 $headline = $numbering . ' ' . $headline;
3794 # Create the anchor for linking from the TOC to the section
3795 $anchor = $safeHeadline;
3796 $legacyAnchor = $legacyHeadline;
3797 if ( $refers[$arrayKey] > 1 ) {
3798 $anchor .= '_' . $refers[$arrayKey];
3800 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3801 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3803 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
3804 $toc .= $sk->tocLine( $anchor, $tocline,
3805 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
3808 # Add the section to the section tree
3809 # Find the DOM node for this header
3810 while ( $node && !$isTemplate ) {
3811 if ( $node->getName() === 'h' ) {
3812 $bits = $node->splitHeading();
3813 if ( $bits['i'] == $sectionIndex )
3816 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
3817 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
3818 $node = $node->getNextSibling();
3821 'toclevel' => $toclevel,
3824 'number' => $numbering,
3825 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
3826 'fromtitle' => $titleText,
3827 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
3828 'anchor' => $anchor,
3831 # give headline the correct <h#> tag
3832 if ( $showEditLink && $sectionIndex !== false ) {
3833 if ( $isTemplate ) {
3834 # Put a T flag in the section identifier, to indicate to extractSections()
3835 # that sections inside <includeonly> should be counted.
3836 $editlink = $sk->doEditSectionLink( Title
::newFromText( $titleText ), "T-$sectionIndex" );
3838 $editlink = $sk->doEditSectionLink( $this->mTitle
, $sectionIndex, $headlineHint );
3843 $head[$headlineCount] = $sk->makeHeadline( $level,
3844 $matches['attrib'][$headlineCount], $anchor, $headline,
3845 $editlink, $legacyAnchor );
3850 $this->setOutputType( $oldType );
3852 # Never ever show TOC if no headers
3853 if ( $numVisible < 1 ) {
3858 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3859 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3861 $toc = $sk->tocList( $toc );
3862 $this->mOutput
->setTOCHTML( $toc );
3866 $this->mOutput
->setSections( $tocraw );
3869 # split up and insert constructed headlines
3871 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3874 foreach ( $blocks as $block ) {
3875 if ( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3876 # This is the [edit] link that appears for the top block of text when
3877 # section editing is enabled
3879 # Disabled because it broke block formatting
3880 # For example, a bullet point in the top line
3881 # $full .= $sk->editSectionLink(0);
3884 if ( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3885 # Top anchor now in skin
3889 if ( !empty( $head[$i] ) ) {
3894 if ( $this->mForceTocPosition
) {
3895 return str_replace( '<!--MWTOC-->', $toc, $full );
3902 * Merge $tree2 into $tree1 by replacing the section with index
3903 * $section in $tree1 and its descendants with the sections in $tree2.
3904 * Note that in the returned section tree, only the 'index' and
3905 * 'byteoffset' fields are guaranteed to be correct.
3906 * @param $tree1 array Section tree from ParserOutput::getSectons()
3907 * @param $tree2 array Section tree
3908 * @param $section int Section index
3909 * @param $title Title Title both section trees come from
3910 * @param $len2 int Length of the original wikitext for $tree2
3911 * @return array Merged section tree
3913 public static function mergeSectionTrees( $tree1, $tree2, $section, $title, $len2 ) {
3916 $targetLevel = false;
3920 $numbering = array( 0 );
3921 $titletext = $title->getPrefixedDBkey();
3922 foreach ( $tree1 as $s ) {
3923 if ( $targetLevel !== false ) {
3924 if ( $s['level'] <= $targetLevel ) {
3925 # We've skipped enough
3926 $targetLevel = false;
3931 if ( $s['index'] != $section ||
3932 $s['fromtitle'] != $titletext ) {
3933 self
::incrementNumbering( $numbering,
3934 $s['toclevel'], $lastLevel );
3936 # Rewrite index, byteoffset and number
3937 if ( $s['fromtitle'] == $titletext ) {
3938 $s['index'] = $nextIndex++
;
3940 $s['byteoffset'] +
= $len2;
3943 $s['number'] = implode( '.', array_map(
3944 array( $wgContLang, 'formatnum' ),
3946 $lastLevel = $s['toclevel'];
3950 # Insert sections from $tree2 here
3951 foreach ( $tree2 as $s2 ) {
3952 # Rewrite the fields in $s2
3953 # before inserting it
3954 $s2['toclevel'] +
= $s['toclevel'] - 1;
3955 $s2['level'] +
= $s['level'] - 1;
3956 $s2['index'] = $nextIndex++
;
3957 $s2['byteoffset'] +
= $s['byteoffset'];
3959 self
::incrementNumbering( $numbering,
3960 $s2['toclevel'], $lastLevel );
3961 $s2['number'] = implode( '.', array_map(
3962 array( $wgContLang, 'formatnum' ),
3964 $lastLevel = $s2['toclevel'];
3967 # Skip all descendants of $section in $tree1
3968 $targetLevel = $s['level'];
3976 * Increment a section number. Helper function for mergeSectionTrees()
3977 * @param $number array Array representing a section number
3978 * @param $level int Current TOC level (depth)
3979 * @param $lastLevel int Level of previous TOC entry
3981 private static function incrementNumbering( &$number, $level, $lastLevel ) {
3982 if ( $level > $lastLevel ) {
3983 $number[$level - 1] = 1;
3984 } elseif ( $level < $lastLevel ) {
3985 foreach ( $number as $key => $unused )
3986 if ( $key >= $level ) {
3987 unset( $number[$key] );
3989 $number[$level - 1]++
;
3991 $number[$level - 1]++
;
3996 * Transform wiki markup when saving a page by doing \r\n -> \n
3997 * conversion, substitting signatures, {{subst:}} templates, etc.
3999 * @param string $text the text to transform
4000 * @param Title &$title the Title object for the current article
4001 * @param User $user the User object describing the current user
4002 * @param ParserOptions $options parsing options
4003 * @param bool $clearState whether to clear the parser state first
4004 * @return string the altered wiki markup
4007 function preSaveTransform( $text, Title
$title, $user, $options, $clearState = true ) {
4008 $this->mOptions
= $options;
4009 $this->setTitle( $title );
4010 $this->setOutputType( self
::OT_WIKI
);
4012 if ( $clearState ) {
4013 $this->clearState();
4019 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4020 $text = $this->pstPass2( $text, $user );
4021 $text = $this->mStripState
->unstripBoth( $text );
4026 * Pre-save transform helper function
4029 function pstPass2( $text, $user ) {
4030 global $wgContLang, $wgLocaltimezone;
4032 # Note: This is the timestamp saved as hardcoded wikitext to
4033 # the database, we use $wgContLang here in order to give
4034 # everyone the same signature and use the default one rather
4035 # than the one selected in each user's preferences.
4036 # (see also bug 12815)
4037 $ts = $this->mOptions
->getTimestamp();
4038 if ( isset( $wgLocaltimezone ) ) {
4039 $tz = $wgLocaltimezone;
4041 $tz = date_default_timezone_get();
4044 $unixts = wfTimestamp( TS_UNIX
, $ts );
4045 $oldtz = date_default_timezone_get();
4046 date_default_timezone_set( $tz );
4047 $ts = date( 'YmdHis', $unixts );
4048 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4050 # Allow translation of timezones trough wiki. date() can return
4051 # whatever crap the system uses, localised or not, so we cannot
4052 # ship premade translations.
4053 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4054 $value = wfMsgForContent( $key );
4055 if ( !wfEmptyMsg( $key, $value ) ) {
4059 date_default_timezone_set( $oldtz );
4061 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4063 # Variable replacement
4064 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4065 $text = $this->replaceVariables( $text );
4068 $sigText = $this->getUserSig( $user );
4069 $text = strtr( $text, array(
4071 '~~~~' => "$sigText $d",
4075 # Context links: [[|name]] and [[name (context)|]]
4076 global $wgLegalTitleChars;
4077 $tc = "[$wgLegalTitleChars]";
4078 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4080 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4081 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
4082 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4083 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4085 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4086 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4087 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4088 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4090 $t = $this->mTitle
->getText();
4092 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4093 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4094 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4095 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4097 # if there's no context, don't bother duplicating the title
4098 $text = preg_replace( $p2, '[[\\1]]', $text );
4101 # Trim trailing whitespace
4102 $text = rtrim( $text );
4108 * Fetch the user's signature text, if any, and normalize to
4109 * validated, ready-to-insert wikitext.
4110 * If you have pre-fetched the nickname or the fancySig option, you can
4111 * specify them here to save a database query.
4116 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4117 global $wgMaxSigChars;
4119 $username = $user->getName();
4121 # If not given, retrieve from the user object.
4122 if ( $nickname === false )
4123 $nickname = $user->getOption( 'nickname' );
4125 if ( is_null( $fancySig ) ) {
4126 $fancySig = $user->getBoolOption( 'fancysig' );
4129 $nickname = $nickname == null ?
$username : $nickname;
4131 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4132 $nickname = $username;
4133 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4134 } elseif ( $fancySig !== false ) {
4135 # Sig. might contain markup; validate this
4136 if ( $this->validateSig( $nickname ) !== false ) {
4137 # Validated; clean up (if needed) and return it
4138 return $this->cleanSig( $nickname, true );
4140 # Failed to validate; fall back to the default
4141 $nickname = $username;
4142 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4146 # Make sure nickname doesnt get a sig in a sig
4147 $nickname = $this->cleanSigInSig( $nickname );
4149 # If we're still here, make it a link to the user page
4150 $userText = wfEscapeWikiText( $username );
4151 $nickText = wfEscapeWikiText( $nickname );
4152 if ( $user->isAnon() ) {
4153 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4155 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4160 * Check that the user's signature contains no bad XML
4162 * @param string $text
4163 * @return mixed An expanded string, or false if invalid.
4165 function validateSig( $text ) {
4166 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4170 * Clean up signature text
4172 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4173 * 2) Substitute all transclusions
4175 * @param string $text
4176 * @param $parsing Whether we're cleaning (preferences save) or parsing
4177 * @return string Signature text
4179 function cleanSig( $text, $parsing = false ) {
4182 $this->clearState();
4183 $this->setTitle( $wgTitle );
4184 $this->mOptions
= new ParserOptions
;
4185 $this->setOutputType
= self
::OT_PREPROCESS
;
4188 # Option to disable this feature
4189 if ( !$this->mOptions
->getCleanSignatures() ) {
4193 # FIXME: regex doesn't respect extension tags or nowiki
4194 # => Move this logic to braceSubstitution()
4195 $substWord = MagicWord
::get( 'subst' );
4196 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4197 $substText = '{{' . $substWord->getSynonym( 0 );
4199 $text = preg_replace( $substRegex, $substText, $text );
4200 $text = $this->cleanSigInSig( $text );
4201 $dom = $this->preprocessToDom( $text );
4202 $frame = $this->getPreprocessor()->newFrame();
4203 $text = $frame->expand( $dom );
4206 $text = $this->mStripState
->unstripBoth( $text );
4213 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4214 * @param string $text
4215 * @return string Signature text with /~{3,5}/ removed
4217 function cleanSigInSig( $text ) {
4218 $text = preg_replace( '/~{3,5}/', '', $text );
4223 * Set up some variables which are usually set up in parse()
4224 * so that an external function can call some class members with confidence
4227 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
4228 $this->setTitle( $title );
4229 $this->mOptions
= $options;
4230 $this->setOutputType( $outputType );
4231 if ( $clearState ) {
4232 $this->clearState();
4237 * Wrapper for preprocess()
4239 * @param string $text the text to preprocess
4240 * @param ParserOptions $options options
4244 function transformMsg( $text, $options ) {
4246 static $executing = false;
4248 # Guard against infinite recursion
4254 wfProfileIn( __METHOD__
);
4255 $text = $this->preprocess( $text, $wgTitle, $options );
4258 wfProfileOut( __METHOD__
);
4263 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4264 * The callback should have the following form:
4265 * function myParserHook( $text, $params, $parser ) { ... }
4267 * Transform and return $text. Use $parser for any required context, e.g. use
4268 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4272 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
4273 * @param mixed $callback The callback function (and object) to use for the tag
4275 * @return The old value of the mTagHooks array associated with the hook
4277 function setHook( $tag, $callback ) {
4278 $tag = strtolower( $tag );
4279 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4280 $this->mTagHooks
[$tag] = $callback;
4281 if ( !in_array( $tag, $this->mStripList
) ) {
4282 $this->mStripList
[] = $tag;
4288 function setTransparentTagHook( $tag, $callback ) {
4289 $tag = strtolower( $tag );
4290 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4291 $this->mTransparentTagHooks
[$tag] = $callback;
4297 * Remove all tag hooks
4299 function clearTagHooks() {
4300 $this->mTagHooks
= array();
4301 $this->mStripList
= $this->mDefaultStripList
;
4305 * Create a function, e.g. {{sum:1|2|3}}
4306 * The callback function should have the form:
4307 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4309 * Or with SFH_OBJECT_ARGS:
4310 * function myParserFunction( $parser, $frame, $args ) { ... }
4312 * The callback may either return the text result of the function, or an array with the text
4313 * in element 0, and a number of flags in the other elements. The names of the flags are
4314 * specified in the keys. Valid flags are:
4315 * found The text returned is valid, stop processing the template. This
4317 * nowiki Wiki markup in the return value should be escaped
4318 * isHTML The returned text is HTML, armour it against wikitext transformation
4322 * @param string $id The magic word ID
4323 * @param mixed $callback The callback function (and object) to use
4324 * @param integer $flags a combination of the following flags:
4325 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4327 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4328 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4329 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4330 * the arguments, and to control the way they are expanded.
4332 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4333 * arguments, for instance:
4334 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4336 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4337 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4338 * working if/when this is changed.
4340 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4343 * Please read the documentation in includes/parser/Preprocessor.php for more information
4344 * about the methods available in PPFrame and PPNode.
4346 * @return The old callback function for this name, if any
4348 function setFunctionHook( $id, $callback, $flags = 0 ) {
4351 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4352 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4354 # Add to function cache
4355 $mw = MagicWord
::get( $id );
4357 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4359 $synonyms = $mw->getSynonyms();
4360 $sensitive = intval( $mw->isCaseSensitive() );
4362 foreach ( $synonyms as $syn ) {
4364 if ( !$sensitive ) {
4365 $syn = $wgContLang->lc( $syn );
4368 if ( !( $flags & SFH_NO_HASH
) ) {
4371 # Remove trailing colon
4372 if ( substr( $syn, -1, 1 ) === ':' ) {
4373 $syn = substr( $syn, 0, -1 );
4375 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4381 * Get all registered function hook identifiers
4385 function getFunctionHooks() {
4386 return array_keys( $this->mFunctionHooks
);
4390 * Create a tag function, e.g. <test>some stuff</test>.
4391 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4392 * Unlike parser functions, their content is not preprocessed.
4394 function setFunctionTagHook( $tag, $callback, $flags ) {
4395 $tag = strtolower( $tag );
4396 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4397 $this->mFunctionTagHooks
[$tag] : null;
4398 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4400 if ( !in_array( $tag, $this->mStripList
) ) {
4401 $this->mStripList
[] = $tag;
4408 * FIXME: update documentation. makeLinkObj() is deprecated.
4409 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4410 * Placeholders created in Skin::makeLinkObj()
4411 * Returns an array of link CSS classes, indexed by PDBK.
4413 function replaceLinkHolders( &$text, $options = 0 ) {
4414 return $this->mLinkHolders
->replace( $text );
4418 * Replace <!--LINK--> link placeholders with plain text of links
4419 * (not HTML-formatted).
4420 * @param string $text
4423 function replaceLinkHoldersText( $text ) {
4424 return $this->mLinkHolders
->replaceText( $text );
4428 * Renders an image gallery from a text with one line per image.
4429 * text labels may be given by using |-style alternative text. E.g.
4430 * Image:one.jpg|The number "1"
4431 * Image:tree.jpg|A tree
4432 * given as text will return the HTML of a gallery with two images,
4433 * labeled 'The number "1"' and
4436 function renderImageGallery( $text, $params ) {
4437 $ig = new ImageGallery();
4438 $ig->setContextTitle( $this->mTitle
);
4439 $ig->setShowBytes( false );
4440 $ig->setShowFilename( false );
4441 $ig->setParser( $this );
4442 $ig->setHideBadImages();
4443 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4444 $ig->useSkin( $this->mOptions
->getSkin() );
4445 $ig->mRevisionId
= $this->mRevisionId
;
4447 if ( isset( $params['showfilename'] ) ) {
4448 $ig->setShowFilename( true );
4450 $ig->setShowFilename( false );
4452 if ( isset( $params['caption'] ) ) {
4453 $caption = $params['caption'];
4454 $caption = htmlspecialchars( $caption );
4455 $caption = $this->replaceInternalLinks( $caption );
4456 $ig->setCaptionHtml( $caption );
4458 if ( isset( $params['perrow'] ) ) {
4459 $ig->setPerRow( $params['perrow'] );
4461 if ( isset( $params['widths'] ) ) {
4462 $ig->setWidths( $params['widths'] );
4464 if ( isset( $params['heights'] ) ) {
4465 $ig->setHeights( $params['heights'] );
4468 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4470 $lines = StringUtils
::explode( "\n", $text );
4471 foreach ( $lines as $line ) {
4472 # match lines like these:
4473 # Image:someimage.jpg|This is some image
4475 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4477 if ( count( $matches ) == 0 ) {
4481 if ( strpos( $matches[0], '%' ) !== false ) {
4482 $matches[1] = urldecode( $matches[1] );
4484 $tp = Title
::newFromText( $matches[1] );
4486 if ( is_null( $nt ) ) {
4487 # Bogus title. Ignore these so we don't bomb out later.
4490 if ( isset( $matches[3] ) ) {
4491 $label = $matches[3];
4496 $html = $this->recursiveTagParse( trim( $label ) );
4498 $ig->add( $nt, $html );
4500 # Only add real images (bug #5586)
4501 if ( $nt->getNamespace() == NS_FILE
) {
4502 $this->mOutput
->addImage( $nt->getDBkey() );
4505 return $ig->toHTML();
4508 function getImageParams( $handler ) {
4510 $handlerClass = get_class( $handler );
4514 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4515 # Initialise static lists
4516 static $internalParamNames = array(
4517 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4518 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4519 'bottom', 'text-bottom' ),
4520 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4521 'upright', 'border', 'link', 'alt' ),
4523 static $internalParamMap;
4524 if ( !$internalParamMap ) {
4525 $internalParamMap = array();
4526 foreach ( $internalParamNames as $type => $names ) {
4527 foreach ( $names as $name ) {
4528 $magicName = str_replace( '-', '_', "img_$name" );
4529 $internalParamMap[$magicName] = array( $type, $name );
4534 # Add handler params
4535 $paramMap = $internalParamMap;
4537 $handlerParamMap = $handler->getParamMap();
4538 foreach ( $handlerParamMap as $magic => $paramName ) {
4539 $paramMap[$magic] = array( 'handler', $paramName );
4542 $this->mImageParams
[$handlerClass] = $paramMap;
4543 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4545 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4549 * Parse image options text and use it to make an image
4550 * @param Title $title
4551 * @param string $options
4552 * @param LinkHolderArray $holders
4554 function makeImage( $title, $options, $holders = false ) {
4555 # Check if the options text is of the form "options|alt text"
4557 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4558 # * left no resizing, just left align. label is used for alt= only
4559 # * right same, but right aligned
4560 # * none same, but not aligned
4561 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4562 # * center center the image
4563 # * frame Keep original image size, no magnify-button.
4564 # * framed Same as "frame"
4565 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4566 # * upright reduce width for upright images, rounded to full __0 px
4567 # * border draw a 1px border around the image
4568 # * alt Text for HTML alt attribute (defaults to empty)
4569 # * link Set the target of the image link. Can be external, interwiki, or local
4570 # vertical-align values (no % or length right now):
4580 $parts = StringUtils
::explode( "|", $options );
4581 $sk = $this->mOptions
->getSkin();
4583 # Give extensions a chance to select the file revision for us
4584 $skip = $time = $descQuery = false;
4585 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4588 return $sk->link( $title );
4592 $imagename = $title->getDBkey();
4593 $file = wfFindFile( $title, array( 'time' => $time ) );
4595 $handler = $file ?
$file->getHandler() : false;
4597 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4599 # Process the input parameters
4601 $params = array( 'frame' => array(), 'handler' => array(),
4602 'horizAlign' => array(), 'vertAlign' => array() );
4603 foreach ( $parts as $part ) {
4604 $part = trim( $part );
4605 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4607 if ( isset( $paramMap[$magicName] ) ) {
4608 list( $type, $paramName ) = $paramMap[$magicName];
4610 # Special case; width and height come in one variable together
4611 if ( $type === 'handler' && $paramName === 'width' ) {
4613 # (bug 13500) In both cases (width/height and width only),
4614 # permit trailing "px" for backward compatibility.
4615 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4616 $width = intval( $m[1] );
4617 $height = intval( $m[2] );
4618 if ( $handler->validateParam( 'width', $width ) ) {
4619 $params[$type]['width'] = $width;
4622 if ( $handler->validateParam( 'height', $height ) ) {
4623 $params[$type]['height'] = $height;
4626 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4627 $width = intval( $value );
4628 if ( $handler->validateParam( 'width', $width ) ) {
4629 $params[$type]['width'] = $width;
4632 } # else no validation -- bug 13436
4634 if ( $type === 'handler' ) {
4635 # Validate handler parameter
4636 $validated = $handler->validateParam( $paramName, $value );
4638 # Validate internal parameters
4639 switch( $paramName ) {
4642 # @todo Fixme: possibly check validity here for
4643 # manualthumb? downstream behavior seems odd with
4644 # missing manual thumbs.
4646 $value = $this->stripAltText( $value, $holders );
4649 $chars = self
::EXT_LINK_URL_CLASS
;
4650 $prots = $this->mUrlProtocols
;
4651 if ( $value === '' ) {
4652 $paramName = 'no-link';
4655 } elseif ( preg_match( "/^$prots/", $value ) ) {
4656 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4657 $paramName = 'link-url';
4658 $this->mOutput
->addExternalLink( $value );
4662 $linkTitle = Title
::newFromText( $value );
4664 $paramName = 'link-title';
4665 $value = $linkTitle;
4666 $this->mOutput
->addLink( $linkTitle );
4672 # Most other things appear to be empty or numeric...
4673 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4678 $params[$type][$paramName] = $value;
4682 if ( !$validated ) {
4687 # Process alignment parameters
4688 if ( $params['horizAlign'] ) {
4689 $params['frame']['align'] = key( $params['horizAlign'] );
4691 if ( $params['vertAlign'] ) {
4692 $params['frame']['valign'] = key( $params['vertAlign'] );
4695 $params['frame']['caption'] = $caption;
4697 # Will the image be presented in a frame, with the caption below?
4698 $imageIsFramed = isset( $params['frame']['frame'] ) ||
4699 isset( $params['frame']['framed'] ) ||
4700 isset( $params['frame']['thumbnail'] ) ||
4701 isset( $params['frame']['manualthumb'] );
4703 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4704 # came to also set the caption, ordinary text after the image -- which
4705 # makes no sense, because that just repeats the text multiple times in
4706 # screen readers. It *also* came to set the title attribute.
4708 # Now that we have an alt attribute, we should not set the alt text to
4709 # equal the caption: that's worse than useless, it just repeats the
4710 # text. This is the framed/thumbnail case. If there's no caption, we
4711 # use the unnamed parameter for alt text as well, just for the time be-
4712 # ing, if the unnamed param is set and the alt param is not.
4714 # For the future, we need to figure out if we want to tweak this more,
4715 # e.g., introducing a title= parameter for the title; ignoring the un-
4716 # named parameter entirely for images without a caption; adding an ex-
4717 # plicit caption= parameter and preserving the old magic unnamed para-
4719 if ( $imageIsFramed ) { # Framed image
4720 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
4721 # No caption or alt text, add the filename as the alt text so
4722 # that screen readers at least get some description of the image
4723 $params['frame']['alt'] = $title->getText();
4725 # Do not set $params['frame']['title'] because tooltips don't make sense
4727 } else { # Inline image
4728 if ( !isset( $params['frame']['alt'] ) ) {
4729 # No alt text, use the "caption" for the alt text
4730 if ( $caption !== '') {
4731 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
4733 # No caption, fall back to using the filename for the
4735 $params['frame']['alt'] = $title->getText();
4738 # Use the "caption" for the tooltip text
4739 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4742 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4744 # Linker does the rest
4745 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4747 # Give the handler a chance to modify the parser object
4749 $handler->parserTransformHook( $this, $file );
4755 protected function stripAltText( $caption, $holders ) {
4756 # Strip bad stuff out of the title (tooltip). We can't just use
4757 # replaceLinkHoldersText() here, because if this function is called
4758 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4760 $tooltip = $holders->replaceText( $caption );
4762 $tooltip = $this->replaceLinkHoldersText( $caption );
4765 # make sure there are no placeholders in thumbnail attributes
4766 # that are later expanded to html- so expand them now and
4768 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
4769 $tooltip = Sanitizer
::stripAllTags( $tooltip );
4775 * Set a flag in the output object indicating that the content is dynamic and
4776 * shouldn't be cached.
4778 function disableCache() {
4779 wfDebug( "Parser output marked as uncacheable.\n" );
4780 $this->mOutput
->mCacheTime
= -1;
4784 * Callback from the Sanitizer for expanding items found in HTML attribute
4785 * values, so they can be safely tested and escaped.
4786 * @param string $text
4787 * @param PPFrame $frame
4791 function attributeStripCallback( &$text, $frame = false ) {
4792 $text = $this->replaceVariables( $text, $frame );
4793 $text = $this->mStripState
->unstripBoth( $text );
4802 function Title( $x = null ) { return wfSetVar( $this->mTitle
, $x ); }
4803 function Options( $x = null ) { return wfSetVar( $this->mOptions
, $x ); }
4804 function OutputType( $x = null ) { return wfSetVar( $this->mOutputType
, $x ); }
4810 function getTags() {
4811 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) );
4817 * Break wikitext input into sections, and either pull or replace
4818 * some particular section's text.
4820 * External callers should use the getSection and replaceSection methods.
4822 * @param string $text Page wikitext
4823 * @param string $section A section identifier string of the form:
4824 * <flag1> - <flag2> - ... - <section number>
4826 * Currently the only recognised flag is "T", which means the target section number
4827 * was derived during a template inclusion parse, in other words this is a template
4828 * section edit link. If no flags are given, it was an ordinary section edit link.
4829 * This flag is required to avoid a section numbering mismatch when a section is
4830 * enclosed by <includeonly> (bug 6563).
4832 * The section number 0 pulls the text before the first heading; other numbers will
4833 * pull the given section along with its lower-level subsections. If the section is
4834 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4836 * @param string $mode One of "get" or "replace"
4837 * @param string $newText Replacement text for section data.
4838 * @return string for "get", the extracted section text.
4839 * for "replace", the whole page with the section replaced.
4841 private function extractSections( $text, $section, $mode, $newText='' ) {
4843 $this->clearState();
4844 $this->setTitle( $wgTitle ); # not generally used but removes an ugly failure mode
4845 $this->mOptions
= new ParserOptions
;
4846 $this->setOutputType( self
::OT_PLAIN
);
4848 $frame = $this->getPreprocessor()->newFrame();
4850 # Process section extraction flags
4852 $sectionParts = explode( '-', $section );
4853 $sectionIndex = array_pop( $sectionParts );
4854 foreach ( $sectionParts as $part ) {
4855 if ( $part === 'T' ) {
4856 $flags |
= self
::PTD_FOR_INCLUSION
;
4859 # Preprocess the text
4860 $root = $this->preprocessToDom( $text, $flags );
4862 # <h> nodes indicate section breaks
4863 # They can only occur at the top level, so we can find them by iterating the root's children
4864 $node = $root->getFirstChild();
4866 # Find the target section
4867 if ( $sectionIndex == 0 ) {
4868 # Section zero doesn't nest, level=big
4869 $targetLevel = 1000;
4872 if ( $node->getName() === 'h' ) {
4873 $bits = $node->splitHeading();
4874 if ( $bits['i'] == $sectionIndex ) {
4875 $targetLevel = $bits['level'];
4879 if ( $mode === 'replace' ) {
4880 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4882 $node = $node->getNextSibling();
4888 if ( $mode === 'get' ) {
4895 # Find the end of the section, including nested sections
4897 if ( $node->getName() === 'h' ) {
4898 $bits = $node->splitHeading();
4899 $curLevel = $bits['level'];
4900 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4904 if ( $mode === 'get' ) {
4905 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4907 $node = $node->getNextSibling();
4910 # Write out the remainder (in replace mode only)
4911 if ( $mode === 'replace' ) {
4912 # Output the replacement text
4913 # Add two newlines on -- trailing whitespace in $newText is conventionally
4914 # stripped by the editor, so we need both newlines to restore the paragraph gap
4915 # Only add trailing whitespace if there is newText
4916 if ( $newText != "" ) {
4917 $outText .= $newText . "\n\n";
4921 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4922 $node = $node->getNextSibling();
4926 if ( is_string( $outText ) ) {
4927 # Re-insert stripped tags
4928 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4935 * This function returns the text of a section, specified by a number ($section).
4936 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4937 * the first section before any such heading (section 0).
4939 * If a section contains subsections, these are also returned.
4941 * @param string $text text to look in
4942 * @param string $section section identifier
4943 * @param string $deftext default to return if section is not found
4944 * @return string text of the requested section
4946 public function getSection( $text, $section, $deftext='' ) {
4947 return $this->extractSections( $text, $section, "get", $deftext );
4950 public function replaceSection( $oldtext, $section, $text ) {
4951 return $this->extractSections( $oldtext, $section, "replace", $text );
4955 * Get the timestamp associated with the current revision, adjusted for
4956 * the default server-local timestamp
4958 function getRevisionTimestamp() {
4959 if ( is_null( $this->mRevisionTimestamp
) ) {
4960 wfProfileIn( __METHOD__
);
4962 $dbr = wfGetDB( DB_SLAVE
);
4963 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4964 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4966 # Normalize timestamp to internal MW format for timezone processing.
4967 # This has the added side-effect of replacing a null value with
4968 # the current time, which gives us more sensible behavior for
4970 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4972 # The cryptic '' timezone parameter tells to use the site-default
4973 # timezone offset instead of the user settings.
4975 # Since this value will be saved into the parser cache, served
4976 # to other users, and potentially even used inside links and such,
4977 # it needs to be consistent for all visitors.
4978 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4980 wfProfileOut( __METHOD__
);
4982 return $this->mRevisionTimestamp
;
4986 * Get the name of the user that edited the last revision
4988 function getRevisionUser() {
4989 # if this template is subst: the revision id will be blank,
4990 # so just use the current user's name
4991 if ( $this->mRevisionId
) {
4992 $revision = Revision
::newFromId( $this->mRevisionId
);
4993 $revuser = $revision->getUserText();
4996 $revuser = $wgUser->getName();
5002 * Mutator for $mDefaultSort
5004 * @param $sort New value
5006 public function setDefaultSort( $sort ) {
5007 $this->mDefaultSort
= $sort;
5011 * Accessor for $mDefaultSort
5012 * Will use the title/prefixed title if none is set
5016 public function getDefaultSort() {
5017 global $wgCategoryPrefixedDefaultSortkey;
5018 if ( $this->mDefaultSort
!== false ) {
5019 return $this->mDefaultSort
;
5020 } elseif ( $this->mTitle
->getNamespace() == NS_CATEGORY ||
5021 !$wgCategoryPrefixedDefaultSortkey )
5023 return $this->mTitle
->getText();
5025 return $this->mTitle
->getPrefixedText();
5030 * Accessor for $mDefaultSort
5031 * Unlike getDefaultSort(), will return false if none is set
5033 * @return string or false
5035 public function getCustomDefaultSort() {
5036 return $this->mDefaultSort
;
5040 * Try to guess the section anchor name based on a wikitext fragment
5041 * presumably extracted from a heading, for example "Header" from
5044 public function guessSectionNameFromWikiText( $text ) {
5045 # Strip out wikitext links(they break the anchor)
5046 $text = $this->stripSectionName( $text );
5047 $headline = Sanitizer
::decodeCharReferences( $text );
5049 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
5050 $headline = trim( $headline );
5051 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
5052 $replacearray = array(
5057 array_keys( $replacearray ),
5058 array_values( $replacearray ),
5063 * Strips a text string of wikitext for use in a section anchor
5065 * Accepts a text string and then removes all wikitext from the
5066 * string and leaves only the resultant text (i.e. the result of
5067 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5068 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5069 * to create valid section anchors by mimicing the output of the
5070 * parser when headings are parsed.
5072 * @param $text string Text string to be stripped of wikitext
5073 * for use in a Section anchor
5074 * @return Filtered text string
5076 public function stripSectionName( $text ) {
5077 # Strip internal link markup
5078 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5079 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5081 # Strip external link markup (FIXME: Not Tolerant to blank link text
5082 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5083 # on how many empty links there are on the page - need to figure that out.
5084 $text = preg_replace( '/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5086 # Parse wikitext quotes (italics & bold)
5087 $text = $this->doQuotes( $text );
5090 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5094 function srvus( $text ) {
5095 return $this->testSrvus( $text, $this->mOutputType
);
5099 * strip/replaceVariables/unstrip for preprocessor regression testing
5101 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
5102 $this->clearState();
5103 if ( !$title instanceof Title
) {
5104 $title = Title
::newFromText( $title );
5106 $this->mTitle
= $title;
5107 $this->mOptions
= $options;
5108 $this->setOutputType( $outputType );
5109 $text = $this->replaceVariables( $text );
5110 $text = $this->mStripState
->unstripBoth( $text );
5111 $text = Sanitizer
::removeHTMLtags( $text );
5115 function testPst( $text, $title, $options ) {
5117 if ( !$title instanceof Title
) {
5118 $title = Title
::newFromText( $title );
5120 return $this->preSaveTransform( $text, $title, $wgUser, $options );
5123 function testPreprocess( $text, $title, $options ) {
5124 if ( !$title instanceof Title
) {
5125 $title = Title
::newFromText( $title );
5127 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5130 function markerSkipCallback( $s, $callback ) {
5133 while ( $i < strlen( $s ) ) {
5134 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5135 if ( $markerStart === false ) {
5136 $out .= call_user_func( $callback, substr( $s, $i ) );
5139 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5140 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5141 if ( $markerEnd === false ) {
5142 $out .= substr( $s, $markerStart );
5145 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5146 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5154 function serialiseHalfParsedText( $text ) {
5156 $data['text'] = $text;
5158 # First, find all strip markers, and store their
5160 $stripState = new StripState
;
5162 while ( ( $start_pos = strpos( $text, $this->mUniqPrefix
, $pos ) )
5163 && ( $end_pos = strpos( $text, self
::MARKER_SUFFIX
, $pos ) ) )
5165 $end_pos +
= strlen( self
::MARKER_SUFFIX
);
5166 $marker = substr( $text, $start_pos, $end_pos-$start_pos );
5168 if ( !empty( $this->mStripState
->general
->data
[$marker] ) ) {
5169 $replaceArray = $stripState->general
;
5170 $stripText = $this->mStripState
->general
->data
[$marker];
5171 } elseif ( !empty( $this->mStripState
->nowiki
->data
[$marker] ) ) {
5172 $replaceArray = $stripState->nowiki
;
5173 $stripText = $this->mStripState
->nowiki
->data
[$marker];
5175 throw new MWException( "Hanging strip marker: '$marker'." );
5178 $replaceArray->setPair( $marker, $stripText );
5181 $data['stripstate'] = $stripState;
5183 # Now, find all of our links, and store THEIR
5184 # data in an array! :)
5185 $links = array( 'internal' => array(), 'interwiki' => array() );
5189 while ( ( $start_pos = strpos( $text, '<!--LINK ', $pos ) ) ) {
5190 list( $ns, $trail ) = explode( ':', substr( $text, $start_pos +
strlen( '<!--LINK ' ) ), 2 );
5193 if ( empty( $links['internal'][$ns] ) ) {
5194 $links['internal'][$ns] = array();
5197 $key = trim( substr( $trail, 0, strpos( $trail, '-->' ) ) );
5198 $links['internal'][$ns][] = $this->mLinkHolders
->internals
[$ns][$key];
5199 $pos = $start_pos +
strlen( "<!--LINK $ns:$key-->" );
5205 while ( ( $start_pos = strpos( $text, '<!--IWLINK ', $pos ) ) ) {
5206 $data = substr( $text, $start_pos );
5207 $key = trim( substr( $data, 0, strpos( $data, '-->' ) ) );
5208 $links['interwiki'][] = $this->mLinkHolders
->interwiki
[$key];
5209 $pos = $start_pos +
strlen( "<!--IWLINK $key-->" );
5212 $data['linkholder'] = $links;
5219 * @param $data Array
5220 * @param $intPrefix String unique identifying prefix
5223 function unserialiseHalfParsedText( $data, $intPrefix = null ) {
5224 if ( !$intPrefix ) {
5225 $intPrefix = $this->getRandomString();
5228 # First, extract the strip state.
5229 $stripState = $data['stripstate'];
5230 $this->mStripState
->general
->merge( $stripState->general
);
5231 $this->mStripState
->nowiki
->merge( $stripState->nowiki
);
5233 # Now, extract the text, and renumber links
5234 $text = $data['text'];
5235 $links = $data['linkholder'];
5238 foreach ( $links['internal'] as $ns => $nsLinks ) {
5239 foreach ( $nsLinks as $key => $entry ) {
5240 $newKey = $intPrefix . '-' . $key;
5241 $this->mLinkHolders
->internals
[$ns][$newKey] = $entry;
5243 $text = str_replace( "<!--LINK $ns:$key-->", "<!--LINK $ns:$newKey-->", $text );
5248 foreach ( $links['interwiki'] as $key => $entry ) {
5249 $newKey = "$intPrefix-$key";
5250 $this->mLinkHolders
->interwikis
[$newKey] = $entry;
5252 $text = str_replace( "<!--IWLINK $key-->", "<!--IWLINK $newKey-->", $text );
5255 # Should be good to go.
5261 * @todo document, briefly.
5265 var $general, $nowiki;
5267 function __construct() {
5268 $this->general
= new ReplacementArray
;
5269 $this->nowiki
= new ReplacementArray
;
5272 function unstripGeneral( $text ) {
5273 wfProfileIn( __METHOD__
);
5276 $text = $this->general
->replace( $text );
5277 } while ( $text !== $oldText );
5278 wfProfileOut( __METHOD__
);
5282 function unstripNoWiki( $text ) {
5283 wfProfileIn( __METHOD__
);
5286 $text = $this->nowiki
->replace( $text );
5287 } while ( $text !== $oldText );
5288 wfProfileOut( __METHOD__
);
5292 function unstripBoth( $text ) {
5293 wfProfileIn( __METHOD__
);
5296 $text = $this->general
->replace( $text );
5297 $text = $this->nowiki
->replace( $text );
5298 } while ( $text !== $oldText );
5299 wfProfileOut( __METHOD__
);
5305 * @todo document, briefly.
5308 class OnlyIncludeReplacer
{
5311 function replace( $matches ) {
5312 if ( substr( $matches[1], -1 ) === "\n" ) {
5313 $this->output
.= substr( $matches[1], 0, -1 );
5315 $this->output
.= $matches[1];