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]+) *([^\]\\x0a\\x0d]*?)\]/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, $wgUser, $wgRequest, $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) Content convert 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 ( !( $wgDisableContentConversion
379 ||
$wgDisableTitleConversion
380 ||
$wgRequest->getText( 'redirect', 'yes' ) == 'no'
381 ||
$wgRequest->getText( 'linkconvert', 'yes' ) == 'no'
382 ||
isset( $this->mDoubleUnderscores
['nocontentconvert'] )
383 ||
isset( $this->mDoubleUnderscores
['notitleconvert'] )
384 ||
$wgUser->getOption( 'noconvertlink' ) == 1 ) ) {
385 $convruletitle = $wgContLang->getConvRuleTitle();
386 if ( $convruletitle ) {
387 $this->mOutput
->setTitleText( $convruletitle );
390 $this->mOutput
->setTitleText( $wgContLang->convert( $title->getPrefixedText() ) );
394 $text = $this->mStripState
->unstripNoWiki( $text );
396 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
398 //!JF Move to its own function
400 $uniq_prefix = $this->mUniqPrefix
;
402 $elements = array_keys( $this->mTransparentTagHooks
);
403 $text = self
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
405 foreach ( $matches as $marker => $data ) {
406 list( $element, $content, $params, $tag ) = $data;
407 $tagName = strtolower( $element );
408 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
409 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
413 $this->mStripState
->general
->setPair( $marker, $output );
415 $text = $this->mStripState
->unstripGeneral( $text );
417 $text = Sanitizer
::normalizeCharReferences( $text );
419 if ( ( $wgUseTidy && $this->mOptions
->mTidy
) ||
$wgAlwaysUseTidy ) {
420 $text = MWTidy
::tidy( $text );
422 # attempt to sanitize at least some nesting problems
423 # (bug #2702 and quite a few others)
425 # ''Something [http://www.cool.com cool''] -->
426 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
427 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
428 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
429 # fix up an anchor inside another anchor, only
430 # at least for a single single nested link (bug 3695)
431 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
432 '\\1\\2</a>\\3</a>\\1\\4</a>',
433 # fix div inside inline elements- doBlockLevels won't wrap a line which
434 # contains a div, so fix it up here; replace
435 # div with escaped text
436 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
437 '\\1\\3<div\\5>\\6</div>\\8\\9',
438 # remove empty italic or bold tag pairs, some
439 # introduced by rules above
440 '/<([bi])><\/\\1>/' => '',
443 $text = preg_replace(
444 array_keys( $tidyregs ),
445 array_values( $tidyregs ),
448 global $wgExpensiveParserFunctionLimit;
449 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
450 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
453 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
455 # Information on include size limits, for the benefit of users who try to skirt them
456 if ( $this->mOptions
->getEnableLimitReport() ) {
457 $max = $this->mOptions
->getMaxIncludeSize();
458 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
460 "NewPP limit report\n" .
461 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
462 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
463 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
465 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
466 $text .= "\n<!-- \n$limitReport-->\n";
468 $this->mOutput
->setText( $text );
470 $this->mRevisionId
= $oldRevisionId;
471 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
472 wfProfileOut( $fname );
473 wfProfileOut( __METHOD__
);
475 return $this->mOutput
;
479 * Recursive parser entry point that can be called from an extension tag
482 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
484 * @param $text String: text extension wants to have parsed
485 * @param PPFrame $frame: The frame to use for expanding any template variables
487 function recursiveTagParse( $text, $frame=false ) {
488 wfProfileIn( __METHOD__
);
489 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
490 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
491 $text = $this->internalParse( $text, false, $frame );
492 wfProfileOut( __METHOD__
);
497 * Expand templates and variables in the text, producing valid, static wikitext.
498 * Also removes comments.
500 function preprocess( $text, $title, $options, $revid = null ) {
501 wfProfileIn( __METHOD__
);
503 $this->setOutputType( self
::OT_PREPROCESS
);
504 $this->mOptions
= $options;
505 $this->setTitle( $title );
506 if ( $revid !== null ) {
507 $this->mRevisionId
= $revid;
509 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
510 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
511 $text = $this->replaceVariables( $text );
512 $text = $this->mStripState
->unstripBoth( $text );
513 wfProfileOut( __METHOD__
);
518 * Process the wikitext for the ?preload= feature. (bug 5210)
520 * <noinclude>, <includeonly> etc. are parsed as for template transclusion,
521 * comments, templates, arguments, tags hooks and parser functions are untouched.
523 public function getPreloadText( $text, $title, $options ) {
524 # Parser (re)initialisation
526 $this->setOutputType( self
::OT_PLAIN
);
527 $this->mOptions
= $options;
528 $this->setTitle( $title );
530 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
531 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
532 return $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
536 * Get a random string
541 function getRandomString() {
542 return dechex( mt_rand( 0, 0x7fffffff ) ) . dechex( mt_rand( 0, 0x7fffffff ) );
545 function &getTitle() { return $this->mTitle
; }
546 function getOptions() { return $this->mOptions
; }
547 function getRevisionId() { return $this->mRevisionId
; }
548 function getOutput() { return $this->mOutput
; }
549 function nextLinkID() { return $this->mLinkID++
; }
551 function getFunctionLang() {
552 global $wgLang, $wgContLang;
554 $target = $this->mOptions
->getTargetLanguage();
555 if ( $target !== null ) {
558 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
563 * Get a preprocessor object
565 function getPreprocessor() {
566 if ( !isset( $this->mPreprocessor
) ) {
567 $class = $this->mPreprocessorClass
;
568 $this->mPreprocessor
= new $class( $this );
570 return $this->mPreprocessor
;
574 * Replaces all occurrences of HTML-style comments and the given tags
575 * in the text with a random marker and returns the next text. The output
576 * parameter $matches will be an associative array filled with data in
578 * 'UNIQ-xxxxx' => array(
581 * array( 'param' => 'x' ),
582 * '<element param="x">tag content</element>' ) )
584 * @param $elements list of element names. Comments are always extracted.
585 * @param $text Source text string.
586 * @param $uniq_prefix
591 function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
596 $taglist = implode( '|', $elements );
597 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
599 while ( $text != '' ) {
600 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
602 if ( count( $p ) < 5 ) {
605 if ( count( $p ) > 5 ) {
619 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
620 $stripped .= $marker;
622 if ( $close === '/>' ) {
623 # Empty element tag, <tag />
628 if ( $element === '!--' ) {
631 $end = "/(<\\/$element\\s*>)/i";
633 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
635 if ( count( $q ) < 3 ) {
636 # No end tag -- let it run out to the end of the text.
645 $matches[$marker] = array( $element,
647 Sanitizer
::decodeTagAttributes( $attributes ),
648 "<$element$attributes$close$content$tail" );
654 * Get a list of strippable XML-like elements
656 function getStripList() {
657 return $this->mStripList
;
661 * @deprecated use replaceVariables
663 function strip( $text, $state, $stripcomments = false , $dontstrip = array() ) {
668 * Restores pre, math, and other extensions removed by strip()
670 * always call unstripNoWiki() after this one
672 * @deprecated use $this->mStripState->unstrip()
674 function unstrip( $text, $state ) {
675 return $state->unstripGeneral( $text );
679 * Always call this after unstrip() to preserve the order
682 * @deprecated use $this->mStripState->unstrip()
684 function unstripNoWiki( $text, $state ) {
685 return $state->unstripNoWiki( $text );
689 * @deprecated use $this->mStripState->unstripBoth()
691 function unstripForHTML( $text ) {
692 return $this->mStripState
->unstripBoth( $text );
696 * Add an item to the strip state
697 * Returns the unique tag which must be inserted into the stripped text
698 * The tag will be replaced with the original text in unstrip()
702 function insertStripItem( $text ) {
703 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
704 $this->mMarkerIndex++
;
705 $this->mStripState
->general
->setPair( $rnd, $text );
710 * Interface with html tidy
711 * @deprecated Use MWTidy::tidy()
713 public static function tidy( $text ) {
714 wfDeprecated( __METHOD__
);
715 return MWTidy
::tidy( $text );
719 * parse the wiki syntax used to render tables
723 function doTableStuff( $text ) {
724 wfProfileIn( __METHOD__
);
726 $lines = StringUtils
::explode( "\n", $text );
728 $td_history = array(); # Is currently a td tag open?
729 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
730 $tr_history = array(); # Is currently a tr tag open?
731 $tr_attributes = array(); # history of tr attributes
732 $has_opened_tr = array(); # Did this table open a <tr> element?
733 $indent_level = 0; # indent level of the table
735 foreach ( $lines as $outLine ) {
736 $line = trim( $outLine );
738 if ( $line == '' ) { # empty line, go to next line
739 $out .= $outLine."\n";
742 $first_character = $line[0];
745 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
746 # First check if we are starting a new table
747 $indent_level = strlen( $matches[1] );
749 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
750 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
752 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
753 array_push( $td_history , false );
754 array_push( $last_tag_history , '' );
755 array_push( $tr_history , false );
756 array_push( $tr_attributes , '' );
757 array_push( $has_opened_tr , false );
758 } elseif ( count( $td_history ) == 0 ) {
759 # Don't do any of the following
760 $out .= $outLine."\n";
762 } elseif ( substr( $line , 0 , 2 ) === '|}' ) {
763 # We are ending a table
764 $line = '</table>' . substr( $line , 2 );
765 $last_tag = array_pop( $last_tag_history );
767 if ( !array_pop( $has_opened_tr ) ) {
768 $line = "<tr><td></td></tr>{$line}";
771 if ( array_pop( $tr_history ) ) {
772 $line = "</tr>{$line}";
775 if ( array_pop( $td_history ) ) {
776 $line = "</{$last_tag}>{$line}";
778 array_pop( $tr_attributes );
779 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
780 } elseif ( substr( $line , 0 , 2 ) === '|-' ) {
781 # Now we have a table row
782 $line = preg_replace( '#^\|-+#', '', $line );
784 # Whats after the tag is now only attributes
785 $attributes = $this->mStripState
->unstripBoth( $line );
786 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
787 array_pop( $tr_attributes );
788 array_push( $tr_attributes, $attributes );
791 $last_tag = array_pop( $last_tag_history );
792 array_pop( $has_opened_tr );
793 array_push( $has_opened_tr , true );
795 if ( array_pop( $tr_history ) ) {
799 if ( array_pop( $td_history ) ) {
800 $line = "</{$last_tag}>{$line}";
804 array_push( $tr_history , false );
805 array_push( $td_history , false );
806 array_push( $last_tag_history , '' );
807 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line , 0 , 2 ) === '|+' ) {
808 # This might be cell elements, td, th or captions
809 if ( substr( $line , 0 , 2 ) === '|+' ) {
810 $first_character = '+';
811 $line = substr( $line , 1 );
814 $line = substr( $line , 1 );
816 if ( $first_character === '!' ) {
817 $line = str_replace( '!!' , '||' , $line );
820 # Split up multiple cells on the same line.
821 # FIXME : This can result in improper nesting of tags processed
822 # by earlier parser steps, but should avoid splitting up eg
823 # attribute values containing literal "||".
824 $cells = StringUtils
::explodeMarkup( '||' , $line );
828 # Loop through each table cell
829 foreach ( $cells as $cell ) {
831 if ( $first_character !== '+' ) {
832 $tr_after = array_pop( $tr_attributes );
833 if ( !array_pop( $tr_history ) ) {
834 $previous = "<tr{$tr_after}>\n";
836 array_push( $tr_history , true );
837 array_push( $tr_attributes , '' );
838 array_pop( $has_opened_tr );
839 array_push( $has_opened_tr , true );
842 $last_tag = array_pop( $last_tag_history );
844 if ( array_pop( $td_history ) ) {
845 $previous = "</{$last_tag}>{$previous}";
848 if ( $first_character === '|' ) {
850 } elseif ( $first_character === '!' ) {
852 } elseif ( $first_character === '+' ) {
853 $last_tag = 'caption';
858 array_push( $last_tag_history , $last_tag );
860 # A cell could contain both parameters and data
861 $cell_data = explode( '|' , $cell , 2 );
863 # Bug 553: Note that a '|' inside an invalid link should not
864 # be mistaken as delimiting cell parameters
865 if ( strpos( $cell_data[0], '[[' ) !== false ) {
866 $cell = "{$previous}<{$last_tag}>{$cell}";
867 } elseif ( count( $cell_data ) == 1 ) {
868 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
870 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
871 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
872 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
876 array_push( $td_history , true );
879 $out .= $outLine . "\n";
882 # Closing open td, tr && table
883 while ( count( $td_history ) > 0 ) {
884 if ( array_pop( $td_history ) ) {
887 if ( array_pop( $tr_history ) ) {
890 if ( !array_pop( $has_opened_tr ) ) {
891 $out .= "<tr><td></td></tr>\n" ;
894 $out .= "</table>\n";
897 # Remove trailing line-ending (b/c)
898 if ( substr( $out, -1 ) === "\n" ) {
899 $out = substr( $out, 0, -1 );
902 # special case: don't return empty table
903 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
907 wfProfileOut( __METHOD__
);
913 * Helper function for parse() that transforms wiki markup into
914 * HTML. Only called for $mOutputType == self::OT_HTML.
918 function internalParse( $text, $isMain = true, $frame=false ) {
919 wfProfileIn( __METHOD__
);
923 # Hook to suspend the parser in this state
924 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
925 wfProfileOut( __METHOD__
);
929 # if $frame is provided, then use $frame for replacing any variables
931 # use frame depth to infer how include/noinclude tags should be handled
932 # depth=0 means this is the top-level document; otherwise it's an included document
933 if ( !$frame->depth
) {
936 $flag = Parser
::PTD_FOR_INCLUSION
;
937 $dom = $this->preprocessToDom( $text, $flag );
938 $text = $frame->expand( $dom );
941 # if $frame is not provided, then use old-style replaceVariables
942 $text = $this->replaceVariables( $text );
945 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
946 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
948 # Tables need to come after variable replacement for things to work
949 # properly; putting them before other transformations should keep
950 # exciting things like link expansions from showing up in surprising
952 $text = $this->doTableStuff( $text );
954 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
956 $text = $this->doDoubleUnderscore( $text );
958 $text = $this->doHeadings( $text );
959 if ( $this->mOptions
->getUseDynamicDates() ) {
960 $df = DateFormatter
::getInstance();
961 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
963 $text = $this->doAllQuotes( $text );
964 $text = $this->replaceInternalLinks( $text );
965 $text = $this->replaceExternalLinks( $text );
967 # replaceInternalLinks may sometimes leave behind
968 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
969 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
971 $text = $this->doMagicLinks( $text );
972 $text = $this->formatHeadings( $text, $origText, $isMain );
974 wfProfileOut( __METHOD__
);
979 * Replace special strings like "ISBN xxx" and "RFC xxx" with
980 * magic external links.
985 function doMagicLinks( $text ) {
986 wfProfileIn( __METHOD__
);
987 $prots = $this->mUrlProtocols
;
988 $urlChar = self
::EXT_LINK_URL_CLASS
;
989 $text = preg_replace_callback(
991 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
992 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
993 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
994 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
995 ISBN\s+(\b # m[5]: ISBN, capture number
996 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
997 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
998 [0-9Xx] # check digit
1000 )!x', array( &$this, 'magicLinkCallback' ), $text );
1001 wfProfileOut( __METHOD__
);
1005 function magicLinkCallback( $m ) {
1006 if ( isset( $m[1] ) && $m[1] !== '' ) {
1009 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1012 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1013 # Free external link
1014 return $this->makeFreeExternalLink( $m[0] );
1015 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1018 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1021 $CssClass = 'mw-magiclink-rfc';
1023 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1025 $urlmsg = 'pubmedurl';
1026 $CssClass = 'mw-magiclink-pmid';
1029 throw new MWException( __METHOD__
.': unrecognised match type "' .
1030 substr( $m[0], 0, 20 ) . '"' );
1032 $url = wfMsg( $urlmsg, $id);
1033 $sk = $this->mOptions
->getSkin();
1034 $la = $sk->getExternalLinkAttributes( "external $CssClass" );
1035 return "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1036 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1039 $num = strtr( $isbn, array(
1044 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1046 $titleObj->escapeLocalUrl() .
1047 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1054 * Make a free external link, given a user-supplied URL
1058 function makeFreeExternalLink( $url ) {
1060 wfProfileIn( __METHOD__
);
1062 $sk = $this->mOptions
->getSkin();
1065 # The characters '<' and '>' (which were escaped by
1066 # removeHTMLtags()) should not be included in
1067 # URLs, per RFC 2396.
1069 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1070 $trail = substr( $url, $m2[0][1] ) . $trail;
1071 $url = substr( $url, 0, $m2[0][1] );
1074 # Move trailing punctuation to $trail
1076 # If there is no left bracket, then consider right brackets fair game too
1077 if ( strpos( $url, '(' ) === false ) {
1081 $numSepChars = strspn( strrev( $url ), $sep );
1082 if ( $numSepChars ) {
1083 $trail = substr( $url, -$numSepChars ) . $trail;
1084 $url = substr( $url, 0, -$numSepChars );
1087 $url = Sanitizer
::cleanUrl( $url );
1089 # Is this an external image?
1090 $text = $this->maybeMakeExternalImage( $url );
1091 if ( $text === false ) {
1092 # Not an image, make a link
1093 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1094 $this->getExternalLinkAttribs( $url ) );
1095 # Register it in the output object...
1096 # Replace unnecessary URL escape codes with their equivalent characters
1097 $pasteurized = self
::replaceUnusualEscapes( $url );
1098 $this->mOutput
->addExternalLink( $pasteurized );
1100 wfProfileOut( __METHOD__
);
1101 return $text . $trail;
1106 * Parse headers and return html
1110 function doHeadings( $text ) {
1111 wfProfileIn( __METHOD__
);
1112 for ( $i = 6; $i >= 1; --$i ) {
1113 $h = str_repeat( '=', $i );
1114 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1115 "<h$i>\\1</h$i>", $text );
1117 wfProfileOut( __METHOD__
);
1122 * Replace single quotes with HTML markup
1124 * @return string the altered text
1126 function doAllQuotes( $text ) {
1127 wfProfileIn( __METHOD__
);
1129 $lines = StringUtils
::explode( "\n", $text );
1130 foreach ( $lines as $line ) {
1131 $outtext .= $this->doQuotes( $line ) . "\n";
1133 $outtext = substr( $outtext, 0,-1 );
1134 wfProfileOut( __METHOD__
);
1139 * Helper function for doAllQuotes()
1141 public function doQuotes( $text ) {
1142 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1143 if ( count( $arr ) == 1 ) {
1146 # First, do some preliminary work. This may shift some apostrophes from
1147 # being mark-up to being text. It also counts the number of occurrences
1148 # of bold and italics mark-ups.
1152 foreach ( $arr as $r ) {
1153 if ( ( $i %
2 ) == 1 ) {
1154 # If there are ever four apostrophes, assume the first is supposed to
1155 # be text, and the remaining three constitute mark-up for bold text.
1156 if ( strlen( $arr[$i] ) == 4 ) {
1159 } elseif ( strlen( $arr[$i] ) > 5 ) {
1160 # If there are more than 5 apostrophes in a row, assume they're all
1161 # text except for the last 5.
1162 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1165 # Count the number of occurrences of bold and italics mark-ups.
1166 # We are not counting sequences of five apostrophes.
1167 if ( strlen( $arr[$i] ) == 2 ) {
1169 } elseif ( strlen( $arr[$i] ) == 3 ) {
1171 } elseif ( strlen( $arr[$i] ) == 5 ) {
1179 # If there is an odd number of both bold and italics, it is likely
1180 # that one of the bold ones was meant to be an apostrophe followed
1181 # by italics. Which one we cannot know for certain, but it is more
1182 # likely to be one that has a single-letter word before it.
1183 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1185 $firstsingleletterword = -1;
1186 $firstmultiletterword = -1;
1188 foreach ( $arr as $r ) {
1189 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1190 $x1 = substr( $arr[$i-1], -1 );
1191 $x2 = substr( $arr[$i-1], -2, 1 );
1192 if ( $x1 === ' ' ) {
1193 if ( $firstspace == -1 ) {
1196 } elseif ( $x2 === ' ') {
1197 if ( $firstsingleletterword == -1 ) {
1198 $firstsingleletterword = $i;
1201 if ( $firstmultiletterword == -1 ) {
1202 $firstmultiletterword = $i;
1209 # If there is a single-letter word, use it!
1210 if ( $firstsingleletterword > -1 ) {
1211 $arr[$firstsingleletterword] = "''";
1212 $arr[$firstsingleletterword-1] .= "'";
1213 } elseif ( $firstmultiletterword > -1 ) {
1214 # If not, but there's a multi-letter word, use that one.
1215 $arr[$firstmultiletterword] = "''";
1216 $arr[$firstmultiletterword-1] .= "'";
1217 } elseif ( $firstspace > -1 ) {
1218 # ... otherwise use the first one that has neither.
1219 # (notice that it is possible for all three to be -1 if, for example,
1220 # there is only one pentuple-apostrophe in the line)
1221 $arr[$firstspace] = "''";
1222 $arr[$firstspace-1] .= "'";
1226 # Now let's actually convert our apostrophic mush to HTML!
1231 foreach ( $arr as $r ) {
1232 if ( ( $i %
2 ) == 0 ) {
1233 if ( $state === 'both' ) {
1239 if ( strlen( $r ) == 2 ) {
1240 if ( $state === 'i' ) {
1241 $output .= '</i>'; $state = '';
1242 } elseif ( $state === 'bi' ) {
1243 $output .= '</i>'; $state = 'b';
1244 } elseif ( $state === 'ib' ) {
1245 $output .= '</b></i><b>'; $state = 'b';
1246 } elseif ( $state === 'both' ) {
1247 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1248 } else { # $state can be 'b' or ''
1249 $output .= '<i>'; $state .= 'i';
1251 } elseif ( strlen( $r ) == 3 ) {
1252 if ( $state === 'b' ) {
1253 $output .= '</b>'; $state = '';
1254 } elseif ( $state === 'bi' ) {
1255 $output .= '</i></b><i>'; $state = 'i';
1256 } elseif ( $state === 'ib' ) {
1257 $output .= '</b>'; $state = 'i';
1258 } elseif ( $state === 'both' ) {
1259 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1260 } else { # $state can be 'i' or ''
1261 $output .= '<b>'; $state .= 'b';
1263 } elseif ( strlen( $r ) == 5 ) {
1264 if ( $state === 'b' ) {
1265 $output .= '</b><i>'; $state = 'i';
1266 } elseif ( $state === 'i' ) {
1267 $output .= '</i><b>'; $state = 'b';
1268 } elseif ( $state === 'bi' ) {
1269 $output .= '</i></b>'; $state = '';
1270 } elseif ( $state === 'ib' ) {
1271 $output .= '</b></i>'; $state = '';
1272 } elseif ( $state === 'both' ) {
1273 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1274 } else { # ($state == '')
1275 $buffer = ''; $state = 'both';
1281 # Now close all remaining tags. Notice that the order is important.
1282 if ( $state === 'b' ||
$state === 'ib' ) {
1285 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1288 if ( $state === 'bi' ) {
1291 # There might be lonely ''''', so make sure we have a buffer
1292 if ( $state === 'both' && $buffer ) {
1293 $output .= '<b><i>'.$buffer.'</i></b>';
1300 * Replace external links (REL)
1302 * Note: this is all very hackish and the order of execution matters a lot.
1303 * Make sure to run maintenance/parserTests.php if you change this code.
1307 function replaceExternalLinks( $text ) {
1309 wfProfileIn( __METHOD__
);
1311 $sk = $this->mOptions
->getSkin();
1313 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1314 $s = array_shift( $bits );
1317 while ( $i<count( $bits ) ) {
1319 $protocol = $bits[$i++
];
1320 $text = $bits[$i++
];
1321 $trail = $bits[$i++
];
1323 # The characters '<' and '>' (which were escaped by
1324 # removeHTMLtags()) should not be included in
1325 # URLs, per RFC 2396.
1327 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1328 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1329 $url = substr( $url, 0, $m2[0][1] );
1332 # If the link text is an image URL, replace it with an <img> tag
1333 # This happened by accident in the original parser, but some people used it extensively
1334 $img = $this->maybeMakeExternalImage( $text );
1335 if ( $img !== false ) {
1341 # Set linktype for CSS - if URL==text, link is essentially free
1342 $linktype = ( $text === $url ) ?
'free' : 'text';
1344 # No link text, e.g. [http://domain.tld/some.link]
1345 if ( $text == '' ) {
1346 # Autonumber if allowed. See bug #5918
1347 if ( strpos( wfUrlProtocols(), substr( $protocol, 0, strpos( $protocol, ':' ) ) ) !== false ) {
1348 $langObj = $this->getFunctionLang();
1349 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1350 $linktype = 'autonumber';
1352 # Otherwise just use the URL
1353 $text = htmlspecialchars( $url );
1357 # Have link text, e.g. [http://domain.tld/some.link text]s
1359 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1362 $text = $wgContLang->markNoConversion( $text );
1364 $url = Sanitizer
::cleanUrl( $url );
1366 # Use the encoded URL
1367 # This means that users can paste URLs directly into the text
1368 # Funny characters like ö aren't valid in URLs anyway
1369 # This was changed in August 2004
1370 $s .= $sk->makeExternalLink( $url, $text, false, $linktype,
1371 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1373 # Register link in the output object.
1374 # Replace unnecessary URL escape codes with the referenced character
1375 # This prevents spammers from hiding links from the filters
1376 $pasteurized = self
::replaceUnusualEscapes( $url );
1377 $this->mOutput
->addExternalLink( $pasteurized );
1380 wfProfileOut( __METHOD__
);
1385 * Get an associative array of additional HTML attributes appropriate for a
1386 * particular external link. This currently may include rel => nofollow
1387 * (depending on configuration, namespace, and the URL's domain) and/or a
1388 * target attribute (depending on configuration).
1390 * @param string $url Optional URL, to extract the domain from for rel =>
1391 * nofollow if appropriate
1392 * @return array Associative array of HTML attributes
1394 function getExternalLinkAttribs( $url = false ) {
1396 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1397 $ns = $this->mTitle
->getNamespace();
1398 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) ) {
1399 $attribs['rel'] = 'nofollow';
1401 global $wgNoFollowDomainExceptions;
1402 if ( $wgNoFollowDomainExceptions ) {
1403 $bits = wfParseUrl( $url );
1404 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1405 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1406 if ( substr( $bits['host'], -strlen( $domain ) ) == $domain ) {
1407 unset( $attribs['rel'] );
1414 if ( $this->mOptions
->getExternalLinkTarget() ) {
1415 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1422 * Replace unusual URL escape codes with their equivalent characters
1426 * @todo This can merge genuinely required bits in the path or query string,
1427 * breaking legit URLs. A proper fix would treat the various parts of
1428 * the URL differently; as a workaround, just use the output for
1429 * statistical records, not for actual linking/output.
1431 static function replaceUnusualEscapes( $url ) {
1432 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1433 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1437 * Callback function used in replaceUnusualEscapes().
1438 * Replaces unusual URL escape codes with their equivalent character
1442 private static function replaceUnusualEscapesCallback( $matches ) {
1443 $char = urldecode( $matches[0] );
1444 $ord = ord( $char );
1445 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1446 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1447 # No, shouldn't be escaped
1450 # Yes, leave it escaped
1456 * make an image if it's allowed, either through the global
1457 * option, through the exception, or through the on-wiki whitelist
1460 function maybeMakeExternalImage( $url ) {
1461 $sk = $this->mOptions
->getSkin();
1462 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1463 $imagesexception = !empty( $imagesfrom );
1465 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1466 if ( $imagesexception && is_array( $imagesfrom ) ) {
1467 $imagematch = false;
1468 foreach ( $imagesfrom as $match ) {
1469 if ( strpos( $url, $match ) === 0 ) {
1474 } elseif ( $imagesexception ) {
1475 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1477 $imagematch = false;
1479 if ( $this->mOptions
->getAllowExternalImages()
1480 ||
( $imagesexception && $imagematch ) ) {
1481 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1483 $text = $sk->makeExternalImage( $url );
1486 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1487 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1488 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1489 foreach ( $whitelist as $entry ) {
1490 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1491 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1494 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1495 # Image matches a whitelist entry
1496 $text = $sk->makeExternalImage( $url );
1505 * Process [[ ]] wikilinks
1506 * @return processed text
1510 function replaceInternalLinks( $s ) {
1511 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1516 * Process [[ ]] wikilinks (RIL)
1517 * @return LinkHolderArray
1521 function replaceInternalLinks2( &$s ) {
1524 wfProfileIn( __METHOD__
);
1526 wfProfileIn( __METHOD__
.'-setup' );
1527 static $tc = FALSE, $e1, $e1_img;
1528 # the % is needed to support urlencoded titles as well
1530 $tc = Title
::legalChars() . '#%';
1531 # Match a link having the form [[namespace:link|alternate]]trail
1532 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1533 # Match cases where there is no "]]", which might still be images
1534 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1537 $sk = $this->mOptions
->getSkin();
1538 $holders = new LinkHolderArray( $this );
1540 # split the entire text string on occurences of [[
1541 $a = StringUtils
::explode( '[[', ' ' . $s );
1542 # get the first element (all text up to first [[), and remove the space we added
1545 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1546 $s = substr( $s, 1 );
1548 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1550 if ( $useLinkPrefixExtension ) {
1551 # Match the end of a line for a word that's not followed by whitespace,
1552 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1553 $e2 = wfMsgForContent( 'linkprefix' );
1556 if ( is_null( $this->mTitle
) ) {
1557 wfProfileOut( __METHOD__
.'-setup' );
1558 wfProfileOut( __METHOD__
);
1559 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1561 $nottalk = !$this->mTitle
->isTalkPage();
1563 if ( $useLinkPrefixExtension ) {
1565 if ( preg_match( $e2, $s, $m ) ) {
1566 $first_prefix = $m[2];
1568 $first_prefix = false;
1574 if ( $wgContLang->hasVariants() ) {
1575 $selflink = $wgContLang->convertLinkToAllVariants( $this->mTitle
->getPrefixedText() );
1577 $selflink = array( $this->mTitle
->getPrefixedText() );
1579 $useSubpages = $this->areSubpagesAllowed();
1580 wfProfileOut( __METHOD__
.'-setup' );
1582 # Loop for each link
1583 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1584 # Check for excessive memory usage
1585 if ( $holders->isBig() ) {
1587 # Do the existence check, replace the link holders and clear the array
1588 $holders->replace( $s );
1592 if ( $useLinkPrefixExtension ) {
1593 wfProfileIn( __METHOD__
.'-prefixhandling' );
1594 if ( preg_match( $e2, $s, $m ) ) {
1601 if ( $first_prefix ) {
1602 $prefix = $first_prefix;
1603 $first_prefix = false;
1605 wfProfileOut( __METHOD__
.'-prefixhandling' );
1608 $might_be_img = false;
1610 wfProfileIn( __METHOD__
."-e1" );
1611 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1613 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1614 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1615 # the real problem is with the $e1 regex
1618 # Still some problems for cases where the ] is meant to be outside punctuation,
1619 # and no image is in sight. See bug 2095.
1621 if ( $text !== '' &&
1622 substr( $m[3], 0, 1 ) === ']' &&
1623 strpos( $text, '[' ) !== false
1626 $text .= ']'; # so that replaceExternalLinks($text) works later
1627 $m[3] = substr( $m[3], 1 );
1629 # fix up urlencoded title texts
1630 if ( strpos( $m[1], '%' ) !== false ) {
1631 # Should anchors '#' also be rejected?
1632 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode( $m[1] ) );
1635 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1636 $might_be_img = true;
1638 if ( strpos( $m[1], '%' ) !== false ) {
1639 $m[1] = urldecode( $m[1] );
1642 } else { # Invalid form; output directly
1643 $s .= $prefix . '[[' . $line ;
1644 wfProfileOut( __METHOD__
."-e1" );
1647 wfProfileOut( __METHOD__
."-e1" );
1648 wfProfileIn( __METHOD__
."-misc" );
1650 # Don't allow internal links to pages containing
1651 # PROTO: where PROTO is a valid URL protocol; these
1652 # should be external links.
1653 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1654 $s .= $prefix . '[[' . $line ;
1655 wfProfileOut( __METHOD__
."-misc" );
1659 # Make subpage if necessary
1660 if ( $useSubpages ) {
1661 $link = $this->maybeDoSubpageLink( $m[1], $text );
1666 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1668 # Strip off leading ':'
1669 $link = substr( $link, 1 );
1672 wfProfileOut( __METHOD__
."-misc" );
1673 wfProfileIn( __METHOD__
."-title" );
1674 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1675 if ( $nt === null ) {
1676 $s .= $prefix . '[[' . $line;
1677 wfProfileOut( __METHOD__
."-title" );
1681 $ns = $nt->getNamespace();
1682 $iw = $nt->getInterWiki();
1683 wfProfileOut( __METHOD__
."-title" );
1685 if ( $might_be_img ) { # if this is actually an invalid link
1686 wfProfileIn( __METHOD__
."-might_be_img" );
1687 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1690 # look at the next 'line' to see if we can close it there
1692 $next_line = $a->current();
1693 if ( $next_line === false ||
$next_line === null ) {
1696 $m = explode( ']]', $next_line, 3 );
1697 if ( count( $m ) == 3 ) {
1698 # the first ]] closes the inner link, the second the image
1700 $text .= "[[{$m[0]}]]{$m[1]}";
1703 } elseif ( count( $m ) == 2 ) {
1704 # if there's exactly one ]] that's fine, we'll keep looking
1705 $text .= "[[{$m[0]}]]{$m[1]}";
1707 # if $next_line is invalid too, we need look no further
1708 $text .= '[[' . $next_line;
1713 # we couldn't find the end of this imageLink, so output it raw
1714 # but don't ignore what might be perfectly normal links in the text we've examined
1715 $holders->merge( $this->replaceInternalLinks2( $text ) );
1716 $s .= "{$prefix}[[$link|$text";
1717 # note: no $trail, because without an end, there *is* no trail
1718 wfProfileOut( __METHOD__
."-might_be_img" );
1721 } else { # it's not an image, so output it raw
1722 $s .= "{$prefix}[[$link|$text";
1723 # note: no $trail, because without an end, there *is* no trail
1724 wfProfileOut( __METHOD__
."-might_be_img" );
1727 wfProfileOut( __METHOD__
."-might_be_img" );
1730 $wasblank = ( $text == '' );
1735 # Link not escaped by : , create the various objects
1739 wfProfileIn( __METHOD__
."-interwiki" );
1740 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1741 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1742 $s = rtrim( $s . $prefix );
1743 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1744 wfProfileOut( __METHOD__
."-interwiki" );
1747 wfProfileOut( __METHOD__
."-interwiki" );
1749 if ( $ns == NS_FILE
) {
1750 wfProfileIn( __METHOD__
."-image" );
1751 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1753 # if no parameters were passed, $text
1754 # becomes something like "File:Foo.png",
1755 # which we don't want to pass on to the
1759 # recursively parse links inside the image caption
1760 # actually, this will parse them in any other parameters, too,
1761 # but it might be hard to fix that, and it doesn't matter ATM
1762 $text = $this->replaceExternalLinks( $text );
1763 $holders->merge( $this->replaceInternalLinks2( $text ) );
1765 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1766 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1768 $s .= $prefix . $trail;
1770 $this->mOutput
->addImage( $nt->getDBkey() );
1771 wfProfileOut( __METHOD__
."-image" );
1776 if ( $ns == NS_CATEGORY
) {
1777 wfProfileIn( __METHOD__
."-category" );
1778 $s = rtrim( $s . "\n" ); # bug 87
1781 $sortkey = $this->getDefaultSort();
1785 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1786 $sortkey = str_replace( "\n", '', $sortkey );
1787 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1788 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1791 * Strip the whitespace Category links produce, see bug 87
1792 * @todo We might want to use trim($tmp, "\n") here.
1794 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'': $prefix . $trail;
1796 wfProfileOut( __METHOD__
."-category" );
1801 # Self-link checking
1802 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1803 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1804 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1809 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1810 # FIXME: Should do batch file existence checks, see comment below
1811 if ( $ns == NS_MEDIA
) {
1812 wfProfileIn( __METHOD__
."-media" );
1813 # Give extensions a chance to select the file revision for us
1814 $skip = $time = false;
1815 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1817 $link = $sk->link( $nt );
1819 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1821 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1822 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1823 $this->mOutput
->addImage( $nt->getDBkey() );
1824 wfProfileOut( __METHOD__
."-media" );
1828 wfProfileIn( __METHOD__
."-always_known" );
1829 # Some titles, such as valid special pages or files in foreign repos, should
1830 # be shown as bluelinks even though they're not included in the page table
1832 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1833 # batch file existence checks for NS_FILE and NS_MEDIA
1834 if ( $iw == '' && $nt->isAlwaysKnown() ) {
1835 $this->mOutput
->addLink( $nt );
1836 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1838 # Links will be added to the output link list after checking
1839 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1841 wfProfileOut( __METHOD__
."-always_known" );
1843 wfProfileOut( __METHOD__
);
1848 * Make a link placeholder. The text returned can be later resolved to a real link with
1849 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1850 * parsing of interwiki links, and secondly to allow all existence checks and
1851 * article length checks (for stub links) to be bundled into a single query.
1855 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1856 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1860 * Render a forced-blue link inline; protect against double expansion of
1861 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1862 * Since this little disaster has to split off the trail text to avoid
1863 * breaking URLs in the following text without breaking trails on the
1864 * wiki links, it's been made into a horrible function.
1867 * @param string $text
1868 * @param string $query
1869 * @param string $trail
1870 * @param string $prefix
1871 * @return string HTML-wikitext mix oh yuck
1873 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1874 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1875 $sk = $this->mOptions
->getSkin();
1876 # FIXME: use link() instead of deprecated makeKnownLinkObj()
1877 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1878 return $this->armorLinks( $link ) . $trail;
1882 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1883 * going to go through further parsing steps before inline URL expansion.
1885 * Not needed quite as much as it used to be since free links are a bit
1886 * more sensible these days. But bracketed links are still an issue.
1888 * @param string more-or-less HTML
1889 * @return string less-or-more HTML with NOPARSE bits
1891 function armorLinks( $text ) {
1892 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1893 "{$this->mUniqPrefix}NOPARSE$1", $text );
1897 * Return true if subpage links should be expanded on this page.
1900 function areSubpagesAllowed() {
1901 # Some namespaces don't allow subpages
1902 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
1906 * Handle link to subpage if necessary
1907 * @param string $target the source of the link
1908 * @param string &$text the link text, modified as necessary
1909 * @return string the full name of the link
1912 function maybeDoSubpageLink( $target, &$text ) {
1913 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
1917 * Used by doBlockLevels()
1920 function closeParagraph() {
1922 if ( $this->mLastSection
!= '' ) {
1923 $result = '</' . $this->mLastSection
. ">\n";
1925 $this->mInPre
= false;
1926 $this->mLastSection
= '';
1930 * getCommon() returns the length of the longest common substring
1931 * of both arguments, starting at the beginning of both.
1934 function getCommon( $st1, $st2 ) {
1935 $fl = strlen( $st1 );
1936 $shorter = strlen( $st2 );
1937 if ( $fl < $shorter ) {
1941 for ( $i = 0; $i < $shorter; ++
$i ) {
1942 if ( $st1{$i} != $st2{$i} ) {
1949 * These next three functions open, continue, and close the list
1950 * element appropriate to the prefix character passed into them.
1953 function openList( $char ) {
1954 $result = $this->closeParagraph();
1956 if ( '*' === $char ) {
1957 $result .= '<ul><li>';
1958 } elseif ( '#' === $char ) {
1959 $result .= '<ol><li>';
1960 } elseif ( ':' === $char ) {
1961 $result .= '<dl><dd>';
1962 } elseif ( ';' === $char ) {
1963 $result .= '<dl><dt>';
1964 $this->mDTopen
= true;
1966 $result = '<!-- ERR 1 -->';
1974 * @param $char String
1977 function nextItem( $char ) {
1978 if ( '*' === $char ||
'#' === $char ) {
1980 } elseif ( ':' === $char ||
';' === $char ) {
1982 if ( $this->mDTopen
) {
1985 if ( ';' === $char ) {
1986 $this->mDTopen
= true;
1987 return $close . '<dt>';
1989 $this->mDTopen
= false;
1990 return $close . '<dd>';
1993 return '<!-- ERR 2 -->';
1998 * @param $char String
2001 function closeList( $char ) {
2002 if ( '*' === $char ) {
2003 $text = '</li></ul>';
2004 } elseif ( '#' === $char ) {
2005 $text = '</li></ol>';
2006 } elseif ( ':' === $char ) {
2007 if ( $this->mDTopen
) {
2008 $this->mDTopen
= false;
2009 $text = '</dt></dl>';
2011 $text = '</dd></dl>';
2014 return '<!-- ERR 3 -->';
2021 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2023 * @param $linestart bool whether or not this is at the start of a line.
2025 * @return string the lists rendered as HTML
2027 function doBlockLevels( $text, $linestart ) {
2028 wfProfileIn( __METHOD__
);
2030 # Parsing through the text line by line. The main thing
2031 # happening here is handling of block-level elements p, pre,
2032 # and making lists from lines starting with * # : etc.
2034 $textLines = StringUtils
::explode( "\n", $text );
2036 $lastPrefix = $output = '';
2037 $this->mDTopen
= $inBlockElem = false;
2039 $paragraphStack = false;
2041 foreach ( $textLines as $oLine ) {
2043 if ( !$linestart ) {
2053 $lastPrefixLength = strlen( $lastPrefix );
2054 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2055 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2056 # If not in a <pre> element, scan for and figure out what prefixes are there.
2057 if ( !$this->mInPre
) {
2058 # Multiple prefixes may abut each other for nested lists.
2059 $prefixLength = strspn( $oLine, '*#:;' );
2060 $prefix = substr( $oLine, 0, $prefixLength );
2063 # ; and : are both from definition-lists, so they're equivalent
2064 # for the purposes of determining whether or not we need to open/close
2066 $prefix2 = str_replace( ';', ':', $prefix );
2067 $t = substr( $oLine, $prefixLength );
2068 $this->mInPre
= (bool)$preOpenMatch;
2070 # Don't interpret any other prefixes in preformatted text
2072 $prefix = $prefix2 = '';
2077 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2078 # Same as the last item, so no need to deal with nesting or opening stuff
2079 $output .= $this->nextItem( substr( $prefix, -1 ) );
2080 $paragraphStack = false;
2082 if ( substr( $prefix, -1 ) === ';') {
2083 # The one nasty exception: definition lists work like this:
2084 # ; title : definition text
2085 # So we check for : in the remainder text to split up the
2086 # title and definition, without b0rking links.
2088 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2090 $output .= $term . $this->nextItem( ':' );
2093 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2094 # We need to open or close prefixes, or both.
2096 # Either open or close a level...
2097 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2098 $paragraphStack = false;
2100 # Close all the prefixes which aren't shared.
2101 while ( $commonPrefixLength < $lastPrefixLength ) {
2102 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2103 --$lastPrefixLength;
2106 # Continue the current prefix if appropriate.
2107 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2108 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2111 # Open prefixes where appropriate.
2112 while ( $prefixLength > $commonPrefixLength ) {
2113 $char = substr( $prefix, $commonPrefixLength, 1 );
2114 $output .= $this->openList( $char );
2116 if ( ';' === $char ) {
2117 # FIXME: This is dupe of code above
2118 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2120 $output .= $term . $this->nextItem( ':' );
2123 ++
$commonPrefixLength;
2125 $lastPrefix = $prefix2;
2128 # If we have no prefixes, go to paragraph mode.
2129 if ( 0 == $prefixLength ) {
2130 wfProfileIn( __METHOD__
."-paragraph" );
2131 # No prefix (not in list)--go to paragraph mode
2132 # XXX: use a stack for nestable elements like span, table and div
2133 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2134 $closematch = preg_match(
2135 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2136 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2137 if ( $openmatch or $closematch ) {
2138 $paragraphStack = false;
2139 #Â TODO bug 5718: paragraph closed
2140 $output .= $this->closeParagraph();
2141 if ( $preOpenMatch and !$preCloseMatch ) {
2142 $this->mInPre
= true;
2144 if ( $closematch ) {
2145 $inBlockElem = false;
2147 $inBlockElem = true;
2149 } elseif ( !$inBlockElem && !$this->mInPre
) {
2150 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2152 if ( $this->mLastSection
!== 'pre' ) {
2153 $paragraphStack = false;
2154 $output .= $this->closeParagraph().'<pre>';
2155 $this->mLastSection
= 'pre';
2157 $t = substr( $t, 1 );
2160 if ( trim( $t ) == '' ) {
2161 if ( $paragraphStack ) {
2162 $output .= $paragraphStack.'<br />';
2163 $paragraphStack = false;
2164 $this->mLastSection
= 'p';
2166 if ( $this->mLastSection
!== 'p' ) {
2167 $output .= $this->closeParagraph();
2168 $this->mLastSection
= '';
2169 $paragraphStack = '<p>';
2171 $paragraphStack = '</p><p>';
2175 if ( $paragraphStack ) {
2176 $output .= $paragraphStack;
2177 $paragraphStack = false;
2178 $this->mLastSection
= 'p';
2179 } elseif ( $this->mLastSection
!== 'p' ) {
2180 $output .= $this->closeParagraph().'<p>';
2181 $this->mLastSection
= 'p';
2186 wfProfileOut( __METHOD__
."-paragraph" );
2188 # somewhere above we forget to get out of pre block (bug 785)
2189 if ( $preCloseMatch && $this->mInPre
) {
2190 $this->mInPre
= false;
2192 if ( $paragraphStack === false ) {
2196 while ( $prefixLength ) {
2197 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2200 if ( $this->mLastSection
!= '' ) {
2201 $output .= '</' . $this->mLastSection
. '>';
2202 $this->mLastSection
= '';
2205 wfProfileOut( __METHOD__
);
2210 * Split up a string on ':', ignoring any occurences inside tags
2211 * to prevent illegal overlapping.
2212 * @param string $str the string to split
2213 * @param string &$before set to everything before the ':'
2214 * @param string &$after set to everything after the ':'
2215 * return string the position of the ':', or false if none found
2217 function findColonNoLinks( $str, &$before, &$after ) {
2218 wfProfileIn( __METHOD__
);
2220 $pos = strpos( $str, ':' );
2221 if ( $pos === false ) {
2223 wfProfileOut( __METHOD__
);
2227 $lt = strpos( $str, '<' );
2228 if ( $lt === false ||
$lt > $pos ) {
2229 # Easy; no tag nesting to worry about
2230 $before = substr( $str, 0, $pos );
2231 $after = substr( $str, $pos+
1 );
2232 wfProfileOut( __METHOD__
);
2236 # Ugly state machine to walk through avoiding tags.
2237 $state = self
::COLON_STATE_TEXT
;
2239 $len = strlen( $str );
2240 for( $i = 0; $i < $len; $i++
) {
2244 # (Using the number is a performance hack for common cases)
2245 case 0: # self::COLON_STATE_TEXT:
2248 # Could be either a <start> tag or an </end> tag
2249 $state = self
::COLON_STATE_TAGSTART
;
2252 if ( $stack == 0 ) {
2254 $before = substr( $str, 0, $i );
2255 $after = substr( $str, $i +
1 );
2256 wfProfileOut( __METHOD__
);
2259 # Embedded in a tag; don't break it.
2262 # Skip ahead looking for something interesting
2263 $colon = strpos( $str, ':', $i );
2264 if ( $colon === false ) {
2265 # Nothing else interesting
2266 wfProfileOut( __METHOD__
);
2269 $lt = strpos( $str, '<', $i );
2270 if ( $stack === 0 ) {
2271 if ( $lt === false ||
$colon < $lt ) {
2273 $before = substr( $str, 0, $colon );
2274 $after = substr( $str, $colon +
1 );
2275 wfProfileOut( __METHOD__
);
2279 if ( $lt === false ) {
2280 # Nothing else interesting to find; abort!
2281 # We're nested, but there's no close tags left. Abort!
2284 # Skip ahead to next tag start
2286 $state = self
::COLON_STATE_TAGSTART
;
2289 case 1: # self::COLON_STATE_TAG:
2294 $state = self
::COLON_STATE_TEXT
;
2297 # Slash may be followed by >?
2298 $state = self
::COLON_STATE_TAGSLASH
;
2304 case 2: # self::COLON_STATE_TAGSTART:
2307 $state = self
::COLON_STATE_CLOSETAG
;
2310 $state = self
::COLON_STATE_COMMENT
;
2313 # Illegal early close? This shouldn't happen D:
2314 $state = self
::COLON_STATE_TEXT
;
2317 $state = self
::COLON_STATE_TAG
;
2320 case 3: # self::COLON_STATE_CLOSETAG:
2325 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2326 wfProfileOut( __METHOD__
);
2329 $state = self
::COLON_STATE_TEXT
;
2332 case self
::COLON_STATE_TAGSLASH
:
2334 # Yes, a self-closed tag <blah/>
2335 $state = self
::COLON_STATE_TEXT
;
2337 # Probably we're jumping the gun, and this is an attribute
2338 $state = self
::COLON_STATE_TAG
;
2341 case 5: # self::COLON_STATE_COMMENT:
2343 $state = self
::COLON_STATE_COMMENTDASH
;
2346 case self
::COLON_STATE_COMMENTDASH
:
2348 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2350 $state = self
::COLON_STATE_COMMENT
;
2353 case self
::COLON_STATE_COMMENTDASHDASH
:
2355 $state = self
::COLON_STATE_TEXT
;
2357 $state = self
::COLON_STATE_COMMENT
;
2361 throw new MWException( "State machine error in " . __METHOD__
);
2365 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2368 wfProfileOut( __METHOD__
);
2373 * Return value of a magic variable (like PAGENAME)
2377 function getVariableValue( $index, $frame=false ) {
2378 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2379 global $wgScriptPath, $wgStylePath;
2382 * Some of these require message or data lookups and can be
2383 * expensive to check many times.
2385 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2386 if ( isset( $this->mVarCache
[$index] ) ) {
2387 return $this->mVarCache
[$index];
2391 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2392 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2395 global $wgLocaltimezone;
2396 if ( isset( $wgLocaltimezone ) ) {
2397 $oldtz = date_default_timezone_get();
2398 date_default_timezone_set( $wgLocaltimezone );
2401 $localTimestamp = date( 'YmdHis', $ts );
2402 $localMonth = date( 'm', $ts );
2403 $localMonth1 = date( 'n', $ts );
2404 $localMonthName = date( 'n', $ts );
2405 $localDay = date( 'j', $ts );
2406 $localDay2 = date( 'd', $ts );
2407 $localDayOfWeek = date( 'w', $ts );
2408 $localWeek = date( 'W', $ts );
2409 $localYear = date( 'Y', $ts );
2410 $localHour = date( 'H', $ts );
2411 if ( isset( $wgLocaltimezone ) ) {
2412 date_default_timezone_set( $oldtz );
2416 case 'currentmonth':
2417 $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2419 case 'currentmonth1':
2420 $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2422 case 'currentmonthname':
2423 $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2425 case 'currentmonthnamegen':
2426 $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2428 case 'currentmonthabbrev':
2429 $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2432 $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2435 $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2438 $value = $wgContLang->formatNum( $localMonth );
2441 $value = $wgContLang->formatNum( $localMonth1 );
2443 case 'localmonthname':
2444 $value = $wgContLang->getMonthName( $localMonthName );
2446 case 'localmonthnamegen':
2447 $value = $wgContLang->getMonthNameGen( $localMonthName );
2449 case 'localmonthabbrev':
2450 $value = $wgContLang->getMonthAbbreviation( $localMonthName );
2453 $value = $wgContLang->formatNum( $localDay );
2456 $value = $wgContLang->formatNum( $localDay2 );
2459 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2462 $value = $this->mTitle
->getPartialURL();
2464 case 'fullpagename':
2465 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2467 case 'fullpagenamee':
2468 $value = $this->mTitle
->getPrefixedURL();
2471 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2473 case 'subpagenamee':
2474 $value = $this->mTitle
->getSubpageUrlForm();
2476 case 'basepagename':
2477 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2479 case 'basepagenamee':
2480 $value = wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2482 case 'talkpagename':
2483 if ( $this->mTitle
->canTalk() ) {
2484 $talkPage = $this->mTitle
->getTalkPage();
2485 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2490 case 'talkpagenamee':
2491 if ( $this->mTitle
->canTalk() ) {
2492 $talkPage = $this->mTitle
->getTalkPage();
2493 $value = $talkPage->getPrefixedUrl();
2498 case 'subjectpagename':
2499 $subjPage = $this->mTitle
->getSubjectPage();
2500 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2502 case 'subjectpagenamee':
2503 $subjPage = $this->mTitle
->getSubjectPage();
2504 $value = $subjPage->getPrefixedUrl();
2507 # Let the edit saving system know we should parse the page
2508 # *after* a revision ID has been assigned.
2509 $this->mOutput
->setFlag( 'vary-revision' );
2510 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2511 $value = $this->mRevisionId
;
2514 # Let the edit saving system know we should parse the page
2515 # *after* a revision ID has been assigned. This is for null edits.
2516 $this->mOutput
->setFlag( 'vary-revision' );
2517 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2518 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2520 case 'revisionday2':
2521 # Let the edit saving system know we should parse the page
2522 # *after* a revision ID has been assigned. This is for null edits.
2523 $this->mOutput
->setFlag( 'vary-revision' );
2524 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2525 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2527 case 'revisionmonth':
2528 # Let the edit saving system know we should parse the page
2529 # *after* a revision ID has been assigned. This is for null edits.
2530 $this->mOutput
->setFlag( 'vary-revision' );
2531 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2532 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2534 case 'revisionyear':
2535 # Let the edit saving system know we should parse the page
2536 # *after* a revision ID has been assigned. This is for null edits.
2537 $this->mOutput
->setFlag( 'vary-revision' );
2538 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2539 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2541 case 'revisiontimestamp':
2542 # Let the edit saving system know we should parse the page
2543 # *after* a revision ID has been assigned. This is for null edits.
2544 $this->mOutput
->setFlag( 'vary-revision' );
2545 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2546 $value = $this->getRevisionTimestamp();
2548 case 'revisionuser':
2549 # Let the edit saving system know we should parse the page
2550 # *after* a revision ID has been assigned. This is for null edits.
2551 $this->mOutput
->setFlag( 'vary-revision' );
2552 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2553 $value = $this->getRevisionUser();
2556 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2559 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2562 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2565 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2567 case 'subjectspace':
2568 $value = $this->mTitle
->getSubjectNsText();
2570 case 'subjectspacee':
2571 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2573 case 'currentdayname':
2574 $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2577 $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2580 $value = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2583 $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2586 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2587 # int to remove the padding
2588 $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2591 $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2593 case 'localdayname':
2594 $value = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2597 $value = $wgContLang->formatNum( $localYear, true );
2600 $value = $wgContLang->time( $localTimestamp, false, false );
2603 $value = $wgContLang->formatNum( $localHour, true );
2606 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2607 # int to remove the padding
2608 $value = $wgContLang->formatNum( (int)$localWeek );
2611 $value = $wgContLang->formatNum( $localDayOfWeek );
2613 case 'numberofarticles':
2614 $value = $wgContLang->formatNum( SiteStats
::articles() );
2616 case 'numberoffiles':
2617 $value = $wgContLang->formatNum( SiteStats
::images() );
2619 case 'numberofusers':
2620 $value = $wgContLang->formatNum( SiteStats
::users() );
2622 case 'numberofactiveusers':
2623 $value = $wgContLang->formatNum( SiteStats
::activeUsers() );
2625 case 'numberofpages':
2626 $value = $wgContLang->formatNum( SiteStats
::pages() );
2628 case 'numberofadmins':
2629 $value = $wgContLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2631 case 'numberofedits':
2632 $value = $wgContLang->formatNum( SiteStats
::edits() );
2634 case 'numberofviews':
2635 $value = $wgContLang->formatNum( SiteStats
::views() );
2637 case 'currenttimestamp':
2638 $value = wfTimestamp( TS_MW
, $ts );
2640 case 'localtimestamp':
2641 $value = $localTimestamp;
2643 case 'currentversion':
2644 $value = SpecialVersion
::getVersion();
2651 return $wgServerName;
2653 return $wgScriptPath;
2655 return $wgStylePath;
2656 case 'directionmark':
2657 return $wgContLang->getDirMark();
2658 case 'contentlanguage':
2659 global $wgContLanguageCode;
2660 return $wgContLanguageCode;
2663 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2671 $this->mVarCache
[$index] = $value;
2677 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2681 function initialiseVariables() {
2682 wfProfileIn( __METHOD__
);
2683 $variableIDs = MagicWord
::getVariableIDs();
2684 $substIDs = MagicWord
::getSubstIDs();
2686 $this->mVariables
= new MagicWordArray( $variableIDs );
2687 $this->mSubstWords
= new MagicWordArray( $substIDs );
2688 wfProfileOut( __METHOD__
);
2692 * Preprocess some wikitext and return the document tree.
2693 * This is the ghost of replace_variables().
2695 * @param string $text The text to parse
2696 * @param integer flags Bitwise combination of:
2697 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2698 * included. Default is to assume a direct page view.
2700 * The generated DOM tree must depend only on the input text and the flags.
2701 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2703 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2704 * change in the DOM tree for a given text, must be passed through the section identifier
2705 * in the section edit link and thus back to extractSections().
2707 * The output of this function is currently only cached in process memory, but a persistent
2708 * cache may be implemented at a later date which takes further advantage of these strict
2709 * dependency requirements.
2713 function preprocessToDom( $text, $flags = 0 ) {
2714 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2719 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2721 public static function splitWhitespace( $s ) {
2722 $ltrimmed = ltrim( $s );
2723 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2724 $trimmed = rtrim( $ltrimmed );
2725 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2727 $w2 = substr( $ltrimmed, -$diff );
2731 return array( $w1, $trimmed, $w2 );
2735 * Replace magic variables, templates, and template arguments
2736 * with the appropriate text. Templates are substituted recursively,
2737 * taking care to avoid infinite loops.
2739 * Note that the substitution depends on value of $mOutputType:
2740 * self::OT_WIKI: only {{subst:}} templates
2741 * self::OT_PREPROCESS: templates but not extension tags
2742 * self::OT_HTML: all templates and extension tags
2744 * @param string $tex The text to transform
2745 * @param PPFrame $frame Object describing the arguments passed to the template.
2746 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2747 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2748 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2751 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2752 # Is there any text? Also, Prevent too big inclusions!
2753 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2756 wfProfileIn( __METHOD__
);
2758 if ( $frame === false ) {
2759 $frame = $this->getPreprocessor()->newFrame();
2760 } elseif ( !( $frame instanceof PPFrame
) ) {
2761 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2762 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2765 $dom = $this->preprocessToDom( $text );
2766 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2767 $text = $frame->expand( $dom, $flags );
2769 wfProfileOut( __METHOD__
);
2773 # Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2774 static function createAssocArgs( $args ) {
2775 $assocArgs = array();
2777 foreach ( $args as $arg ) {
2778 $eqpos = strpos( $arg, '=' );
2779 if ( $eqpos === false ) {
2780 $assocArgs[$index++
] = $arg;
2782 $name = trim( substr( $arg, 0, $eqpos ) );
2783 $value = trim( substr( $arg, $eqpos+
1 ) );
2784 if ( $value === false ) {
2787 if ( $name !== false ) {
2788 $assocArgs[$name] = $value;
2797 * Warn the user when a parser limitation is reached
2798 * Will warn at most once the user per limitation type
2800 * @param string $limitationType, should be one of:
2801 * 'expensive-parserfunction' (corresponding messages:
2802 * 'expensive-parserfunction-warning',
2803 * 'expensive-parserfunction-category')
2804 * 'post-expand-template-argument' (corresponding messages:
2805 * 'post-expand-template-argument-warning',
2806 * 'post-expand-template-argument-category')
2807 * 'post-expand-template-inclusion' (corresponding messages:
2808 * 'post-expand-template-inclusion-warning',
2809 * 'post-expand-template-inclusion-category')
2810 * @params int $current, $max When an explicit limit has been
2811 * exceeded, provide the values (optional)
2813 function limitationWarn( $limitationType, $current=null, $max=null) {
2814 # does no harm if $current and $max are present but are unnecessary for the message
2815 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
2816 $this->mOutput
->addWarning( $warning );
2817 $this->addTrackingCategory( "$limitationType-category" );
2821 * Return the text of a template, after recursively
2822 * replacing any variables or templates within the template.
2824 * @param array $piece The parts of the template
2825 * $piece['title']: the title, i.e. the part before the |
2826 * $piece['parts']: the parameter array
2827 * $piece['lineStart']: whether the brace was at the start of a line
2828 * @param PPFrame The current frame, contains template arguments
2829 * @return string the text of the template
2832 function braceSubstitution( $piece, $frame ) {
2833 global $wgContLang, $wgNonincludableNamespaces;
2834 wfProfileIn( __METHOD__
);
2835 wfProfileIn( __METHOD__
.'-setup' );
2838 $found = false; # $text has been filled
2839 $nowiki = false; # wiki markup in $text should be escaped
2840 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2841 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2842 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2843 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2845 # Title object, where $text came from
2848 # $part1 is the bit before the first |, and must contain only title characters.
2849 # Various prefixes will be stripped from it later.
2850 $titleWithSpaces = $frame->expand( $piece['title'] );
2851 $part1 = trim( $titleWithSpaces );
2854 # Original title text preserved for various purposes
2855 $originalTitle = $part1;
2857 # $args is a list of argument nodes, starting from index 0, not including $part1
2858 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
2859 wfProfileOut( __METHOD__
.'-setup' );
2862 wfProfileIn( __METHOD__
.'-modifiers' );
2865 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
2867 # Possibilities for substMatch: "subst", "safesubst" or FALSE
2868 # Decide whether to expand template or keep wikitext as-is.
2869 if ( $this->ot
['wiki'] ) {
2870 if ( $substMatch === false ) {
2871 $literal = true; # literal when in PST with no prefix
2873 $literal = false; # expand when in PST with subst: or safesubst:
2876 if ( $substMatch == 'subst' ) {
2877 $literal = true; # literal when not in PST with plain subst:
2879 $literal = false; # expand when not in PST with safesubst: or no prefix
2883 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2890 if ( !$found && $args->getLength() == 0 ) {
2891 $id = $this->mVariables
->matchStartToEnd( $part1 );
2892 if ( $id !== false ) {
2893 $text = $this->getVariableValue( $id, $frame );
2894 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
2895 $this->mOutput
->mContainsOldMagic
= true;
2901 # MSG, MSGNW and RAW
2904 $mwMsgnw = MagicWord
::get( 'msgnw' );
2905 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2908 # Remove obsolete MSG:
2909 $mwMsg = MagicWord
::get( 'msg' );
2910 $mwMsg->matchStartAndRemove( $part1 );
2914 $mwRaw = MagicWord
::get( 'raw' );
2915 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2916 $forceRawInterwiki = true;
2919 wfProfileOut( __METHOD__
.'-modifiers' );
2923 wfProfileIn( __METHOD__
. '-pfunc' );
2925 $colonPos = strpos( $part1, ':' );
2926 if ( $colonPos !== false ) {
2927 # Case sensitive functions
2928 $function = substr( $part1, 0, $colonPos );
2929 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2930 $function = $this->mFunctionSynonyms
[1][$function];
2932 # Case insensitive functions
2933 $function = $wgContLang->lc( $function );
2934 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2935 $function = $this->mFunctionSynonyms
[0][$function];
2941 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2942 $initialArgs = array( &$this );
2943 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2944 if ( $flags & SFH_OBJECT_ARGS
) {
2945 # Add a frame parameter, and pass the arguments as an array
2946 $allArgs = $initialArgs;
2947 $allArgs[] = $frame;
2948 for ( $i = 0; $i < $args->getLength(); $i++
) {
2949 $funcArgs[] = $args->item( $i );
2951 $allArgs[] = $funcArgs;
2953 # Convert arguments to plain text
2954 for ( $i = 0; $i < $args->getLength(); $i++
) {
2955 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2957 $allArgs = array_merge( $initialArgs, $funcArgs );
2960 # Workaround for PHP bug 35229 and similar
2961 if ( !is_callable( $callback ) ) {
2962 wfProfileOut( __METHOD__
. '-pfunc' );
2963 wfProfileOut( __METHOD__
);
2964 throw new MWException( "Tag hook for $function is not callable\n" );
2966 $result = call_user_func_array( $callback, $allArgs );
2969 $preprocessFlags = 0;
2971 if ( is_array( $result ) ) {
2972 if ( isset( $result[0] ) ) {
2974 unset( $result[0] );
2977 # Extract flags into the local scope
2978 # This allows callers to set flags such as nowiki, found, etc.
2984 $text = $this->preprocessToDom( $text, $preprocessFlags );
2989 wfProfileOut( __METHOD__
. '-pfunc' );
2992 # Finish mangling title and then check for loops.
2993 # Set $title to a Title object and $titleText to the PDBK
2996 # Split the title into page and subpage
2998 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2999 if ( $subpage !== '' ) {
3000 $ns = $this->mTitle
->getNamespace();
3002 $title = Title
::newFromText( $part1, $ns );
3004 $titleText = $title->getPrefixedText();
3005 # Check for language variants if the template is not found
3006 if ( $wgContLang->hasVariants() && $title->getArticleID() == 0 ) {
3007 $wgContLang->findVariantLink( $part1, $title, true );
3009 # Do recursion depth check
3010 $limit = $this->mOptions
->getMaxTemplateDepth();
3011 if ( $frame->depth
>= $limit ) {
3013 $text = '<span class="error">'
3014 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
3020 # Load from database
3021 if ( !$found && $title ) {
3022 wfProfileIn( __METHOD__
. '-loadtpl' );
3023 if ( !$title->isExternal() ) {
3024 if ( $title->getNamespace() == NS_SPECIAL
3025 && $this->mOptions
->getAllowSpecialInclusion()
3026 && $this->ot
['html'] )
3028 $text = SpecialPage
::capturePath( $title );
3029 if ( is_string( $text ) ) {
3032 $this->disableCache();
3034 } elseif ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3035 $found = false; # access denied
3036 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3038 list( $text, $title ) = $this->getTemplateDom( $title );
3039 if ( $text !== false ) {
3045 # If the title is valid but undisplayable, make a link to it
3046 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3047 $text = "[[:$titleText]]";
3050 } elseif ( $title->isTrans() ) {
3051 # Interwiki transclusion
3052 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3053 $text = $this->interwikiTransclude( $title, 'render' );
3056 $text = $this->interwikiTransclude( $title, 'raw' );
3057 # Preprocess it like a template
3058 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3064 # Do infinite loop check
3065 # This has to be done after redirect resolution to avoid infinite loops via redirects
3066 if ( !$frame->loopCheck( $title ) ) {
3068 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3069 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3071 wfProfileOut( __METHOD__
. '-loadtpl' );
3074 # If we haven't found text to substitute by now, we're done
3075 # Recover the source wikitext and return it
3077 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3078 wfProfileOut( __METHOD__
);
3079 return array( 'object' => $text );
3082 # Expand DOM-style return values in a child frame
3083 if ( $isChildObj ) {
3084 # Clean up argument array
3085 $newFrame = $frame->newChild( $args, $title );
3088 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3089 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3090 # Expansion is eligible for the empty-frame cache
3091 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3092 $text = $this->mTplExpandCache
[$titleText];
3094 $text = $newFrame->expand( $text );
3095 $this->mTplExpandCache
[$titleText] = $text;
3098 # Uncached expansion
3099 $text = $newFrame->expand( $text );
3102 if ( $isLocalObj && $nowiki ) {
3103 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3104 $isLocalObj = false;
3107 # Replace raw HTML by a placeholder
3108 # Add a blank line preceding, to prevent it from mucking up
3109 # immediately preceding headings
3111 $text = "\n\n" . $this->insertStripItem( $text );
3112 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3113 # Escape nowiki-style return values
3114 $text = wfEscapeWikiText( $text );
3115 } elseif ( is_string( $text )
3116 && !$piece['lineStart']
3117 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3119 # Bug 529: if the template begins with a table or block-level
3120 # element, it should be treated as beginning a new line.
3121 # This behaviour is somewhat controversial.
3122 $text = "\n" . $text;
3125 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3126 # Error, oversize inclusion
3127 $text = "[[$originalTitle]]" .
3128 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3129 $this->limitationWarn( 'post-expand-template-inclusion' );
3132 if ( $isLocalObj ) {
3133 $ret = array( 'object' => $text );
3135 $ret = array( 'text' => $text );
3138 wfProfileOut( __METHOD__
);
3143 * Get the semi-parsed DOM representation of a template with a given title,
3144 * and its redirect destination title. Cached.
3146 function getTemplateDom( $title ) {
3147 $cacheTitle = $title;
3148 $titleText = $title->getPrefixedDBkey();
3150 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3151 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3152 $title = Title
::makeTitle( $ns, $dbk );
3153 $titleText = $title->getPrefixedDBkey();
3155 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3156 return array( $this->mTplDomCache
[$titleText], $title );
3159 # Cache miss, go to the database
3160 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3162 if ( $text === false ) {
3163 $this->mTplDomCache
[$titleText] = false;
3164 return array( false, $title );
3167 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3168 $this->mTplDomCache
[ $titleText ] = $dom;
3170 if ( !$title->equals( $cacheTitle ) ) {
3171 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3172 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3175 return array( $dom, $title );
3179 * Fetch the unparsed text of a template and register a reference to it.
3181 function fetchTemplateAndTitle( $title ) {
3182 $templateCb = $this->mOptions
->getTemplateCallback();
3183 $stuff = call_user_func( $templateCb, $title, $this );
3184 $text = $stuff['text'];
3185 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3186 if ( isset( $stuff['deps'] ) ) {
3187 foreach ( $stuff['deps'] as $dep ) {
3188 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3191 return array( $text, $finalTitle );
3194 function fetchTemplate( $title ) {
3195 $rv = $this->fetchTemplateAndTitle( $title );
3200 * Static function to get a template
3201 * Can be overridden via ParserOptions::setTemplateCallback().
3203 static function statelessFetchTemplate( $title, $parser=false ) {
3204 $text = $skip = false;
3205 $finalTitle = $title;
3208 # Loop to fetch the article, with up to 1 redirect
3209 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3210 # Give extensions a chance to select the revision instead
3211 $id = false; # Assume current
3212 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3218 'page_id' => $title->getArticleID(),
3222 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3223 $rev_id = $rev ?
$rev->getId() : 0;
3224 # If there is no current revision, there is no page
3225 if ( $id === false && !$rev ) {
3226 $linkCache = LinkCache
::singleton();
3227 $linkCache->addBadLinkObj( $title );
3232 'page_id' => $title->getArticleID(),
3233 'rev_id' => $rev_id );
3236 $text = $rev->getText();
3237 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3239 $message = $wgContLang->lcfirst( $title->getText() );
3240 $text = wfMsgForContentNoTrans( $message );
3241 if ( wfEmptyMsg( $message, $text ) ) {
3248 if ( $text === false ) {
3252 $finalTitle = $title;
3253 $title = Title
::newFromRedirect( $text );
3257 'finalTitle' => $finalTitle,
3262 * Transclude an interwiki link.
3264 function interwikiTransclude( $title, $action ) {
3265 global $wgEnableScaryTranscluding;
3267 if ( !$wgEnableScaryTranscluding ) {
3268 return wfMsg('scarytranscludedisabled');
3271 $url = $title->getFullUrl( "action=$action" );
3273 if ( strlen( $url ) > 255 ) {
3274 return wfMsg( 'scarytranscludetoolong' );
3276 return $this->fetchScaryTemplateMaybeFromCache( $url );
3279 function fetchScaryTemplateMaybeFromCache( $url ) {
3280 global $wgTranscludeCacheExpiry;
3281 $dbr = wfGetDB( DB_SLAVE
);
3282 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3283 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3284 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3286 return $obj->tc_contents
;
3289 $text = Http
::get( $url );
3291 return wfMsg( 'scarytranscludefailed', $url );
3294 $dbw = wfGetDB( DB_MASTER
);
3295 $dbw->replace( 'transcache', array('tc_url'), array(
3297 'tc_time' => $dbw->timestamp( time() ),
3298 'tc_contents' => $text)
3305 * Triple brace replacement -- used for template arguments
3308 function argSubstitution( $piece, $frame ) {
3309 wfProfileIn( __METHOD__
);
3312 $parts = $piece['parts'];
3313 $nameWithSpaces = $frame->expand( $piece['title'] );
3314 $argName = trim( $nameWithSpaces );
3316 $text = $frame->getArgument( $argName );
3317 if ( $text === false && $parts->getLength() > 0
3321 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3324 # No match in frame, use the supplied default
3325 $object = $parts->item( 0 )->getChildren();
3327 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3328 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3329 $this->limitationWarn( 'post-expand-template-argument' );
3332 if ( $text === false && $object === false ) {
3334 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3336 if ( $error !== false ) {
3339 if ( $object !== false ) {
3340 $ret = array( 'object' => $object );
3342 $ret = array( 'text' => $text );
3345 wfProfileOut( __METHOD__
);
3350 * Return the text to be used for a given extension tag.
3351 * This is the ghost of strip().
3353 * @param array $params Associative array of parameters:
3354 * name PPNode for the tag name
3355 * attr PPNode for unparsed text where tag attributes are thought to be
3356 * attributes Optional associative array of parsed attributes
3357 * inner Contents of extension element
3358 * noClose Original text did not have a close tag
3359 * @param PPFrame $frame
3361 function extensionSubstitution( $params, $frame ) {
3362 global $wgRawHtml, $wgContLang;
3364 $name = $frame->expand( $params['name'] );
3365 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3366 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3367 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3369 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3370 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3371 if ( $isFunctionTag ) {
3372 $markerType = 'none';
3374 $markerType = 'general';
3376 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3377 $name = strtolower( $name );
3378 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3379 if ( isset( $params['attributes'] ) ) {
3380 $attributes = $attributes +
$params['attributes'];
3383 if ( isset( $this->mTagHooks
[$name] ) ) {
3384 # Workaround for PHP bug 35229 and similar
3385 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3386 throw new MWException( "Tag hook for $name is not callable\n" );
3388 $output = call_user_func_array( $this->mTagHooks
[$name],
3389 array( $content, $attributes, $this, $frame ) );
3390 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3391 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3392 if ( !is_callable( $callback ) ) {
3393 throw new MWException( "Tag hook for $name is not callable\n" );
3396 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3398 $output = '<span class="error">Invalid tag extension name: ' .
3399 htmlspecialchars( $name ) . '</span>';
3402 if ( is_array( $output ) ) {
3403 # Extract flags to local scope (to override $markerType)
3405 $output = $flags[0];
3410 if ( is_null( $attrText ) ) {
3413 if ( isset( $params['attributes'] ) ) {
3414 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3415 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3416 htmlspecialchars( $attrValue ) . '"';
3419 if ( $content === null ) {
3420 $output = "<$name$attrText/>";
3422 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3423 $output = "<$name$attrText>$content$close";
3427 if ( $markerType === 'none' ) {
3429 } elseif ( $markerType === 'nowiki' ) {
3430 $this->mStripState
->nowiki
->setPair( $marker, $output );
3431 } elseif ( $markerType === 'general' ) {
3432 $this->mStripState
->general
->setPair( $marker, $output );
3434 throw new MWException( __METHOD__
.': invalid marker type' );
3440 * Increment an include size counter
3442 * @param string $type The type of expansion
3443 * @param integer $size The size of the text
3444 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3446 function incrementIncludeSize( $type, $size ) {
3447 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3450 $this->mIncludeSizes
[$type] +
= $size;
3456 * Increment the expensive function count
3458 * @return boolean False if the limit has been exceeded
3460 function incrementExpensiveFunctionCount() {
3461 global $wgExpensiveParserFunctionLimit;
3462 $this->mExpensiveFunctionCount++
;
3463 if ( $this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit ) {
3470 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3471 * Fills $this->mDoubleUnderscores, returns the modified text
3473 function doDoubleUnderscore( $text ) {
3474 wfProfileIn( __METHOD__
);
3476 # The position of __TOC__ needs to be recorded
3477 $mw = MagicWord
::get( 'toc' );
3478 if ( $mw->match( $text ) ) {
3479 $this->mShowToc
= true;
3480 $this->mForceTocPosition
= true;
3482 # Set a placeholder. At the end we'll fill it in with the TOC.
3483 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3485 # Only keep the first one.
3486 $text = $mw->replace( '', $text );
3489 # Now match and remove the rest of them
3490 $mwa = MagicWord
::getDoubleUnderscoreArray();
3491 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3493 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3494 $this->mOutput
->mNoGallery
= true;
3496 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3497 $this->mShowToc
= false;
3499 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3500 $this->mOutput
->setProperty( 'hiddencat', 'y' );
3501 $this->addTrackingCategory( 'hidden-category-category' );
3503 # (bug 8068) Allow control over whether robots index a page.
3505 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3506 # is not desirable, the last one on the page should win.
3507 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3508 $this->mOutput
->setIndexPolicy( 'noindex' );
3509 $this->addTrackingCategory( 'noindex-category' );
3511 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3512 $this->mOutput
->setIndexPolicy( 'index' );
3513 $this->addTrackingCategory( 'index-category' );
3516 wfProfileOut( __METHOD__
);
3521 * Add a tracking category, getting the title from a system message,
3522 * or print a debug message if the title is invalid.
3523 * @param $msg String message key
3524 * @return Bool whether the addition was successful
3526 protected function addTrackingCategory( $msg ) {
3527 $cat = wfMsgForContent( $msg );
3529 # Allow tracking categories to be disabled by setting them to "-"
3530 if ( $cat === '-' ) {
3534 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3535 if ( $containerCategory ) {
3536 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3539 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3545 * This function accomplishes several tasks:
3546 * 1) Auto-number headings if that option is enabled
3547 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3548 * 3) Add a Table of contents on the top for users who have enabled the option
3549 * 4) Auto-anchor headings
3551 * It loops through all headlines, collects the necessary data, then splits up the
3552 * string and re-inserts the newly formatted headlines.
3554 * @param string $text
3555 * @param string $origText Original, untouched wikitext
3556 * @param boolean $isMain
3559 function formatHeadings( $text, $origText, $isMain=true ) {
3560 global $wgMaxTocLevel, $wgContLang, $wgHtml5, $wgExperimentalHtmlIds;
3562 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3563 $showEditLink = $this->mOptions
->getEditSection();
3565 # Do not call quickUserCan unless necessary
3566 if ( $showEditLink && !$this->mTitle
->quickUserCan( 'edit' ) ) {
3570 # Inhibit editsection links if requested in the page
3571 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ||
$this->mOptions
->getIsPrintable() ) {
3575 # Get all headlines for numbering them and adding funky stuff like [edit]
3576 # links - this is for later, but we need the number of headlines right now
3578 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3580 # if there are fewer than 4 headlines in the article, do not show TOC
3581 # unless it's been explicitly enabled.
3582 $enoughToc = $this->mShowToc
&&
3583 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
3585 # Allow user to stipulate that a page should have a "new section"
3586 # link added via __NEWSECTIONLINK__
3587 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3588 $this->mOutput
->setNewSection( true );
3591 # Allow user to remove the "new section"
3592 # link via __NONEWSECTIONLINK__
3593 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3594 $this->mOutput
->hideNewSection( true );
3597 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3598 # override above conditions and always show TOC above first header
3599 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3600 $this->mShowToc
= true;
3604 # We need this to perform operations on the HTML
3605 $sk = $this->mOptions
->getSkin();
3611 # Ugh .. the TOC should have neat indentation levels which can be
3612 # passed to the skin functions. These are determined here
3616 $sublevelCount = array();
3617 $levelCount = array();
3623 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3624 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3625 $oldType = $this->mOutputType
;
3626 $this->setOutputType( self
::OT_WIKI
);
3627 $frame = $this->getPreprocessor()->newFrame();
3628 $root = $this->preprocessToDom( $origText );
3629 $node = $root->getFirstChild();
3633 foreach ( $matches[3] as $headline ) {
3634 $isTemplate = false;
3636 $sectionIndex = false;
3638 $markerMatches = array();
3639 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
3640 $serial = $markerMatches[1];
3641 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3642 $isTemplate = ( $titleText != $baseTitleText );
3643 $headline = preg_replace( "/^$markerRegex/", "", $headline );
3647 $prevlevel = $level;
3648 $prevtoclevel = $toclevel;
3650 $level = $matches[1][$headlineCount];
3652 if ( $level > $prevlevel ) {
3653 # Increase TOC level
3655 $sublevelCount[$toclevel] = 0;
3656 if ( $toclevel<$wgMaxTocLevel ) {
3657 $prevtoclevel = $toclevel;
3658 $toc .= $sk->tocIndent();
3661 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
3662 # Decrease TOC level, find level to jump to
3664 for ( $i = $toclevel; $i > 0; $i-- ) {
3665 if ( $levelCount[$i] == $level ) {
3666 # Found last matching level
3669 } elseif ( $levelCount[$i] < $level ) {
3670 # Found first matching level below current level
3678 if ( $toclevel<$wgMaxTocLevel ) {
3679 if ( $prevtoclevel < $wgMaxTocLevel ) {
3680 # Unindent only if the previous toc level was shown :p
3681 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3682 $prevtoclevel = $toclevel;
3684 $toc .= $sk->tocLineEnd();
3688 # No change in level, end TOC line
3689 if ( $toclevel<$wgMaxTocLevel ) {
3690 $toc .= $sk->tocLineEnd();
3694 $levelCount[$toclevel] = $level;
3696 # count number of headlines for each level
3697 @$sublevelCount[$toclevel]++
;
3699 for( $i = 1; $i <= $toclevel; $i++
) {
3700 if ( !empty( $sublevelCount[$i] ) ) {
3704 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3709 # The safe header is a version of the header text safe to use for links
3710 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3711 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3713 # Remove link placeholders by the link text.
3714 # <!--LINK number-->
3716 # link text with suffix
3717 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3719 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3720 $tocline = preg_replace(
3721 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3722 array( '', '<$1>' ),
3725 $tocline = trim( $tocline );
3727 # For the anchor, strip out HTML-y stuff period
3728 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3729 $safeHeadline = preg_replace( '/[ _]+/', ' ', $safeHeadline );
3730 $safeHeadline = trim( $safeHeadline );
3732 # Save headline for section edit hint before it's escaped
3733 $headlineHint = $safeHeadline;
3735 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
3736 # For reverse compatibility, provide an id that's
3737 # HTML4-compatible, like we used to.
3739 # It may be worth noting, academically, that it's possible for
3740 # the legacy anchor to conflict with a non-legacy headline
3741 # anchor on the page. In this case likely the "correct" thing
3742 # would be to either drop the legacy anchors or make sure
3743 # they're numbered first. However, this would require people
3744 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3745 # manually, so let's not bother worrying about it.
3746 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
3747 array( 'noninitial', 'legacy' ) );
3748 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3750 if ( $legacyHeadline == $safeHeadline ) {
3751 # No reason to have both (in fact, we can't)
3752 $legacyHeadline = false;
3755 $legacyHeadline = false;
3756 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
3760 # HTML names must be case-insensitively unique (bug 10721). FIXME:
3761 # Does this apply to Unicode characters? Because we aren't
3762 # handling those here.
3763 $arrayKey = strtolower( $safeHeadline );
3764 if ( $legacyHeadline === false ) {
3765 $legacyArrayKey = false;
3767 $legacyArrayKey = strtolower( $legacyHeadline );
3770 # count how many in assoc. array so we can track dupes in anchors
3771 if ( isset( $refers[$arrayKey] ) ) {
3772 $refers[$arrayKey]++
;
3774 $refers[$arrayKey] = 1;
3776 if ( isset( $refers[$legacyArrayKey] ) ) {
3777 $refers[$legacyArrayKey]++
;
3779 $refers[$legacyArrayKey] = 1;
3782 # Don't number the heading if it is the only one (looks silly)
3783 if ( $doNumberHeadings && count( $matches[3] ) > 1) {
3784 # the two are different if the line contains a link
3785 $headline = $numbering . ' ' . $headline;
3788 # Create the anchor for linking from the TOC to the section
3789 $anchor = $safeHeadline;
3790 $legacyAnchor = $legacyHeadline;
3791 if ( $refers[$arrayKey] > 1 ) {
3792 $anchor .= '_' . $refers[$arrayKey];
3794 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3795 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3797 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
3798 $toc .= $sk->tocLine( $anchor, $tocline,
3799 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
3802 # Add the section to the section tree
3803 # Find the DOM node for this header
3804 while ( $node && !$isTemplate ) {
3805 if ( $node->getName() === 'h' ) {
3806 $bits = $node->splitHeading();
3807 if ( $bits['i'] == $sectionIndex )
3810 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
3811 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
3812 $node = $node->getNextSibling();
3815 'toclevel' => $toclevel,
3818 'number' => $numbering,
3819 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
3820 'fromtitle' => $titleText,
3821 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
3822 'anchor' => $anchor,
3825 # give headline the correct <h#> tag
3826 if ( $showEditLink && $sectionIndex !== false ) {
3827 if ( $isTemplate ) {
3828 # Put a T flag in the section identifier, to indicate to extractSections()
3829 # that sections inside <includeonly> should be counted.
3830 $editlink = $sk->doEditSectionLink( Title
::newFromText( $titleText ), "T-$sectionIndex" );
3832 $editlink = $sk->doEditSectionLink( $this->mTitle
, $sectionIndex, $headlineHint );
3837 $head[$headlineCount] = $sk->makeHeadline( $level,
3838 $matches['attrib'][$headlineCount], $anchor, $headline,
3839 $editlink, $legacyAnchor );
3844 $this->setOutputType( $oldType );
3846 # Never ever show TOC if no headers
3847 if ( $numVisible < 1 ) {
3852 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3853 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3855 $toc = $sk->tocList( $toc );
3856 $this->mOutput
->setTOCHTML( $toc );
3860 $this->mOutput
->setSections( $tocraw );
3863 # split up and insert constructed headlines
3865 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3868 foreach ( $blocks as $block ) {
3869 if ( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3870 # This is the [edit] link that appears for the top block of text when
3871 # section editing is enabled
3873 # Disabled because it broke block formatting
3874 # For example, a bullet point in the top line
3875 # $full .= $sk->editSectionLink(0);
3878 if ( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3879 # Top anchor now in skin
3883 if ( !empty( $head[$i] ) ) {
3888 if ( $this->mForceTocPosition
) {
3889 return str_replace( '<!--MWTOC-->', $toc, $full );
3896 * Merge $tree2 into $tree1 by replacing the section with index
3897 * $section in $tree1 and its descendants with the sections in $tree2.
3898 * Note that in the returned section tree, only the 'index' and
3899 * 'byteoffset' fields are guaranteed to be correct.
3900 * @param $tree1 array Section tree from ParserOutput::getSectons()
3901 * @param $tree2 array Section tree
3902 * @param $section int Section index
3903 * @param $title Title Title both section trees come from
3904 * @param $len2 int Length of the original wikitext for $tree2
3905 * @return array Merged section tree
3907 public static function mergeSectionTrees( $tree1, $tree2, $section, $title, $len2 ) {
3910 $targetLevel = false;
3914 $numbering = array( 0 );
3915 $titletext = $title->getPrefixedDBkey();
3916 foreach ( $tree1 as $s ) {
3917 if ( $targetLevel !== false ) {
3918 if ( $s['level'] <= $targetLevel ) {
3919 # We've skipped enough
3920 $targetLevel = false;
3925 if ( $s['index'] != $section ||
3926 $s['fromtitle'] != $titletext ) {
3927 self
::incrementNumbering( $numbering,
3928 $s['toclevel'], $lastLevel );
3930 # Rewrite index, byteoffset and number
3931 if ( $s['fromtitle'] == $titletext ) {
3932 $s['index'] = $nextIndex++
;
3934 $s['byteoffset'] +
= $len2;
3937 $s['number'] = implode( '.', array_map(
3938 array( $wgContLang, 'formatnum' ),
3940 $lastLevel = $s['toclevel'];
3944 # Insert sections from $tree2 here
3945 foreach ( $tree2 as $s2 ) {
3946 # Rewrite the fields in $s2
3947 # before inserting it
3948 $s2['toclevel'] +
= $s['toclevel'] - 1;
3949 $s2['level'] +
= $s['level'] - 1;
3950 $s2['index'] = $nextIndex++
;
3951 $s2['byteoffset'] +
= $s['byteoffset'];
3953 self
::incrementNumbering( $numbering,
3954 $s2['toclevel'], $lastLevel );
3955 $s2['number'] = implode( '.', array_map(
3956 array( $wgContLang, 'formatnum' ),
3958 $lastLevel = $s2['toclevel'];
3961 # Skip all descendants of $section in $tree1
3962 $targetLevel = $s['level'];
3970 * Increment a section number. Helper function for mergeSectionTrees()
3971 * @param $number array Array representing a section number
3972 * @param $level int Current TOC level (depth)
3973 * @param $lastLevel int Level of previous TOC entry
3975 private static function incrementNumbering( &$number, $level, $lastLevel ) {
3976 if ( $level > $lastLevel ) {
3977 $number[$level - 1] = 1;
3978 } elseif ( $level < $lastLevel ) {
3979 foreach ( $number as $key => $unused )
3980 if ( $key >= $level ) {
3981 unset( $number[$key] );
3983 $number[$level - 1]++
;
3985 $number[$level - 1]++
;
3990 * Transform wiki markup when saving a page by doing \r\n -> \n
3991 * conversion, substitting signatures, {{subst:}} templates, etc.
3993 * @param string $text the text to transform
3994 * @param Title &$title the Title object for the current article
3995 * @param User $user the User object describing the current user
3996 * @param ParserOptions $options parsing options
3997 * @param bool $clearState whether to clear the parser state first
3998 * @return string the altered wiki markup
4001 function preSaveTransform( $text, Title
$title, $user, $options, $clearState = true ) {
4002 $this->mOptions
= $options;
4003 $this->setTitle( $title );
4004 $this->setOutputType( self
::OT_WIKI
);
4006 if ( $clearState ) {
4007 $this->clearState();
4013 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4014 $text = $this->pstPass2( $text, $user );
4015 $text = $this->mStripState
->unstripBoth( $text );
4020 * Pre-save transform helper function
4023 function pstPass2( $text, $user ) {
4024 global $wgContLang, $wgLocaltimezone;
4026 # Note: This is the timestamp saved as hardcoded wikitext to
4027 # the database, we use $wgContLang here in order to give
4028 # everyone the same signature and use the default one rather
4029 # than the one selected in each user's preferences.
4030 # (see also bug 12815)
4031 $ts = $this->mOptions
->getTimestamp();
4032 if ( isset( $wgLocaltimezone ) ) {
4033 $tz = $wgLocaltimezone;
4035 $tz = date_default_timezone_get();
4038 $unixts = wfTimestamp( TS_UNIX
, $ts );
4039 $oldtz = date_default_timezone_get();
4040 date_default_timezone_set( $tz );
4041 $ts = date( 'YmdHis', $unixts );
4042 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4044 # Allow translation of timezones trough wiki. date() can return
4045 # whatever crap the system uses, localised or not, so we cannot
4046 # ship premade translations.
4047 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4048 $value = wfMsgForContent( $key );
4049 if ( !wfEmptyMsg( $key, $value ) ) {
4053 date_default_timezone_set( $oldtz );
4055 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4057 # Variable replacement
4058 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4059 $text = $this->replaceVariables( $text );
4062 $sigText = $this->getUserSig( $user );
4063 $text = strtr( $text, array(
4065 '~~~~' => "$sigText $d",
4069 # Context links: [[|name]] and [[name (context)|]]
4070 global $wgLegalTitleChars;
4071 $tc = "[$wgLegalTitleChars]";
4072 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4074 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4075 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
4076 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4077 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4079 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4080 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4081 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4082 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4084 $t = $this->mTitle
->getText();
4086 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4087 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4088 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4089 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4091 # if there's no context, don't bother duplicating the title
4092 $text = preg_replace( $p2, '[[\\1]]', $text );
4095 # Trim trailing whitespace
4096 $text = rtrim( $text );
4102 * Fetch the user's signature text, if any, and normalize to
4103 * validated, ready-to-insert wikitext.
4104 * If you have pre-fetched the nickname or the fancySig option, you can
4105 * specify them here to save a database query.
4110 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4111 global $wgMaxSigChars;
4113 $username = $user->getName();
4115 # If not given, retrieve from the user object.
4116 if ( $nickname === false )
4117 $nickname = $user->getOption( 'nickname' );
4119 if ( is_null( $fancySig ) ) {
4120 $fancySig = $user->getBoolOption( 'fancysig' );
4123 $nickname = $nickname == null ?
$username : $nickname;
4125 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4126 $nickname = $username;
4127 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4128 } elseif ( $fancySig !== false ) {
4129 # Sig. might contain markup; validate this
4130 if ( $this->validateSig( $nickname ) !== false ) {
4131 # Validated; clean up (if needed) and return it
4132 return $this->cleanSig( $nickname, true );
4134 # Failed to validate; fall back to the default
4135 $nickname = $username;
4136 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4140 # Make sure nickname doesnt get a sig in a sig
4141 $nickname = $this->cleanSigInSig( $nickname );
4143 # If we're still here, make it a link to the user page
4144 $userText = wfEscapeWikiText( $username );
4145 $nickText = wfEscapeWikiText( $nickname );
4146 if ( $user->isAnon() ) {
4147 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4149 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4154 * Check that the user's signature contains no bad XML
4156 * @param string $text
4157 * @return mixed An expanded string, or false if invalid.
4159 function validateSig( $text ) {
4160 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4164 * Clean up signature text
4166 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4167 * 2) Substitute all transclusions
4169 * @param string $text
4170 * @param $parsing Whether we're cleaning (preferences save) or parsing
4171 * @return string Signature text
4173 function cleanSig( $text, $parsing = false ) {
4176 $this->clearState();
4177 $this->setTitle( $wgTitle );
4178 $this->mOptions
= new ParserOptions
;
4179 $this->setOutputType
= self
::OT_PREPROCESS
;
4182 # Option to disable this feature
4183 if ( !$this->mOptions
->getCleanSignatures() ) {
4187 # FIXME: regex doesn't respect extension tags or nowiki
4188 # => Move this logic to braceSubstitution()
4189 $substWord = MagicWord
::get( 'subst' );
4190 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4191 $substText = '{{' . $substWord->getSynonym( 0 );
4193 $text = preg_replace( $substRegex, $substText, $text );
4194 $text = $this->cleanSigInSig( $text );
4195 $dom = $this->preprocessToDom( $text );
4196 $frame = $this->getPreprocessor()->newFrame();
4197 $text = $frame->expand( $dom );
4200 $text = $this->mStripState
->unstripBoth( $text );
4207 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4208 * @param string $text
4209 * @return string Signature text with /~{3,5}/ removed
4211 function cleanSigInSig( $text ) {
4212 $text = preg_replace( '/~{3,5}/', '', $text );
4217 * Set up some variables which are usually set up in parse()
4218 * so that an external function can call some class members with confidence
4221 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
4222 $this->setTitle( $title );
4223 $this->mOptions
= $options;
4224 $this->setOutputType( $outputType );
4225 if ( $clearState ) {
4226 $this->clearState();
4231 * Wrapper for preprocess()
4233 * @param string $text the text to preprocess
4234 * @param ParserOptions $options options
4238 function transformMsg( $text, $options ) {
4240 static $executing = false;
4242 # Guard against infinite recursion
4248 wfProfileIn( __METHOD__
);
4249 $text = $this->preprocess( $text, $wgTitle, $options );
4252 wfProfileOut( __METHOD__
);
4257 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4258 * The callback should have the following form:
4259 * function myParserHook( $text, $params, $parser ) { ... }
4261 * Transform and return $text. Use $parser for any required context, e.g. use
4262 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4266 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
4267 * @param mixed $callback The callback function (and object) to use for the tag
4269 * @return The old value of the mTagHooks array associated with the hook
4271 function setHook( $tag, $callback ) {
4272 $tag = strtolower( $tag );
4273 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4274 $this->mTagHooks
[$tag] = $callback;
4275 if ( !in_array( $tag, $this->mStripList
) ) {
4276 $this->mStripList
[] = $tag;
4282 function setTransparentTagHook( $tag, $callback ) {
4283 $tag = strtolower( $tag );
4284 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4285 $this->mTransparentTagHooks
[$tag] = $callback;
4291 * Remove all tag hooks
4293 function clearTagHooks() {
4294 $this->mTagHooks
= array();
4295 $this->mStripList
= $this->mDefaultStripList
;
4299 * Create a function, e.g. {{sum:1|2|3}}
4300 * The callback function should have the form:
4301 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4303 * Or with SFH_OBJECT_ARGS:
4304 * function myParserFunction( $parser, $frame, $args ) { ... }
4306 * The callback may either return the text result of the function, or an array with the text
4307 * in element 0, and a number of flags in the other elements. The names of the flags are
4308 * specified in the keys. Valid flags are:
4309 * found The text returned is valid, stop processing the template. This
4311 * nowiki Wiki markup in the return value should be escaped
4312 * isHTML The returned text is HTML, armour it against wikitext transformation
4316 * @param string $id The magic word ID
4317 * @param mixed $callback The callback function (and object) to use
4318 * @param integer $flags a combination of the following flags:
4319 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4321 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4322 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4323 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4324 * the arguments, and to control the way they are expanded.
4326 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4327 * arguments, for instance:
4328 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4330 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4331 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4332 * working if/when this is changed.
4334 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4337 * Please read the documentation in includes/parser/Preprocessor.php for more information
4338 * about the methods available in PPFrame and PPNode.
4340 * @return The old callback function for this name, if any
4342 function setFunctionHook( $id, $callback, $flags = 0 ) {
4345 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4346 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4348 # Add to function cache
4349 $mw = MagicWord
::get( $id );
4351 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4353 $synonyms = $mw->getSynonyms();
4354 $sensitive = intval( $mw->isCaseSensitive() );
4356 foreach ( $synonyms as $syn ) {
4358 if ( !$sensitive ) {
4359 $syn = $wgContLang->lc( $syn );
4362 if ( !( $flags & SFH_NO_HASH
) ) {
4365 # Remove trailing colon
4366 if ( substr( $syn, -1, 1 ) === ':' ) {
4367 $syn = substr( $syn, 0, -1 );
4369 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4375 * Get all registered function hook identifiers
4379 function getFunctionHooks() {
4380 return array_keys( $this->mFunctionHooks
);
4384 * Create a tag function, e.g. <test>some stuff</test>.
4385 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4386 * Unlike parser functions, their content is not preprocessed.
4388 function setFunctionTagHook( $tag, $callback, $flags ) {
4389 $tag = strtolower( $tag );
4390 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4391 $this->mFunctionTagHooks
[$tag] : null;
4392 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4394 if ( !in_array( $tag, $this->mStripList
) ) {
4395 $this->mStripList
[] = $tag;
4402 * FIXME: update documentation. makeLinkObj() is deprecated.
4403 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4404 * Placeholders created in Skin::makeLinkObj()
4405 * Returns an array of link CSS classes, indexed by PDBK.
4407 function replaceLinkHolders( &$text, $options = 0 ) {
4408 return $this->mLinkHolders
->replace( $text );
4412 * Replace <!--LINK--> link placeholders with plain text of links
4413 * (not HTML-formatted).
4414 * @param string $text
4417 function replaceLinkHoldersText( $text ) {
4418 return $this->mLinkHolders
->replaceText( $text );
4422 * Renders an image gallery from a text with one line per image.
4423 * text labels may be given by using |-style alternative text. E.g.
4424 * Image:one.jpg|The number "1"
4425 * Image:tree.jpg|A tree
4426 * given as text will return the HTML of a gallery with two images,
4427 * labeled 'The number "1"' and
4430 function renderImageGallery( $text, $params ) {
4431 $ig = new ImageGallery();
4432 $ig->setContextTitle( $this->mTitle
);
4433 $ig->setShowBytes( false );
4434 $ig->setShowFilename( false );
4435 $ig->setParser( $this );
4436 $ig->setHideBadImages();
4437 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4438 $ig->useSkin( $this->mOptions
->getSkin() );
4439 $ig->mRevisionId
= $this->mRevisionId
;
4441 if ( isset( $params['showfilename'] ) ) {
4442 $ig->setShowFilename( true );
4444 $ig->setShowFilename( false );
4446 if ( isset( $params['caption'] ) ) {
4447 $caption = $params['caption'];
4448 $caption = htmlspecialchars( $caption );
4449 $caption = $this->replaceInternalLinks( $caption );
4450 $ig->setCaptionHtml( $caption );
4452 if ( isset( $params['perrow'] ) ) {
4453 $ig->setPerRow( $params['perrow'] );
4455 if ( isset( $params['widths'] ) ) {
4456 $ig->setWidths( $params['widths'] );
4458 if ( isset( $params['heights'] ) ) {
4459 $ig->setHeights( $params['heights'] );
4462 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4464 $lines = StringUtils
::explode( "\n", $text );
4465 foreach ( $lines as $line ) {
4466 # match lines like these:
4467 # Image:someimage.jpg|This is some image
4469 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4471 if ( count( $matches ) == 0 ) {
4475 if ( strpos( $matches[0], '%' ) !== false ) {
4476 $matches[1] = urldecode( $matches[1] );
4478 $tp = Title
::newFromText( $matches[1] );
4480 if ( is_null( $nt ) ) {
4481 # Bogus title. Ignore these so we don't bomb out later.
4484 if ( isset( $matches[3] ) ) {
4485 $label = $matches[3];
4490 $html = $this->recursiveTagParse( trim( $label ) );
4492 $ig->add( $nt, $html );
4494 # Only add real images (bug #5586)
4495 if ( $nt->getNamespace() == NS_FILE
) {
4496 $this->mOutput
->addImage( $nt->getDBkey() );
4499 return $ig->toHTML();
4502 function getImageParams( $handler ) {
4504 $handlerClass = get_class( $handler );
4508 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4509 # Initialise static lists
4510 static $internalParamNames = array(
4511 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4512 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4513 'bottom', 'text-bottom' ),
4514 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4515 'upright', 'border', 'link', 'alt' ),
4517 static $internalParamMap;
4518 if ( !$internalParamMap ) {
4519 $internalParamMap = array();
4520 foreach ( $internalParamNames as $type => $names ) {
4521 foreach ( $names as $name ) {
4522 $magicName = str_replace( '-', '_', "img_$name" );
4523 $internalParamMap[$magicName] = array( $type, $name );
4528 # Add handler params
4529 $paramMap = $internalParamMap;
4531 $handlerParamMap = $handler->getParamMap();
4532 foreach ( $handlerParamMap as $magic => $paramName ) {
4533 $paramMap[$magic] = array( 'handler', $paramName );
4536 $this->mImageParams
[$handlerClass] = $paramMap;
4537 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4539 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4543 * Parse image options text and use it to make an image
4544 * @param Title $title
4545 * @param string $options
4546 * @param LinkHolderArray $holders
4548 function makeImage( $title, $options, $holders = false ) {
4549 # Check if the options text is of the form "options|alt text"
4551 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4552 # * left no resizing, just left align. label is used for alt= only
4553 # * right same, but right aligned
4554 # * none same, but not aligned
4555 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4556 # * center center the image
4557 # * frame Keep original image size, no magnify-button.
4558 # * framed Same as "frame"
4559 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4560 # * upright reduce width for upright images, rounded to full __0 px
4561 # * border draw a 1px border around the image
4562 # * alt Text for HTML alt attribute (defaults to empty)
4563 # * link Set the target of the image link. Can be external, interwiki, or local
4564 # vertical-align values (no % or length right now):
4574 $parts = StringUtils
::explode( "|", $options );
4575 $sk = $this->mOptions
->getSkin();
4577 # Give extensions a chance to select the file revision for us
4578 $skip = $time = $descQuery = false;
4579 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4582 return $sk->link( $title );
4586 $imagename = $title->getDBkey();
4587 $file = wfFindFile( $title, array( 'time' => $time ) );
4589 $handler = $file ?
$file->getHandler() : false;
4591 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4593 # Process the input parameters
4595 $params = array( 'frame' => array(), 'handler' => array(),
4596 'horizAlign' => array(), 'vertAlign' => array() );
4597 foreach ( $parts as $part ) {
4598 $part = trim( $part );
4599 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4601 if ( isset( $paramMap[$magicName] ) ) {
4602 list( $type, $paramName ) = $paramMap[$magicName];
4604 # Special case; width and height come in one variable together
4605 if ( $type === 'handler' && $paramName === 'width' ) {
4607 # (bug 13500) In both cases (width/height and width only),
4608 # permit trailing "px" for backward compatibility.
4609 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4610 $width = intval( $m[1] );
4611 $height = intval( $m[2] );
4612 if ( $handler->validateParam( 'width', $width ) ) {
4613 $params[$type]['width'] = $width;
4616 if ( $handler->validateParam( 'height', $height ) ) {
4617 $params[$type]['height'] = $height;
4620 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4621 $width = intval( $value );
4622 if ( $handler->validateParam( 'width', $width ) ) {
4623 $params[$type]['width'] = $width;
4626 } # else no validation -- bug 13436
4628 if ( $type === 'handler' ) {
4629 # Validate handler parameter
4630 $validated = $handler->validateParam( $paramName, $value );
4632 # Validate internal parameters
4633 switch( $paramName ) {
4636 # @todo Fixme: possibly check validity here for
4637 # manualthumb? downstream behavior seems odd with
4638 # missing manual thumbs.
4640 $value = $this->stripAltText( $value, $holders );
4643 $chars = self
::EXT_LINK_URL_CLASS
;
4644 $prots = $this->mUrlProtocols
;
4645 if ( $value === '' ) {
4646 $paramName = 'no-link';
4649 } elseif ( preg_match( "/^$prots/", $value ) ) {
4650 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4651 $paramName = 'link-url';
4652 $this->mOutput
->addExternalLink( $value );
4656 $linkTitle = Title
::newFromText( $value );
4658 $paramName = 'link-title';
4659 $value = $linkTitle;
4660 $this->mOutput
->addLink( $linkTitle );
4666 # Most other things appear to be empty or numeric...
4667 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4672 $params[$type][$paramName] = $value;
4676 if ( !$validated ) {
4681 # Process alignment parameters
4682 if ( $params['horizAlign'] ) {
4683 $params['frame']['align'] = key( $params['horizAlign'] );
4685 if ( $params['vertAlign'] ) {
4686 $params['frame']['valign'] = key( $params['vertAlign'] );
4689 $params['frame']['caption'] = $caption;
4691 # Will the image be presented in a frame, with the caption below?
4692 $imageIsFramed = isset( $params['frame']['frame'] ) ||
4693 isset( $params['frame']['framed'] ) ||
4694 isset( $params['frame']['thumbnail'] ) ||
4695 isset( $params['frame']['manualthumb'] );
4697 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4698 # came to also set the caption, ordinary text after the image -- which
4699 # makes no sense, because that just repeats the text multiple times in
4700 # screen readers. It *also* came to set the title attribute.
4702 # Now that we have an alt attribute, we should not set the alt text to
4703 # equal the caption: that's worse than useless, it just repeats the
4704 # text. This is the framed/thumbnail case. If there's no caption, we
4705 # use the unnamed parameter for alt text as well, just for the time be-
4706 # ing, if the unnamed param is set and the alt param is not.
4708 # For the future, we need to figure out if we want to tweak this more,
4709 # e.g., introducing a title= parameter for the title; ignoring the un-
4710 # named parameter entirely for images without a caption; adding an ex-
4711 # plicit caption= parameter and preserving the old magic unnamed para-
4713 if ( $imageIsFramed ) { # Framed image
4714 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
4715 # No caption or alt text, add the filename as the alt text so
4716 # that screen readers at least get some description of the image
4717 $params['frame']['alt'] = $title->getText();
4719 # Do not set $params['frame']['title'] because tooltips don't make sense
4721 } else { # Inline image
4722 if ( !isset( $params['frame']['alt'] ) ) {
4723 # No alt text, use the "caption" for the alt text
4724 if ( $caption !== '') {
4725 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
4727 # No caption, fall back to using the filename for the
4729 $params['frame']['alt'] = $title->getText();
4732 # Use the "caption" for the tooltip text
4733 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4736 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4738 # Linker does the rest
4739 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4741 # Give the handler a chance to modify the parser object
4743 $handler->parserTransformHook( $this, $file );
4749 protected function stripAltText( $caption, $holders ) {
4750 # Strip bad stuff out of the title (tooltip). We can't just use
4751 # replaceLinkHoldersText() here, because if this function is called
4752 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4754 $tooltip = $holders->replaceText( $caption );
4756 $tooltip = $this->replaceLinkHoldersText( $caption );
4759 # make sure there are no placeholders in thumbnail attributes
4760 # that are later expanded to html- so expand them now and
4762 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
4763 $tooltip = Sanitizer
::stripAllTags( $tooltip );
4769 * Set a flag in the output object indicating that the content is dynamic and
4770 * shouldn't be cached.
4772 function disableCache() {
4773 wfDebug( "Parser output marked as uncacheable.\n" );
4774 $this->mOutput
->mCacheTime
= -1;
4778 * Callback from the Sanitizer for expanding items found in HTML attribute
4779 * values, so they can be safely tested and escaped.
4780 * @param string $text
4781 * @param PPFrame $frame
4785 function attributeStripCallback( &$text, $frame = false ) {
4786 $text = $this->replaceVariables( $text, $frame );
4787 $text = $this->mStripState
->unstripBoth( $text );
4796 function Title( $x = null ) { return wfSetVar( $this->mTitle
, $x ); }
4797 function Options( $x = null ) { return wfSetVar( $this->mOptions
, $x ); }
4798 function OutputType( $x = null ) { return wfSetVar( $this->mOutputType
, $x ); }
4804 function getTags() {
4805 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) );
4811 * Break wikitext input into sections, and either pull or replace
4812 * some particular section's text.
4814 * External callers should use the getSection and replaceSection methods.
4816 * @param string $text Page wikitext
4817 * @param string $section A section identifier string of the form:
4818 * <flag1> - <flag2> - ... - <section number>
4820 * Currently the only recognised flag is "T", which means the target section number
4821 * was derived during a template inclusion parse, in other words this is a template
4822 * section edit link. If no flags are given, it was an ordinary section edit link.
4823 * This flag is required to avoid a section numbering mismatch when a section is
4824 * enclosed by <includeonly> (bug 6563).
4826 * The section number 0 pulls the text before the first heading; other numbers will
4827 * pull the given section along with its lower-level subsections. If the section is
4828 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4830 * @param string $mode One of "get" or "replace"
4831 * @param string $newText Replacement text for section data.
4832 * @return string for "get", the extracted section text.
4833 * for "replace", the whole page with the section replaced.
4835 private function extractSections( $text, $section, $mode, $newText='' ) {
4837 $this->clearState();
4838 $this->setTitle( $wgTitle ); # not generally used but removes an ugly failure mode
4839 $this->mOptions
= new ParserOptions
;
4840 $this->setOutputType( self
::OT_PLAIN
);
4842 $frame = $this->getPreprocessor()->newFrame();
4844 # Process section extraction flags
4846 $sectionParts = explode( '-', $section );
4847 $sectionIndex = array_pop( $sectionParts );
4848 foreach ( $sectionParts as $part ) {
4849 if ( $part === 'T' ) {
4850 $flags |
= self
::PTD_FOR_INCLUSION
;
4853 # Preprocess the text
4854 $root = $this->preprocessToDom( $text, $flags );
4856 # <h> nodes indicate section breaks
4857 # They can only occur at the top level, so we can find them by iterating the root's children
4858 $node = $root->getFirstChild();
4860 # Find the target section
4861 if ( $sectionIndex == 0 ) {
4862 # Section zero doesn't nest, level=big
4863 $targetLevel = 1000;
4866 if ( $node->getName() === 'h' ) {
4867 $bits = $node->splitHeading();
4868 if ( $bits['i'] == $sectionIndex ) {
4869 $targetLevel = $bits['level'];
4873 if ( $mode === 'replace' ) {
4874 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4876 $node = $node->getNextSibling();
4882 if ( $mode === 'get' ) {
4889 # Find the end of the section, including nested sections
4891 if ( $node->getName() === 'h' ) {
4892 $bits = $node->splitHeading();
4893 $curLevel = $bits['level'];
4894 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4898 if ( $mode === 'get' ) {
4899 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4901 $node = $node->getNextSibling();
4904 # Write out the remainder (in replace mode only)
4905 if ( $mode === 'replace' ) {
4906 # Output the replacement text
4907 # Add two newlines on -- trailing whitespace in $newText is conventionally
4908 # stripped by the editor, so we need both newlines to restore the paragraph gap
4909 # Only add trailing whitespace if there is newText
4910 if ( $newText != "" ) {
4911 $outText .= $newText . "\n\n";
4915 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4916 $node = $node->getNextSibling();
4920 if ( is_string( $outText ) ) {
4921 # Re-insert stripped tags
4922 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4929 * This function returns the text of a section, specified by a number ($section).
4930 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4931 * the first section before any such heading (section 0).
4933 * If a section contains subsections, these are also returned.
4935 * @param string $text text to look in
4936 * @param string $section section identifier
4937 * @param string $deftext default to return if section is not found
4938 * @return string text of the requested section
4940 public function getSection( $text, $section, $deftext='' ) {
4941 return $this->extractSections( $text, $section, "get", $deftext );
4944 public function replaceSection( $oldtext, $section, $text ) {
4945 return $this->extractSections( $oldtext, $section, "replace", $text );
4949 * Get the timestamp associated with the current revision, adjusted for
4950 * the default server-local timestamp
4952 function getRevisionTimestamp() {
4953 if ( is_null( $this->mRevisionTimestamp
) ) {
4954 wfProfileIn( __METHOD__
);
4956 $dbr = wfGetDB( DB_SLAVE
);
4957 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4958 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4960 # Normalize timestamp to internal MW format for timezone processing.
4961 # This has the added side-effect of replacing a null value with
4962 # the current time, which gives us more sensible behavior for
4964 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4966 # The cryptic '' timezone parameter tells to use the site-default
4967 # timezone offset instead of the user settings.
4969 # Since this value will be saved into the parser cache, served
4970 # to other users, and potentially even used inside links and such,
4971 # it needs to be consistent for all visitors.
4972 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4974 wfProfileOut( __METHOD__
);
4976 return $this->mRevisionTimestamp
;
4980 * Get the name of the user that edited the last revision
4982 function getRevisionUser() {
4983 # if this template is subst: the revision id will be blank,
4984 # so just use the current user's name
4985 if ( $this->mRevisionId
) {
4986 $revision = Revision
::newFromId( $this->mRevisionId
);
4987 $revuser = $revision->getUserText();
4990 $revuser = $wgUser->getName();
4996 * Mutator for $mDefaultSort
4998 * @param $sort New value
5000 public function setDefaultSort( $sort ) {
5001 $this->mDefaultSort
= $sort;
5005 * Accessor for $mDefaultSort
5006 * Will use the title/prefixed title if none is set
5010 public function getDefaultSort() {
5011 global $wgCategoryPrefixedDefaultSortkey;
5012 if ( $this->mDefaultSort
!== false ) {
5013 return $this->mDefaultSort
;
5014 } elseif ( $this->mTitle
->getNamespace() == NS_CATEGORY ||
5015 !$wgCategoryPrefixedDefaultSortkey )
5017 return $this->mTitle
->getText();
5019 return $this->mTitle
->getPrefixedText();
5024 * Accessor for $mDefaultSort
5025 * Unlike getDefaultSort(), will return false if none is set
5027 * @return string or false
5029 public function getCustomDefaultSort() {
5030 return $this->mDefaultSort
;
5034 * Try to guess the section anchor name based on a wikitext fragment
5035 * presumably extracted from a heading, for example "Header" from
5038 public function guessSectionNameFromWikiText( $text ) {
5039 # Strip out wikitext links(they break the anchor)
5040 $text = $this->stripSectionName( $text );
5041 $headline = Sanitizer
::decodeCharReferences( $text );
5043 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
5044 $headline = trim( $headline );
5045 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
5046 $replacearray = array(
5051 array_keys( $replacearray ),
5052 array_values( $replacearray ),
5057 * Strips a text string of wikitext for use in a section anchor
5059 * Accepts a text string and then removes all wikitext from the
5060 * string and leaves only the resultant text (i.e. the result of
5061 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5062 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5063 * to create valid section anchors by mimicing the output of the
5064 * parser when headings are parsed.
5066 * @param $text string Text string to be stripped of wikitext
5067 * for use in a Section anchor
5068 * @return Filtered text string
5070 public function stripSectionName( $text ) {
5071 # Strip internal link markup
5072 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5073 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5075 # Strip external link markup (FIXME: Not Tolerant to blank link text
5076 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5077 # on how many empty links there are on the page - need to figure that out.
5078 $text = preg_replace( '/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5080 # Parse wikitext quotes (italics & bold)
5081 $text = $this->doQuotes( $text );
5084 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5088 function srvus( $text ) {
5089 return $this->testSrvus( $text, $this->mOutputType
);
5093 * strip/replaceVariables/unstrip for preprocessor regression testing
5095 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
5096 $this->clearState();
5097 if ( !$title instanceof Title
) {
5098 $title = Title
::newFromText( $title );
5100 $this->mTitle
= $title;
5101 $this->mOptions
= $options;
5102 $this->setOutputType( $outputType );
5103 $text = $this->replaceVariables( $text );
5104 $text = $this->mStripState
->unstripBoth( $text );
5105 $text = Sanitizer
::removeHTMLtags( $text );
5109 function testPst( $text, $title, $options ) {
5111 if ( !$title instanceof Title
) {
5112 $title = Title
::newFromText( $title );
5114 return $this->preSaveTransform( $text, $title, $wgUser, $options );
5117 function testPreprocess( $text, $title, $options ) {
5118 if ( !$title instanceof Title
) {
5119 $title = Title
::newFromText( $title );
5121 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5124 function markerSkipCallback( $s, $callback ) {
5127 while ( $i < strlen( $s ) ) {
5128 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5129 if ( $markerStart === false ) {
5130 $out .= call_user_func( $callback, substr( $s, $i ) );
5133 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5134 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5135 if ( $markerEnd === false ) {
5136 $out .= substr( $s, $markerStart );
5139 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5140 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5148 function serialiseHalfParsedText( $text ) {
5150 $data['text'] = $text;
5152 # First, find all strip markers, and store their
5154 $stripState = new StripState
;
5156 while ( ( $start_pos = strpos( $text, $this->mUniqPrefix
, $pos ) )
5157 && ( $end_pos = strpos( $text, self
::MARKER_SUFFIX
, $pos ) ) )
5159 $end_pos +
= strlen( self
::MARKER_SUFFIX
);
5160 $marker = substr( $text, $start_pos, $end_pos-$start_pos );
5162 if ( !empty( $this->mStripState
->general
->data
[$marker] ) ) {
5163 $replaceArray = $stripState->general
;
5164 $stripText = $this->mStripState
->general
->data
[$marker];
5165 } elseif ( !empty( $this->mStripState
->nowiki
->data
[$marker] ) ) {
5166 $replaceArray = $stripState->nowiki
;
5167 $stripText = $this->mStripState
->nowiki
->data
[$marker];
5169 throw new MWException( "Hanging strip marker: '$marker'." );
5172 $replaceArray->setPair( $marker, $stripText );
5175 $data['stripstate'] = $stripState;
5177 # Now, find all of our links, and store THEIR
5178 # data in an array! :)
5179 $links = array( 'internal' => array(), 'interwiki' => array() );
5183 while ( ( $start_pos = strpos( $text, '<!--LINK ', $pos ) ) ) {
5184 list( $ns, $trail ) = explode( ':', substr( $text, $start_pos +
strlen( '<!--LINK ' ) ), 2 );
5187 if ( empty( $links['internal'][$ns] ) ) {
5188 $links['internal'][$ns] = array();
5191 $key = trim( substr( $trail, 0, strpos( $trail, '-->' ) ) );
5192 $links['internal'][$ns][] = $this->mLinkHolders
->internals
[$ns][$key];
5193 $pos = $start_pos +
strlen( "<!--LINK $ns:$key-->" );
5199 while ( ( $start_pos = strpos( $text, '<!--IWLINK ', $pos ) ) ) {
5200 $data = substr( $text, $start_pos );
5201 $key = trim( substr( $data, 0, strpos( $data, '-->' ) ) );
5202 $links['interwiki'][] = $this->mLinkHolders
->interwiki
[$key];
5203 $pos = $start_pos +
strlen( "<!--IWLINK $key-->" );
5206 $data['linkholder'] = $links;
5213 * @param $data Array
5214 * @param $intPrefix String unique identifying prefix
5217 function unserialiseHalfParsedText( $data, $intPrefix = null ) {
5218 if ( !$intPrefix ) {
5219 $intPrefix = $this->getRandomString();
5222 # First, extract the strip state.
5223 $stripState = $data['stripstate'];
5224 $this->mStripState
->general
->merge( $stripState->general
);
5225 $this->mStripState
->nowiki
->merge( $stripState->nowiki
);
5227 # Now, extract the text, and renumber links
5228 $text = $data['text'];
5229 $links = $data['linkholder'];
5232 foreach ( $links['internal'] as $ns => $nsLinks ) {
5233 foreach ( $nsLinks as $key => $entry ) {
5234 $newKey = $intPrefix . '-' . $key;
5235 $this->mLinkHolders
->internals
[$ns][$newKey] = $entry;
5237 $text = str_replace( "<!--LINK $ns:$key-->", "<!--LINK $ns:$newKey-->", $text );
5242 foreach ( $links['interwiki'] as $key => $entry ) {
5243 $newKey = "$intPrefix-$key";
5244 $this->mLinkHolders
->interwikis
[$newKey] = $entry;
5246 $text = str_replace( "<!--IWLINK $key-->", "<!--IWLINK $newKey-->", $text );
5249 # Should be good to go.
5255 * @todo document, briefly.
5259 var $general, $nowiki;
5261 function __construct() {
5262 $this->general
= new ReplacementArray
;
5263 $this->nowiki
= new ReplacementArray
;
5266 function unstripGeneral( $text ) {
5267 wfProfileIn( __METHOD__
);
5270 $text = $this->general
->replace( $text );
5271 } while ( $text !== $oldText );
5272 wfProfileOut( __METHOD__
);
5276 function unstripNoWiki( $text ) {
5277 wfProfileIn( __METHOD__
);
5280 $text = $this->nowiki
->replace( $text );
5281 } while ( $text !== $oldText );
5282 wfProfileOut( __METHOD__
);
5286 function unstripBoth( $text ) {
5287 wfProfileIn( __METHOD__
);
5290 $text = $this->general
->replace( $text );
5291 $text = $this->nowiki
->replace( $text );
5292 } while ( $text !== $oldText );
5293 wfProfileOut( __METHOD__
);
5299 * @todo document, briefly.
5302 class OnlyIncludeReplacer
{
5305 function replace( $matches ) {
5306 if ( substr( $matches[1], -1 ) === "\n" ) {
5307 $this->output
.= substr( $matches[1], 0, -1 );
5309 $this->output
.= $matches[1];