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 ( !( $wgDisableLangConversion
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 );
389 $this->mOutput
->setTitleText( $wgContLang->convert( $this->mOutput
->getTitleText() ) );
393 $text = $this->mStripState
->unstripNoWiki( $text );
395 wfRunHooks( 'ParserBeforeTidy', array( &$this, &$text ) );
397 //!JF Move to its own function
399 $uniq_prefix = $this->mUniqPrefix
;
401 $elements = array_keys( $this->mTransparentTagHooks
);
402 $text = self
::extractTagsAndParams( $elements, $text, $matches, $uniq_prefix );
404 foreach ( $matches as $marker => $data ) {
405 list( $element, $content, $params, $tag ) = $data;
406 $tagName = strtolower( $element );
407 if ( isset( $this->mTransparentTagHooks
[$tagName] ) ) {
408 $output = call_user_func_array( $this->mTransparentTagHooks
[$tagName], array( $content, $params, $this ) );
412 $this->mStripState
->general
->setPair( $marker, $output );
414 $text = $this->mStripState
->unstripGeneral( $text );
416 $text = Sanitizer
::normalizeCharReferences( $text );
418 if ( ( $wgUseTidy && $this->mOptions
->mTidy
) ||
$wgAlwaysUseTidy ) {
419 $text = MWTidy
::tidy( $text );
421 # attempt to sanitize at least some nesting problems
422 # (bug #2702 and quite a few others)
424 # ''Something [http://www.cool.com cool''] -->
425 # <i>Something</i><a href="http://www.cool.com"..><i>cool></i></a>
426 '/(<([bi])>)(<([bi])>)?([^<]*)(<\/?a[^<]*>)([^<]*)(<\/\\4>)?(<\/\\2>)/' =>
427 '\\1\\3\\5\\8\\9\\6\\1\\3\\7\\8\\9',
428 # fix up an anchor inside another anchor, only
429 # at least for a single single nested link (bug 3695)
430 '/(<a[^>]+>)([^<]*)(<a[^>]+>[^<]*)<\/a>(.*)<\/a>/' =>
431 '\\1\\2</a>\\3</a>\\1\\4</a>',
432 # fix div inside inline elements- doBlockLevels won't wrap a line which
433 # contains a div, so fix it up here; replace
434 # div with escaped text
435 '/(<([aib]) [^>]+>)([^<]*)(<div([^>]*)>)(.*)(<\/div>)([^<]*)(<\/\\2>)/' =>
436 '\\1\\3<div\\5>\\6</div>\\8\\9',
437 # remove empty italic or bold tag pairs, some
438 # introduced by rules above
439 '/<([bi])><\/\\1>/' => '',
442 $text = preg_replace(
443 array_keys( $tidyregs ),
444 array_values( $tidyregs ),
447 global $wgExpensiveParserFunctionLimit;
448 if ( $this->mExpensiveFunctionCount
> $wgExpensiveParserFunctionLimit ) {
449 $this->limitationWarn( 'expensive-parserfunction', $this->mExpensiveFunctionCount
, $wgExpensiveParserFunctionLimit );
452 wfRunHooks( 'ParserAfterTidy', array( &$this, &$text ) );
454 # Information on include size limits, for the benefit of users who try to skirt them
455 if ( $this->mOptions
->getEnableLimitReport() ) {
456 $max = $this->mOptions
->getMaxIncludeSize();
457 $PFreport = "Expensive parser function count: {$this->mExpensiveFunctionCount}/$wgExpensiveParserFunctionLimit\n";
459 "NewPP limit report\n" .
460 "Preprocessor node count: {$this->mPPNodeCount}/{$this->mOptions->mMaxPPNodeCount}\n" .
461 "Post-expand include size: {$this->mIncludeSizes['post-expand']}/$max bytes\n" .
462 "Template argument size: {$this->mIncludeSizes['arg']}/$max bytes\n".
464 wfRunHooks( 'ParserLimitReport', array( $this, &$limitReport ) );
465 $text .= "\n<!-- \n$limitReport-->\n";
467 $this->mOutput
->setText( $text );
469 $this->mRevisionId
= $oldRevisionId;
470 $this->mRevisionTimestamp
= $oldRevisionTimestamp;
471 wfProfileOut( $fname );
472 wfProfileOut( __METHOD__
);
474 return $this->mOutput
;
478 * Recursive parser entry point that can be called from an extension tag
481 * If $frame is not provided, then template variables (e.g., {{{1}}}) within $text are not expanded
483 * @param $text String: text extension wants to have parsed
484 * @param PPFrame $frame: The frame to use for expanding any template variables
486 function recursiveTagParse( $text, $frame=false ) {
487 wfProfileIn( __METHOD__
);
488 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
489 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
490 $text = $this->internalParse( $text, false, $frame );
491 wfProfileOut( __METHOD__
);
496 * Expand templates and variables in the text, producing valid, static wikitext.
497 * Also removes comments.
499 function preprocess( $text, $title, $options, $revid = null ) {
500 wfProfileIn( __METHOD__
);
502 $this->setOutputType( self
::OT_PREPROCESS
);
503 $this->mOptions
= $options;
504 $this->setTitle( $title );
505 if ( $revid !== null ) {
506 $this->mRevisionId
= $revid;
508 wfRunHooks( 'ParserBeforeStrip', array( &$this, &$text, &$this->mStripState
) );
509 wfRunHooks( 'ParserAfterStrip', array( &$this, &$text, &$this->mStripState
) );
510 $text = $this->replaceVariables( $text );
511 $text = $this->mStripState
->unstripBoth( $text );
512 wfProfileOut( __METHOD__
);
517 * Process the wikitext for the ?preload= feature. (bug 5210)
519 * <noinclude>, <includeonly> etc. are parsed as for template transclusion,
520 * comments, templates, arguments, tags hooks and parser functions are untouched.
522 public function getPreloadText( $text, $title, $options ) {
523 # Parser (re)initialisation
525 $this->setOutputType( self
::OT_PLAIN
);
526 $this->mOptions
= $options;
527 $this->setTitle( $title );
529 $flags = PPFrame
::NO_ARGS | PPFrame
::NO_TEMPLATES
;
530 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
531 return $this->getPreprocessor()->newFrame()->expand( $dom, $flags );
535 * Get a random string
540 function getRandomString() {
541 return dechex( mt_rand( 0, 0x7fffffff ) ) . dechex( mt_rand( 0, 0x7fffffff ) );
544 function &getTitle() { return $this->mTitle
; }
545 function getOptions() { return $this->mOptions
; }
546 function getRevisionId() { return $this->mRevisionId
; }
547 function getOutput() { return $this->mOutput
; }
548 function nextLinkID() { return $this->mLinkID++
; }
550 function getFunctionLang() {
551 global $wgLang, $wgContLang;
553 $target = $this->mOptions
->getTargetLanguage();
554 if ( $target !== null ) {
557 return $this->mOptions
->getInterfaceMessage() ?
$wgLang : $wgContLang;
562 * Get a preprocessor object
564 function getPreprocessor() {
565 if ( !isset( $this->mPreprocessor
) ) {
566 $class = $this->mPreprocessorClass
;
567 $this->mPreprocessor
= new $class( $this );
569 return $this->mPreprocessor
;
573 * Replaces all occurrences of HTML-style comments and the given tags
574 * in the text with a random marker and returns the next text. The output
575 * parameter $matches will be an associative array filled with data in
577 * 'UNIQ-xxxxx' => array(
580 * array( 'param' => 'x' ),
581 * '<element param="x">tag content</element>' ) )
583 * @param $elements list of element names. Comments are always extracted.
584 * @param $text Source text string.
585 * @param $uniq_prefix
590 function extractTagsAndParams( $elements, $text, &$matches, $uniq_prefix = '' ) {
595 $taglist = implode( '|', $elements );
596 $start = "/<($taglist)(\\s+[^>]*?|\\s*?)(\/?" . ">)|<(!--)/i";
598 while ( $text != '' ) {
599 $p = preg_split( $start, $text, 2, PREG_SPLIT_DELIM_CAPTURE
);
601 if ( count( $p ) < 5 ) {
604 if ( count( $p ) > 5 ) {
618 $marker = "$uniq_prefix-$element-" . sprintf( '%08X', $n++
) . self
::MARKER_SUFFIX
;
619 $stripped .= $marker;
621 if ( $close === '/>' ) {
622 # Empty element tag, <tag />
627 if ( $element === '!--' ) {
630 $end = "/(<\\/$element\\s*>)/i";
632 $q = preg_split( $end, $inside, 2, PREG_SPLIT_DELIM_CAPTURE
);
634 if ( count( $q ) < 3 ) {
635 # No end tag -- let it run out to the end of the text.
644 $matches[$marker] = array( $element,
646 Sanitizer
::decodeTagAttributes( $attributes ),
647 "<$element$attributes$close$content$tail" );
653 * Get a list of strippable XML-like elements
655 function getStripList() {
656 return $this->mStripList
;
660 * @deprecated use replaceVariables
662 function strip( $text, $state, $stripcomments = false , $dontstrip = array() ) {
667 * Restores pre, math, and other extensions removed by strip()
669 * always call unstripNoWiki() after this one
671 * @deprecated use $this->mStripState->unstrip()
673 function unstrip( $text, $state ) {
674 return $state->unstripGeneral( $text );
678 * Always call this after unstrip() to preserve the order
681 * @deprecated use $this->mStripState->unstrip()
683 function unstripNoWiki( $text, $state ) {
684 return $state->unstripNoWiki( $text );
688 * @deprecated use $this->mStripState->unstripBoth()
690 function unstripForHTML( $text ) {
691 return $this->mStripState
->unstripBoth( $text );
695 * Add an item to the strip state
696 * Returns the unique tag which must be inserted into the stripped text
697 * The tag will be replaced with the original text in unstrip()
701 function insertStripItem( $text ) {
702 $rnd = "{$this->mUniqPrefix}-item-{$this->mMarkerIndex}-" . self
::MARKER_SUFFIX
;
703 $this->mMarkerIndex++
;
704 $this->mStripState
->general
->setPair( $rnd, $text );
709 * Interface with html tidy
710 * @deprecated Use MWTidy::tidy()
712 public static function tidy( $text ) {
713 wfDeprecated( __METHOD__
);
714 return MWTidy
::tidy( $text );
718 * parse the wiki syntax used to render tables
722 function doTableStuff( $text ) {
723 wfProfileIn( __METHOD__
);
725 $lines = StringUtils
::explode( "\n", $text );
727 $td_history = array(); # Is currently a td tag open?
728 $last_tag_history = array(); # Save history of last lag activated (td, th or caption)
729 $tr_history = array(); # Is currently a tr tag open?
730 $tr_attributes = array(); # history of tr attributes
731 $has_opened_tr = array(); # Did this table open a <tr> element?
732 $indent_level = 0; # indent level of the table
734 foreach ( $lines as $outLine ) {
735 $line = trim( $outLine );
737 if ( $line == '' ) { # empty line, go to next line
738 $out .= $outLine."\n";
741 $first_character = $line[0];
744 if ( preg_match( '/^(:*)\{\|(.*)$/', $line , $matches ) ) {
745 # First check if we are starting a new table
746 $indent_level = strlen( $matches[1] );
748 $attributes = $this->mStripState
->unstripBoth( $matches[2] );
749 $attributes = Sanitizer
::fixTagAttributes( $attributes , 'table' );
751 $outLine = str_repeat( '<dl><dd>' , $indent_level ) . "<table{$attributes}>";
752 array_push( $td_history , false );
753 array_push( $last_tag_history , '' );
754 array_push( $tr_history , false );
755 array_push( $tr_attributes , '' );
756 array_push( $has_opened_tr , false );
757 } elseif ( count( $td_history ) == 0 ) {
758 # Don't do any of the following
759 $out .= $outLine."\n";
761 } elseif ( substr( $line , 0 , 2 ) === '|}' ) {
762 # We are ending a table
763 $line = '</table>' . substr( $line , 2 );
764 $last_tag = array_pop( $last_tag_history );
766 if ( !array_pop( $has_opened_tr ) ) {
767 $line = "<tr><td></td></tr>{$line}";
770 if ( array_pop( $tr_history ) ) {
771 $line = "</tr>{$line}";
774 if ( array_pop( $td_history ) ) {
775 $line = "</{$last_tag}>{$line}";
777 array_pop( $tr_attributes );
778 $outLine = $line . str_repeat( '</dd></dl>' , $indent_level );
779 } elseif ( substr( $line , 0 , 2 ) === '|-' ) {
780 # Now we have a table row
781 $line = preg_replace( '#^\|-+#', '', $line );
783 # Whats after the tag is now only attributes
784 $attributes = $this->mStripState
->unstripBoth( $line );
785 $attributes = Sanitizer
::fixTagAttributes( $attributes, 'tr' );
786 array_pop( $tr_attributes );
787 array_push( $tr_attributes, $attributes );
790 $last_tag = array_pop( $last_tag_history );
791 array_pop( $has_opened_tr );
792 array_push( $has_opened_tr , true );
794 if ( array_pop( $tr_history ) ) {
798 if ( array_pop( $td_history ) ) {
799 $line = "</{$last_tag}>{$line}";
803 array_push( $tr_history , false );
804 array_push( $td_history , false );
805 array_push( $last_tag_history , '' );
806 } elseif ( $first_character === '|' ||
$first_character === '!' ||
substr( $line , 0 , 2 ) === '|+' ) {
807 # This might be cell elements, td, th or captions
808 if ( substr( $line , 0 , 2 ) === '|+' ) {
809 $first_character = '+';
810 $line = substr( $line , 1 );
813 $line = substr( $line , 1 );
815 if ( $first_character === '!' ) {
816 $line = str_replace( '!!' , '||' , $line );
819 # Split up multiple cells on the same line.
820 # FIXME : This can result in improper nesting of tags processed
821 # by earlier parser steps, but should avoid splitting up eg
822 # attribute values containing literal "||".
823 $cells = StringUtils
::explodeMarkup( '||' , $line );
827 # Loop through each table cell
828 foreach ( $cells as $cell ) {
830 if ( $first_character !== '+' ) {
831 $tr_after = array_pop( $tr_attributes );
832 if ( !array_pop( $tr_history ) ) {
833 $previous = "<tr{$tr_after}>\n";
835 array_push( $tr_history , true );
836 array_push( $tr_attributes , '' );
837 array_pop( $has_opened_tr );
838 array_push( $has_opened_tr , true );
841 $last_tag = array_pop( $last_tag_history );
843 if ( array_pop( $td_history ) ) {
844 $previous = "</{$last_tag}>{$previous}";
847 if ( $first_character === '|' ) {
849 } elseif ( $first_character === '!' ) {
851 } elseif ( $first_character === '+' ) {
852 $last_tag = 'caption';
857 array_push( $last_tag_history , $last_tag );
859 # A cell could contain both parameters and data
860 $cell_data = explode( '|' , $cell , 2 );
862 # Bug 553: Note that a '|' inside an invalid link should not
863 # be mistaken as delimiting cell parameters
864 if ( strpos( $cell_data[0], '[[' ) !== false ) {
865 $cell = "{$previous}<{$last_tag}>{$cell}";
866 } elseif ( count( $cell_data ) == 1 ) {
867 $cell = "{$previous}<{$last_tag}>{$cell_data[0]}";
869 $attributes = $this->mStripState
->unstripBoth( $cell_data[0] );
870 $attributes = Sanitizer
::fixTagAttributes( $attributes , $last_tag );
871 $cell = "{$previous}<{$last_tag}{$attributes}>{$cell_data[1]}";
875 array_push( $td_history , true );
878 $out .= $outLine . "\n";
881 # Closing open td, tr && table
882 while ( count( $td_history ) > 0 ) {
883 if ( array_pop( $td_history ) ) {
886 if ( array_pop( $tr_history ) ) {
889 if ( !array_pop( $has_opened_tr ) ) {
890 $out .= "<tr><td></td></tr>\n" ;
893 $out .= "</table>\n";
896 # Remove trailing line-ending (b/c)
897 if ( substr( $out, -1 ) === "\n" ) {
898 $out = substr( $out, 0, -1 );
901 # special case: don't return empty table
902 if ( $out === "<table>\n<tr><td></td></tr>\n</table>" ) {
906 wfProfileOut( __METHOD__
);
912 * Helper function for parse() that transforms wiki markup into
913 * HTML. Only called for $mOutputType == self::OT_HTML.
917 function internalParse( $text, $isMain = true, $frame=false ) {
918 wfProfileIn( __METHOD__
);
922 # Hook to suspend the parser in this state
923 if ( !wfRunHooks( 'ParserBeforeInternalParse', array( &$this, &$text, &$this->mStripState
) ) ) {
924 wfProfileOut( __METHOD__
);
928 # if $frame is provided, then use $frame for replacing any variables
930 # use frame depth to infer how include/noinclude tags should be handled
931 # depth=0 means this is the top-level document; otherwise it's an included document
932 if ( !$frame->depth
) {
935 $flag = Parser
::PTD_FOR_INCLUSION
;
936 $dom = $this->preprocessToDom( $text, $flag );
937 $text = $frame->expand( $dom );
940 # if $frame is not provided, then use old-style replaceVariables
941 $text = $this->replaceVariables( $text );
944 $text = Sanitizer
::removeHTMLtags( $text, array( &$this, 'attributeStripCallback' ), false, array_keys( $this->mTransparentTagHooks
) );
945 wfRunHooks( 'InternalParseBeforeLinks', array( &$this, &$text, &$this->mStripState
) );
947 # Tables need to come after variable replacement for things to work
948 # properly; putting them before other transformations should keep
949 # exciting things like link expansions from showing up in surprising
951 $text = $this->doTableStuff( $text );
953 $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text );
955 $text = $this->doDoubleUnderscore( $text );
957 $text = $this->doHeadings( $text );
958 if ( $this->mOptions
->getUseDynamicDates() ) {
959 $df = DateFormatter
::getInstance();
960 $text = $df->reformat( $this->mOptions
->getDateFormat(), $text );
962 $text = $this->doAllQuotes( $text );
963 $text = $this->replaceInternalLinks( $text );
964 $text = $this->replaceExternalLinks( $text );
966 # replaceInternalLinks may sometimes leave behind
967 # absolute URLs, which have to be masked to hide them from replaceExternalLinks
968 $text = str_replace( $this->mUniqPrefix
.'NOPARSE', '', $text );
970 $text = $this->doMagicLinks( $text );
971 $text = $this->formatHeadings( $text, $origText, $isMain );
973 wfProfileOut( __METHOD__
);
978 * Replace special strings like "ISBN xxx" and "RFC xxx" with
979 * magic external links.
984 function doMagicLinks( $text ) {
985 wfProfileIn( __METHOD__
);
986 $prots = $this->mUrlProtocols
;
987 $urlChar = self
::EXT_LINK_URL_CLASS
;
988 $text = preg_replace_callback(
990 (<a[ \t\r\n>].*?</a>) | # m[1]: Skip link text
991 (<.*?>) | # m[2]: Skip stuff inside HTML elements' . "
992 (\\b(?:$prots)$urlChar+) | # m[3]: Free external links" . '
993 (?:RFC|PMID)\s+([0-9]+) | # m[4]: RFC or PMID, capture number
994 ISBN\s+(\b # m[5]: ISBN, capture number
995 (?: 97[89] [\ \-]? )? # optional 13-digit ISBN prefix
996 (?: [0-9] [\ \-]? ){9} # 9 digits with opt. delimiters
997 [0-9Xx] # check digit
999 )!x', array( &$this, 'magicLinkCallback' ), $text );
1000 wfProfileOut( __METHOD__
);
1004 function magicLinkCallback( $m ) {
1005 if ( isset( $m[1] ) && $m[1] !== '' ) {
1008 } elseif ( isset( $m[2] ) && $m[2] !== '' ) {
1011 } elseif ( isset( $m[3] ) && $m[3] !== '' ) {
1012 # Free external link
1013 return $this->makeFreeExternalLink( $m[0] );
1014 } elseif ( isset( $m[4] ) && $m[4] !== '' ) {
1017 if ( substr( $m[0], 0, 3 ) === 'RFC' ) {
1020 $CssClass = 'mw-magiclink-rfc';
1022 } elseif ( substr( $m[0], 0, 4 ) === 'PMID' ) {
1024 $urlmsg = 'pubmedurl';
1025 $CssClass = 'mw-magiclink-pmid';
1028 throw new MWException( __METHOD__
.': unrecognised match type "' .
1029 substr( $m[0], 0, 20 ) . '"' );
1031 $url = wfMsg( $urlmsg, $id);
1032 $sk = $this->mOptions
->getSkin();
1033 $la = $sk->getExternalLinkAttributes( "external $CssClass" );
1034 return "<a href=\"{$url}\"{$la}>{$keyword} {$id}</a>";
1035 } elseif ( isset( $m[5] ) && $m[5] !== '' ) {
1038 $num = strtr( $isbn, array(
1043 $titleObj = SpecialPage
::getTitleFor( 'Booksources', $num );
1045 $titleObj->escapeLocalUrl() .
1046 "\" class=\"internal mw-magiclink-isbn\">ISBN $isbn</a>";
1053 * Make a free external link, given a user-supplied URL
1057 function makeFreeExternalLink( $url ) {
1059 wfProfileIn( __METHOD__
);
1061 $sk = $this->mOptions
->getSkin();
1064 # The characters '<' and '>' (which were escaped by
1065 # removeHTMLtags()) should not be included in
1066 # URLs, per RFC 2396.
1068 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1069 $trail = substr( $url, $m2[0][1] ) . $trail;
1070 $url = substr( $url, 0, $m2[0][1] );
1073 # Move trailing punctuation to $trail
1075 # If there is no left bracket, then consider right brackets fair game too
1076 if ( strpos( $url, '(' ) === false ) {
1080 $numSepChars = strspn( strrev( $url ), $sep );
1081 if ( $numSepChars ) {
1082 $trail = substr( $url, -$numSepChars ) . $trail;
1083 $url = substr( $url, 0, -$numSepChars );
1086 $url = Sanitizer
::cleanUrl( $url );
1088 # Is this an external image?
1089 $text = $this->maybeMakeExternalImage( $url );
1090 if ( $text === false ) {
1091 # Not an image, make a link
1092 $text = $sk->makeExternalLink( $url, $wgContLang->markNoConversion($url), true, 'free',
1093 $this->getExternalLinkAttribs( $url ) );
1094 # Register it in the output object...
1095 # Replace unnecessary URL escape codes with their equivalent characters
1096 $pasteurized = self
::replaceUnusualEscapes( $url );
1097 $this->mOutput
->addExternalLink( $pasteurized );
1099 wfProfileOut( __METHOD__
);
1100 return $text . $trail;
1105 * Parse headers and return html
1109 function doHeadings( $text ) {
1110 wfProfileIn( __METHOD__
);
1111 for ( $i = 6; $i >= 1; --$i ) {
1112 $h = str_repeat( '=', $i );
1113 $text = preg_replace( "/^$h(.+)$h\\s*$/m",
1114 "<h$i>\\1</h$i>", $text );
1116 wfProfileOut( __METHOD__
);
1121 * Replace single quotes with HTML markup
1123 * @return string the altered text
1125 function doAllQuotes( $text ) {
1126 wfProfileIn( __METHOD__
);
1128 $lines = StringUtils
::explode( "\n", $text );
1129 foreach ( $lines as $line ) {
1130 $outtext .= $this->doQuotes( $line ) . "\n";
1132 $outtext = substr( $outtext, 0,-1 );
1133 wfProfileOut( __METHOD__
);
1138 * Helper function for doAllQuotes()
1140 public function doQuotes( $text ) {
1141 $arr = preg_split( "/(''+)/", $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1142 if ( count( $arr ) == 1 ) {
1145 # First, do some preliminary work. This may shift some apostrophes from
1146 # being mark-up to being text. It also counts the number of occurrences
1147 # of bold and italics mark-ups.
1151 foreach ( $arr as $r ) {
1152 if ( ( $i %
2 ) == 1 ) {
1153 # If there are ever four apostrophes, assume the first is supposed to
1154 # be text, and the remaining three constitute mark-up for bold text.
1155 if ( strlen( $arr[$i] ) == 4 ) {
1158 } elseif ( strlen( $arr[$i] ) > 5 ) {
1159 # If there are more than 5 apostrophes in a row, assume they're all
1160 # text except for the last 5.
1161 $arr[$i-1] .= str_repeat( "'", strlen( $arr[$i] ) - 5 );
1164 # Count the number of occurrences of bold and italics mark-ups.
1165 # We are not counting sequences of five apostrophes.
1166 if ( strlen( $arr[$i] ) == 2 ) {
1168 } elseif ( strlen( $arr[$i] ) == 3 ) {
1170 } elseif ( strlen( $arr[$i] ) == 5 ) {
1178 # If there is an odd number of both bold and italics, it is likely
1179 # that one of the bold ones was meant to be an apostrophe followed
1180 # by italics. Which one we cannot know for certain, but it is more
1181 # likely to be one that has a single-letter word before it.
1182 if ( ( $numbold %
2 == 1 ) && ( $numitalics %
2 == 1 ) ) {
1184 $firstsingleletterword = -1;
1185 $firstmultiletterword = -1;
1187 foreach ( $arr as $r ) {
1188 if ( ( $i %
2 == 1 ) and ( strlen( $r ) == 3 ) ) {
1189 $x1 = substr( $arr[$i-1], -1 );
1190 $x2 = substr( $arr[$i-1], -2, 1 );
1191 if ( $x1 === ' ' ) {
1192 if ( $firstspace == -1 ) {
1195 } elseif ( $x2 === ' ') {
1196 if ( $firstsingleletterword == -1 ) {
1197 $firstsingleletterword = $i;
1200 if ( $firstmultiletterword == -1 ) {
1201 $firstmultiletterword = $i;
1208 # If there is a single-letter word, use it!
1209 if ( $firstsingleletterword > -1 ) {
1210 $arr[$firstsingleletterword] = "''";
1211 $arr[$firstsingleletterword-1] .= "'";
1212 } elseif ( $firstmultiletterword > -1 ) {
1213 # If not, but there's a multi-letter word, use that one.
1214 $arr[$firstmultiletterword] = "''";
1215 $arr[$firstmultiletterword-1] .= "'";
1216 } elseif ( $firstspace > -1 ) {
1217 # ... otherwise use the first one that has neither.
1218 # (notice that it is possible for all three to be -1 if, for example,
1219 # there is only one pentuple-apostrophe in the line)
1220 $arr[$firstspace] = "''";
1221 $arr[$firstspace-1] .= "'";
1225 # Now let's actually convert our apostrophic mush to HTML!
1230 foreach ( $arr as $r ) {
1231 if ( ( $i %
2 ) == 0 ) {
1232 if ( $state === 'both' ) {
1238 if ( strlen( $r ) == 2 ) {
1239 if ( $state === 'i' ) {
1240 $output .= '</i>'; $state = '';
1241 } elseif ( $state === 'bi' ) {
1242 $output .= '</i>'; $state = 'b';
1243 } elseif ( $state === 'ib' ) {
1244 $output .= '</b></i><b>'; $state = 'b';
1245 } elseif ( $state === 'both' ) {
1246 $output .= '<b><i>'.$buffer.'</i>'; $state = 'b';
1247 } else { # $state can be 'b' or ''
1248 $output .= '<i>'; $state .= 'i';
1250 } elseif ( strlen( $r ) == 3 ) {
1251 if ( $state === 'b' ) {
1252 $output .= '</b>'; $state = '';
1253 } elseif ( $state === 'bi' ) {
1254 $output .= '</i></b><i>'; $state = 'i';
1255 } elseif ( $state === 'ib' ) {
1256 $output .= '</b>'; $state = 'i';
1257 } elseif ( $state === 'both' ) {
1258 $output .= '<i><b>'.$buffer.'</b>'; $state = 'i';
1259 } else { # $state can be 'i' or ''
1260 $output .= '<b>'; $state .= 'b';
1262 } elseif ( strlen( $r ) == 5 ) {
1263 if ( $state === 'b' ) {
1264 $output .= '</b><i>'; $state = 'i';
1265 } elseif ( $state === 'i' ) {
1266 $output .= '</i><b>'; $state = 'b';
1267 } elseif ( $state === 'bi' ) {
1268 $output .= '</i></b>'; $state = '';
1269 } elseif ( $state === 'ib' ) {
1270 $output .= '</b></i>'; $state = '';
1271 } elseif ( $state === 'both' ) {
1272 $output .= '<i><b>'.$buffer.'</b></i>'; $state = '';
1273 } else { # ($state == '')
1274 $buffer = ''; $state = 'both';
1280 # Now close all remaining tags. Notice that the order is important.
1281 if ( $state === 'b' ||
$state === 'ib' ) {
1284 if ( $state === 'i' ||
$state === 'bi' ||
$state === 'ib' ) {
1287 if ( $state === 'bi' ) {
1290 # There might be lonely ''''', so make sure we have a buffer
1291 if ( $state === 'both' && $buffer ) {
1292 $output .= '<b><i>'.$buffer.'</i></b>';
1299 * Replace external links (REL)
1301 * Note: this is all very hackish and the order of execution matters a lot.
1302 * Make sure to run maintenance/parserTests.php if you change this code.
1306 function replaceExternalLinks( $text ) {
1308 wfProfileIn( __METHOD__
);
1310 $sk = $this->mOptions
->getSkin();
1312 $bits = preg_split( $this->mExtLinkBracketedRegex
, $text, -1, PREG_SPLIT_DELIM_CAPTURE
);
1313 $s = array_shift( $bits );
1316 while ( $i<count( $bits ) ) {
1318 $protocol = $bits[$i++
];
1319 $text = $bits[$i++
];
1320 $trail = $bits[$i++
];
1322 # The characters '<' and '>' (which were escaped by
1323 # removeHTMLtags()) should not be included in
1324 # URLs, per RFC 2396.
1326 if ( preg_match( '/&(lt|gt);/', $url, $m2, PREG_OFFSET_CAPTURE
) ) {
1327 $text = substr( $url, $m2[0][1] ) . ' ' . $text;
1328 $url = substr( $url, 0, $m2[0][1] );
1331 # If the link text is an image URL, replace it with an <img> tag
1332 # This happened by accident in the original parser, but some people used it extensively
1333 $img = $this->maybeMakeExternalImage( $text );
1334 if ( $img !== false ) {
1340 # Set linktype for CSS - if URL==text, link is essentially free
1341 $linktype = ( $text === $url ) ?
'free' : 'text';
1343 # No link text, e.g. [http://domain.tld/some.link]
1344 if ( $text == '' ) {
1345 # Autonumber if allowed. See bug #5918
1346 if ( strpos( wfUrlProtocols(), substr( $protocol, 0, strpos( $protocol, ':' ) ) ) !== false ) {
1347 $langObj = $this->getFunctionLang();
1348 $text = '[' . $langObj->formatNum( ++
$this->mAutonumber
) . ']';
1349 $linktype = 'autonumber';
1351 # Otherwise just use the URL
1352 $text = htmlspecialchars( $url );
1356 # Have link text, e.g. [http://domain.tld/some.link text]s
1358 list( $dtrail, $trail ) = Linker
::splitTrail( $trail );
1361 $text = $wgContLang->markNoConversion( $text );
1363 $url = Sanitizer
::cleanUrl( $url );
1365 # Use the encoded URL
1366 # This means that users can paste URLs directly into the text
1367 # Funny characters like ö aren't valid in URLs anyway
1368 # This was changed in August 2004
1369 $s .= $sk->makeExternalLink( $url, $text, false, $linktype,
1370 $this->getExternalLinkAttribs( $url ) ) . $dtrail . $trail;
1372 # Register link in the output object.
1373 # Replace unnecessary URL escape codes with the referenced character
1374 # This prevents spammers from hiding links from the filters
1375 $pasteurized = self
::replaceUnusualEscapes( $url );
1376 $this->mOutput
->addExternalLink( $pasteurized );
1379 wfProfileOut( __METHOD__
);
1384 * Get an associative array of additional HTML attributes appropriate for a
1385 * particular external link. This currently may include rel => nofollow
1386 * (depending on configuration, namespace, and the URL's domain) and/or a
1387 * target attribute (depending on configuration).
1389 * @param string $url Optional URL, to extract the domain from for rel =>
1390 * nofollow if appropriate
1391 * @return array Associative array of HTML attributes
1393 function getExternalLinkAttribs( $url = false ) {
1395 global $wgNoFollowLinks, $wgNoFollowNsExceptions;
1396 $ns = $this->mTitle
->getNamespace();
1397 if ( $wgNoFollowLinks && !in_array( $ns, $wgNoFollowNsExceptions ) ) {
1398 $attribs['rel'] = 'nofollow';
1400 global $wgNoFollowDomainExceptions;
1401 if ( $wgNoFollowDomainExceptions ) {
1402 $bits = wfParseUrl( $url );
1403 if ( is_array( $bits ) && isset( $bits['host'] ) ) {
1404 foreach ( $wgNoFollowDomainExceptions as $domain ) {
1405 if ( substr( $bits['host'], -strlen( $domain ) ) == $domain ) {
1406 unset( $attribs['rel'] );
1413 if ( $this->mOptions
->getExternalLinkTarget() ) {
1414 $attribs['target'] = $this->mOptions
->getExternalLinkTarget();
1421 * Replace unusual URL escape codes with their equivalent characters
1425 * @todo This can merge genuinely required bits in the path or query string,
1426 * breaking legit URLs. A proper fix would treat the various parts of
1427 * the URL differently; as a workaround, just use the output for
1428 * statistical records, not for actual linking/output.
1430 static function replaceUnusualEscapes( $url ) {
1431 return preg_replace_callback( '/%[0-9A-Fa-f]{2}/',
1432 array( __CLASS__
, 'replaceUnusualEscapesCallback' ), $url );
1436 * Callback function used in replaceUnusualEscapes().
1437 * Replaces unusual URL escape codes with their equivalent character
1441 private static function replaceUnusualEscapesCallback( $matches ) {
1442 $char = urldecode( $matches[0] );
1443 $ord = ord( $char );
1444 # Is it an unsafe or HTTP reserved character according to RFC 1738?
1445 if ( $ord > 32 && $ord < 127 && strpos( '<>"#{}|\^~[]`;/?', $char ) === false ) {
1446 # No, shouldn't be escaped
1449 # Yes, leave it escaped
1455 * make an image if it's allowed, either through the global
1456 * option, through the exception, or through the on-wiki whitelist
1459 function maybeMakeExternalImage( $url ) {
1460 $sk = $this->mOptions
->getSkin();
1461 $imagesfrom = $this->mOptions
->getAllowExternalImagesFrom();
1462 $imagesexception = !empty( $imagesfrom );
1464 # $imagesfrom could be either a single string or an array of strings, parse out the latter
1465 if ( $imagesexception && is_array( $imagesfrom ) ) {
1466 $imagematch = false;
1467 foreach ( $imagesfrom as $match ) {
1468 if ( strpos( $url, $match ) === 0 ) {
1473 } elseif ( $imagesexception ) {
1474 $imagematch = ( strpos( $url, $imagesfrom ) === 0 );
1476 $imagematch = false;
1478 if ( $this->mOptions
->getAllowExternalImages()
1479 ||
( $imagesexception && $imagematch ) ) {
1480 if ( preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1482 $text = $sk->makeExternalImage( $url );
1485 if ( !$text && $this->mOptions
->getEnableImageWhitelist()
1486 && preg_match( self
::EXT_IMAGE_REGEX
, $url ) ) {
1487 $whitelist = explode( "\n", wfMsgForContent( 'external_image_whitelist' ) );
1488 foreach ( $whitelist as $entry ) {
1489 # Sanitize the regex fragment, make it case-insensitive, ignore blank entries/comments
1490 if ( strpos( $entry, '#' ) === 0 ||
$entry === '' ) {
1493 if ( preg_match( '/' . str_replace( '/', '\\/', $entry ) . '/i', $url ) ) {
1494 # Image matches a whitelist entry
1495 $text = $sk->makeExternalImage( $url );
1504 * Process [[ ]] wikilinks
1505 * @return processed text
1509 function replaceInternalLinks( $s ) {
1510 $this->mLinkHolders
->merge( $this->replaceInternalLinks2( $s ) );
1515 * Process [[ ]] wikilinks (RIL)
1516 * @return LinkHolderArray
1520 function replaceInternalLinks2( &$s ) {
1523 wfProfileIn( __METHOD__
);
1525 wfProfileIn( __METHOD__
.'-setup' );
1526 static $tc = FALSE, $e1, $e1_img;
1527 # the % is needed to support urlencoded titles as well
1529 $tc = Title
::legalChars() . '#%';
1530 # Match a link having the form [[namespace:link|alternate]]trail
1531 $e1 = "/^([{$tc}]+)(?:\\|(.+?))?]](.*)\$/sD";
1532 # Match cases where there is no "]]", which might still be images
1533 $e1_img = "/^([{$tc}]+)\\|(.*)\$/sD";
1536 $sk = $this->mOptions
->getSkin();
1537 $holders = new LinkHolderArray( $this );
1539 # split the entire text string on occurences of [[
1540 $a = StringUtils
::explode( '[[', ' ' . $s );
1541 # get the first element (all text up to first [[), and remove the space we added
1544 $line = $a->current(); # Workaround for broken ArrayIterator::next() that returns "void"
1545 $s = substr( $s, 1 );
1547 $useLinkPrefixExtension = $wgContLang->linkPrefixExtension();
1549 if ( $useLinkPrefixExtension ) {
1550 # Match the end of a line for a word that's not followed by whitespace,
1551 # e.g. in the case of 'The Arab al[[Razi]]', 'al' will be matched
1552 $e2 = wfMsgForContent( 'linkprefix' );
1555 if ( is_null( $this->mTitle
) ) {
1556 wfProfileOut( __METHOD__
.'-setup' );
1557 wfProfileOut( __METHOD__
);
1558 throw new MWException( __METHOD__
.": \$this->mTitle is null\n" );
1560 $nottalk = !$this->mTitle
->isTalkPage();
1562 if ( $useLinkPrefixExtension ) {
1564 if ( preg_match( $e2, $s, $m ) ) {
1565 $first_prefix = $m[2];
1567 $first_prefix = false;
1573 if ( $wgContLang->hasVariants() ) {
1574 $selflink = $wgContLang->convertLinkToAllVariants( $this->mTitle
->getPrefixedText() );
1576 $selflink = array( $this->mTitle
->getPrefixedText() );
1578 $useSubpages = $this->areSubpagesAllowed();
1579 wfProfileOut( __METHOD__
.'-setup' );
1581 # Loop for each link
1582 for ( ; $line !== false && $line !== null ; $a->next(), $line = $a->current() ) {
1583 # Check for excessive memory usage
1584 if ( $holders->isBig() ) {
1586 # Do the existence check, replace the link holders and clear the array
1587 $holders->replace( $s );
1591 if ( $useLinkPrefixExtension ) {
1592 wfProfileIn( __METHOD__
.'-prefixhandling' );
1593 if ( preg_match( $e2, $s, $m ) ) {
1600 if ( $first_prefix ) {
1601 $prefix = $first_prefix;
1602 $first_prefix = false;
1604 wfProfileOut( __METHOD__
.'-prefixhandling' );
1607 $might_be_img = false;
1609 wfProfileIn( __METHOD__
."-e1" );
1610 if ( preg_match( $e1, $line, $m ) ) { # page with normal text or alt
1612 # If we get a ] at the beginning of $m[3] that means we have a link that's something like:
1613 # [[Image:Foo.jpg|[http://example.com desc]]] <- having three ] in a row fucks up,
1614 # the real problem is with the $e1 regex
1617 # Still some problems for cases where the ] is meant to be outside punctuation,
1618 # and no image is in sight. See bug 2095.
1620 if ( $text !== '' &&
1621 substr( $m[3], 0, 1 ) === ']' &&
1622 strpos( $text, '[' ) !== false
1625 $text .= ']'; # so that replaceExternalLinks($text) works later
1626 $m[3] = substr( $m[3], 1 );
1628 # fix up urlencoded title texts
1629 if ( strpos( $m[1], '%' ) !== false ) {
1630 # Should anchors '#' also be rejected?
1631 $m[1] = str_replace( array('<', '>'), array('<', '>'), urldecode( $m[1] ) );
1634 } elseif ( preg_match( $e1_img, $line, $m ) ) { # Invalid, but might be an image with a link in its caption
1635 $might_be_img = true;
1637 if ( strpos( $m[1], '%' ) !== false ) {
1638 $m[1] = urldecode( $m[1] );
1641 } else { # Invalid form; output directly
1642 $s .= $prefix . '[[' . $line ;
1643 wfProfileOut( __METHOD__
."-e1" );
1646 wfProfileOut( __METHOD__
."-e1" );
1647 wfProfileIn( __METHOD__
."-misc" );
1649 # Don't allow internal links to pages containing
1650 # PROTO: where PROTO is a valid URL protocol; these
1651 # should be external links.
1652 if ( preg_match( '/^\b(?:' . wfUrlProtocols() . ')/', $m[1] ) ) {
1653 $s .= $prefix . '[[' . $line ;
1654 wfProfileOut( __METHOD__
."-misc" );
1658 # Make subpage if necessary
1659 if ( $useSubpages ) {
1660 $link = $this->maybeDoSubpageLink( $m[1], $text );
1665 $noforce = ( substr( $m[1], 0, 1 ) !== ':' );
1667 # Strip off leading ':'
1668 $link = substr( $link, 1 );
1671 wfProfileOut( __METHOD__
."-misc" );
1672 wfProfileIn( __METHOD__
."-title" );
1673 $nt = Title
::newFromText( $this->mStripState
->unstripNoWiki( $link ) );
1674 if ( $nt === null ) {
1675 $s .= $prefix . '[[' . $line;
1676 wfProfileOut( __METHOD__
."-title" );
1680 $ns = $nt->getNamespace();
1681 $iw = $nt->getInterWiki();
1682 wfProfileOut( __METHOD__
."-title" );
1684 if ( $might_be_img ) { # if this is actually an invalid link
1685 wfProfileIn( __METHOD__
."-might_be_img" );
1686 if ( $ns == NS_FILE
&& $noforce ) { # but might be an image
1689 # look at the next 'line' to see if we can close it there
1691 $next_line = $a->current();
1692 if ( $next_line === false ||
$next_line === null ) {
1695 $m = explode( ']]', $next_line, 3 );
1696 if ( count( $m ) == 3 ) {
1697 # the first ]] closes the inner link, the second the image
1699 $text .= "[[{$m[0]}]]{$m[1]}";
1702 } elseif ( count( $m ) == 2 ) {
1703 # if there's exactly one ]] that's fine, we'll keep looking
1704 $text .= "[[{$m[0]}]]{$m[1]}";
1706 # if $next_line is invalid too, we need look no further
1707 $text .= '[[' . $next_line;
1712 # we couldn't find the end of this imageLink, so output it raw
1713 # but don't ignore what might be perfectly normal links in the text we've examined
1714 $holders->merge( $this->replaceInternalLinks2( $text ) );
1715 $s .= "{$prefix}[[$link|$text";
1716 # note: no $trail, because without an end, there *is* no trail
1717 wfProfileOut( __METHOD__
."-might_be_img" );
1720 } else { # it's not an image, so output it raw
1721 $s .= "{$prefix}[[$link|$text";
1722 # note: no $trail, because without an end, there *is* no trail
1723 wfProfileOut( __METHOD__
."-might_be_img" );
1726 wfProfileOut( __METHOD__
."-might_be_img" );
1729 $wasblank = ( $text == '' );
1734 # Link not escaped by : , create the various objects
1738 wfProfileIn( __METHOD__
."-interwiki" );
1739 if ( $iw && $this->mOptions
->getInterwikiMagic() && $nottalk && $wgContLang->getLanguageName( $iw ) ) {
1740 $this->mOutput
->addLanguageLink( $nt->getFullText() );
1741 $s = rtrim( $s . $prefix );
1742 $s .= trim( $trail, "\n" ) == '' ?
'': $prefix . $trail;
1743 wfProfileOut( __METHOD__
."-interwiki" );
1746 wfProfileOut( __METHOD__
."-interwiki" );
1748 if ( $ns == NS_FILE
) {
1749 wfProfileIn( __METHOD__
."-image" );
1750 if ( !wfIsBadImage( $nt->getDBkey(), $this->mTitle
) ) {
1752 # if no parameters were passed, $text
1753 # becomes something like "File:Foo.png",
1754 # which we don't want to pass on to the
1758 # recursively parse links inside the image caption
1759 # actually, this will parse them in any other parameters, too,
1760 # but it might be hard to fix that, and it doesn't matter ATM
1761 $text = $this->replaceExternalLinks( $text );
1762 $holders->merge( $this->replaceInternalLinks2( $text ) );
1764 # cloak any absolute URLs inside the image markup, so replaceExternalLinks() won't touch them
1765 $s .= $prefix . $this->armorLinks( $this->makeImage( $nt, $text, $holders ) ) . $trail;
1767 $s .= $prefix . $trail;
1769 $this->mOutput
->addImage( $nt->getDBkey() );
1770 wfProfileOut( __METHOD__
."-image" );
1775 if ( $ns == NS_CATEGORY
) {
1776 wfProfileIn( __METHOD__
."-category" );
1777 $s = rtrim( $s . "\n" ); # bug 87
1780 $sortkey = $this->getDefaultSort();
1784 $sortkey = Sanitizer
::decodeCharReferences( $sortkey );
1785 $sortkey = str_replace( "\n", '', $sortkey );
1786 $sortkey = $wgContLang->convertCategoryKey( $sortkey );
1787 $this->mOutput
->addCategory( $nt->getDBkey(), $sortkey );
1790 * Strip the whitespace Category links produce, see bug 87
1791 * @todo We might want to use trim($tmp, "\n") here.
1793 $s .= trim( $prefix . $trail, "\n" ) == '' ?
'': $prefix . $trail;
1795 wfProfileOut( __METHOD__
."-category" );
1800 # Self-link checking
1801 if ( $nt->getFragment() === '' && $ns != NS_SPECIAL
) {
1802 if ( in_array( $nt->getPrefixedText(), $selflink, true ) ) {
1803 $s .= $prefix . $sk->makeSelfLinkObj( $nt, $text, '', $trail );
1808 # NS_MEDIA is a pseudo-namespace for linking directly to a file
1809 # FIXME: Should do batch file existence checks, see comment below
1810 if ( $ns == NS_MEDIA
) {
1811 wfProfileIn( __METHOD__
."-media" );
1812 # Give extensions a chance to select the file revision for us
1813 $skip = $time = false;
1814 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$nt, &$skip, &$time ) );
1816 $link = $sk->link( $nt );
1818 $link = $sk->makeMediaLinkObj( $nt, $text, $time );
1820 # Cloak with NOPARSE to avoid replacement in replaceExternalLinks
1821 $s .= $prefix . $this->armorLinks( $link ) . $trail;
1822 $this->mOutput
->addImage( $nt->getDBkey() );
1823 wfProfileOut( __METHOD__
."-media" );
1827 wfProfileIn( __METHOD__
."-always_known" );
1828 # Some titles, such as valid special pages or files in foreign repos, should
1829 # be shown as bluelinks even though they're not included in the page table
1831 # FIXME: isAlwaysKnown() can be expensive for file links; we should really do
1832 # batch file existence checks for NS_FILE and NS_MEDIA
1833 if ( $iw == '' && $nt->isAlwaysKnown() ) {
1834 $this->mOutput
->addLink( $nt );
1835 $s .= $this->makeKnownLinkHolder( $nt, $text, '', $trail, $prefix );
1837 # Links will be added to the output link list after checking
1838 $s .= $holders->makeHolder( $nt, $text, '', $trail, $prefix );
1840 wfProfileOut( __METHOD__
."-always_known" );
1842 wfProfileOut( __METHOD__
);
1847 * Make a link placeholder. The text returned can be later resolved to a real link with
1848 * replaceLinkHolders(). This is done for two reasons: firstly to avoid further
1849 * parsing of interwiki links, and secondly to allow all existence checks and
1850 * article length checks (for stub links) to be bundled into a single query.
1854 function makeLinkHolder( &$nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1855 return $this->mLinkHolders
->makeHolder( $nt, $text, $query, $trail, $prefix );
1859 * Render a forced-blue link inline; protect against double expansion of
1860 * URLs if we're in a mode that prepends full URL prefixes to internal links.
1861 * Since this little disaster has to split off the trail text to avoid
1862 * breaking URLs in the following text without breaking trails on the
1863 * wiki links, it's been made into a horrible function.
1866 * @param string $text
1867 * @param string $query
1868 * @param string $trail
1869 * @param string $prefix
1870 * @return string HTML-wikitext mix oh yuck
1872 function makeKnownLinkHolder( $nt, $text = '', $query = '', $trail = '', $prefix = '' ) {
1873 list( $inside, $trail ) = Linker
::splitTrail( $trail );
1874 $sk = $this->mOptions
->getSkin();
1875 # FIXME: use link() instead of deprecated makeKnownLinkObj()
1876 $link = $sk->makeKnownLinkObj( $nt, $text, $query, $inside, $prefix );
1877 return $this->armorLinks( $link ) . $trail;
1881 * Insert a NOPARSE hacky thing into any inline links in a chunk that's
1882 * going to go through further parsing steps before inline URL expansion.
1884 * Not needed quite as much as it used to be since free links are a bit
1885 * more sensible these days. But bracketed links are still an issue.
1887 * @param string more-or-less HTML
1888 * @return string less-or-more HTML with NOPARSE bits
1890 function armorLinks( $text ) {
1891 return preg_replace( '/\b(' . wfUrlProtocols() . ')/',
1892 "{$this->mUniqPrefix}NOPARSE$1", $text );
1896 * Return true if subpage links should be expanded on this page.
1899 function areSubpagesAllowed() {
1900 # Some namespaces don't allow subpages
1901 return MWNamespace
::hasSubpages( $this->mTitle
->getNamespace() );
1905 * Handle link to subpage if necessary
1906 * @param string $target the source of the link
1907 * @param string &$text the link text, modified as necessary
1908 * @return string the full name of the link
1911 function maybeDoSubpageLink( $target, &$text ) {
1912 return Linker
::normalizeSubpageLink( $this->mTitle
, $target, $text );
1916 * Used by doBlockLevels()
1919 function closeParagraph() {
1921 if ( $this->mLastSection
!= '' ) {
1922 $result = '</' . $this->mLastSection
. ">\n";
1924 $this->mInPre
= false;
1925 $this->mLastSection
= '';
1929 * getCommon() returns the length of the longest common substring
1930 * of both arguments, starting at the beginning of both.
1933 function getCommon( $st1, $st2 ) {
1934 $fl = strlen( $st1 );
1935 $shorter = strlen( $st2 );
1936 if ( $fl < $shorter ) {
1940 for ( $i = 0; $i < $shorter; ++
$i ) {
1941 if ( $st1{$i} != $st2{$i} ) {
1948 * These next three functions open, continue, and close the list
1949 * element appropriate to the prefix character passed into them.
1952 function openList( $char ) {
1953 $result = $this->closeParagraph();
1955 if ( '*' === $char ) {
1956 $result .= '<ul><li>';
1957 } elseif ( '#' === $char ) {
1958 $result .= '<ol><li>';
1959 } elseif ( ':' === $char ) {
1960 $result .= '<dl><dd>';
1961 } elseif ( ';' === $char ) {
1962 $result .= '<dl><dt>';
1963 $this->mDTopen
= true;
1965 $result = '<!-- ERR 1 -->';
1973 * @param $char String
1976 function nextItem( $char ) {
1977 if ( '*' === $char ||
'#' === $char ) {
1979 } elseif ( ':' === $char ||
';' === $char ) {
1981 if ( $this->mDTopen
) {
1984 if ( ';' === $char ) {
1985 $this->mDTopen
= true;
1986 return $close . '<dt>';
1988 $this->mDTopen
= false;
1989 return $close . '<dd>';
1992 return '<!-- ERR 2 -->';
1997 * @param $char String
2000 function closeList( $char ) {
2001 if ( '*' === $char ) {
2002 $text = '</li></ul>';
2003 } elseif ( '#' === $char ) {
2004 $text = '</li></ol>';
2005 } elseif ( ':' === $char ) {
2006 if ( $this->mDTopen
) {
2007 $this->mDTopen
= false;
2008 $text = '</dt></dl>';
2010 $text = '</dd></dl>';
2013 return '<!-- ERR 3 -->';
2020 * Make lists from lines starting with ':', '*', '#', etc. (DBL)
2022 * @param $linestart bool whether or not this is at the start of a line.
2024 * @return string the lists rendered as HTML
2026 function doBlockLevels( $text, $linestart ) {
2027 wfProfileIn( __METHOD__
);
2029 # Parsing through the text line by line. The main thing
2030 # happening here is handling of block-level elements p, pre,
2031 # and making lists from lines starting with * # : etc.
2033 $textLines = StringUtils
::explode( "\n", $text );
2035 $lastPrefix = $output = '';
2036 $this->mDTopen
= $inBlockElem = false;
2038 $paragraphStack = false;
2040 foreach ( $textLines as $oLine ) {
2042 if ( !$linestart ) {
2052 $lastPrefixLength = strlen( $lastPrefix );
2053 $preCloseMatch = preg_match( '/<\\/pre/i', $oLine );
2054 $preOpenMatch = preg_match( '/<pre/i', $oLine );
2055 # If not in a <pre> element, scan for and figure out what prefixes are there.
2056 if ( !$this->mInPre
) {
2057 # Multiple prefixes may abut each other for nested lists.
2058 $prefixLength = strspn( $oLine, '*#:;' );
2059 $prefix = substr( $oLine, 0, $prefixLength );
2062 # ; and : are both from definition-lists, so they're equivalent
2063 # for the purposes of determining whether or not we need to open/close
2065 $prefix2 = str_replace( ';', ':', $prefix );
2066 $t = substr( $oLine, $prefixLength );
2067 $this->mInPre
= (bool)$preOpenMatch;
2069 # Don't interpret any other prefixes in preformatted text
2071 $prefix = $prefix2 = '';
2076 if ( $prefixLength && $lastPrefix === $prefix2 ) {
2077 # Same as the last item, so no need to deal with nesting or opening stuff
2078 $output .= $this->nextItem( substr( $prefix, -1 ) );
2079 $paragraphStack = false;
2081 if ( substr( $prefix, -1 ) === ';') {
2082 # The one nasty exception: definition lists work like this:
2083 # ; title : definition text
2084 # So we check for : in the remainder text to split up the
2085 # title and definition, without b0rking links.
2087 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2089 $output .= $term . $this->nextItem( ':' );
2092 } elseif ( $prefixLength ||
$lastPrefixLength ) {
2093 # We need to open or close prefixes, or both.
2095 # Either open or close a level...
2096 $commonPrefixLength = $this->getCommon( $prefix, $lastPrefix );
2097 $paragraphStack = false;
2099 # Close all the prefixes which aren't shared.
2100 while ( $commonPrefixLength < $lastPrefixLength ) {
2101 $output .= $this->closeList( $lastPrefix[$lastPrefixLength-1] );
2102 --$lastPrefixLength;
2105 # Continue the current prefix if appropriate.
2106 if ( $prefixLength <= $commonPrefixLength && $commonPrefixLength > 0 ) {
2107 $output .= $this->nextItem( $prefix[$commonPrefixLength-1] );
2110 # Open prefixes where appropriate.
2111 while ( $prefixLength > $commonPrefixLength ) {
2112 $char = substr( $prefix, $commonPrefixLength, 1 );
2113 $output .= $this->openList( $char );
2115 if ( ';' === $char ) {
2116 # FIXME: This is dupe of code above
2117 if ( $this->findColonNoLinks( $t, $term, $t2 ) !== false ) {
2119 $output .= $term . $this->nextItem( ':' );
2122 ++
$commonPrefixLength;
2124 $lastPrefix = $prefix2;
2127 # If we have no prefixes, go to paragraph mode.
2128 if ( 0 == $prefixLength ) {
2129 wfProfileIn( __METHOD__
."-paragraph" );
2130 # No prefix (not in list)--go to paragraph mode
2131 # XXX: use a stack for nestable elements like span, table and div
2132 $openmatch = preg_match('/(?:<table|<blockquote|<h1|<h2|<h3|<h4|<h5|<h6|<pre|<tr|<p|<ul|<ol|<li|<\\/tr|<\\/td|<\\/th)/iS', $t );
2133 $closematch = preg_match(
2134 '/(?:<\\/table|<\\/blockquote|<\\/h1|<\\/h2|<\\/h3|<\\/h4|<\\/h5|<\\/h6|'.
2135 '<td|<th|<\\/?div|<hr|<\\/pre|<\\/p|'.$this->mUniqPrefix
.'-pre|<\\/li|<\\/ul|<\\/ol|<\\/?center)/iS', $t );
2136 if ( $openmatch or $closematch ) {
2137 $paragraphStack = false;
2138 #Â TODO bug 5718: paragraph closed
2139 $output .= $this->closeParagraph();
2140 if ( $preOpenMatch and !$preCloseMatch ) {
2141 $this->mInPre
= true;
2143 if ( $closematch ) {
2144 $inBlockElem = false;
2146 $inBlockElem = true;
2148 } elseif ( !$inBlockElem && !$this->mInPre
) {
2149 if ( ' ' == substr( $t, 0, 1 ) and ( $this->mLastSection
=== 'pre' ||
trim( $t ) != '' ) ) {
2151 if ( $this->mLastSection
!== 'pre' ) {
2152 $paragraphStack = false;
2153 $output .= $this->closeParagraph().'<pre>';
2154 $this->mLastSection
= 'pre';
2156 $t = substr( $t, 1 );
2159 if ( trim( $t ) == '' ) {
2160 if ( $paragraphStack ) {
2161 $output .= $paragraphStack.'<br />';
2162 $paragraphStack = false;
2163 $this->mLastSection
= 'p';
2165 if ( $this->mLastSection
!== 'p' ) {
2166 $output .= $this->closeParagraph();
2167 $this->mLastSection
= '';
2168 $paragraphStack = '<p>';
2170 $paragraphStack = '</p><p>';
2174 if ( $paragraphStack ) {
2175 $output .= $paragraphStack;
2176 $paragraphStack = false;
2177 $this->mLastSection
= 'p';
2178 } elseif ( $this->mLastSection
!== 'p' ) {
2179 $output .= $this->closeParagraph().'<p>';
2180 $this->mLastSection
= 'p';
2185 wfProfileOut( __METHOD__
."-paragraph" );
2187 # somewhere above we forget to get out of pre block (bug 785)
2188 if ( $preCloseMatch && $this->mInPre
) {
2189 $this->mInPre
= false;
2191 if ( $paragraphStack === false ) {
2195 while ( $prefixLength ) {
2196 $output .= $this->closeList( $prefix2[$prefixLength-1] );
2199 if ( $this->mLastSection
!= '' ) {
2200 $output .= '</' . $this->mLastSection
. '>';
2201 $this->mLastSection
= '';
2204 wfProfileOut( __METHOD__
);
2209 * Split up a string on ':', ignoring any occurences inside tags
2210 * to prevent illegal overlapping.
2211 * @param string $str the string to split
2212 * @param string &$before set to everything before the ':'
2213 * @param string &$after set to everything after the ':'
2214 * return string the position of the ':', or false if none found
2216 function findColonNoLinks( $str, &$before, &$after ) {
2217 wfProfileIn( __METHOD__
);
2219 $pos = strpos( $str, ':' );
2220 if ( $pos === false ) {
2222 wfProfileOut( __METHOD__
);
2226 $lt = strpos( $str, '<' );
2227 if ( $lt === false ||
$lt > $pos ) {
2228 # Easy; no tag nesting to worry about
2229 $before = substr( $str, 0, $pos );
2230 $after = substr( $str, $pos+
1 );
2231 wfProfileOut( __METHOD__
);
2235 # Ugly state machine to walk through avoiding tags.
2236 $state = self
::COLON_STATE_TEXT
;
2238 $len = strlen( $str );
2239 for( $i = 0; $i < $len; $i++
) {
2243 # (Using the number is a performance hack for common cases)
2244 case 0: # self::COLON_STATE_TEXT:
2247 # Could be either a <start> tag or an </end> tag
2248 $state = self
::COLON_STATE_TAGSTART
;
2251 if ( $stack == 0 ) {
2253 $before = substr( $str, 0, $i );
2254 $after = substr( $str, $i +
1 );
2255 wfProfileOut( __METHOD__
);
2258 # Embedded in a tag; don't break it.
2261 # Skip ahead looking for something interesting
2262 $colon = strpos( $str, ':', $i );
2263 if ( $colon === false ) {
2264 # Nothing else interesting
2265 wfProfileOut( __METHOD__
);
2268 $lt = strpos( $str, '<', $i );
2269 if ( $stack === 0 ) {
2270 if ( $lt === false ||
$colon < $lt ) {
2272 $before = substr( $str, 0, $colon );
2273 $after = substr( $str, $colon +
1 );
2274 wfProfileOut( __METHOD__
);
2278 if ( $lt === false ) {
2279 # Nothing else interesting to find; abort!
2280 # We're nested, but there's no close tags left. Abort!
2283 # Skip ahead to next tag start
2285 $state = self
::COLON_STATE_TAGSTART
;
2288 case 1: # self::COLON_STATE_TAG:
2293 $state = self
::COLON_STATE_TEXT
;
2296 # Slash may be followed by >?
2297 $state = self
::COLON_STATE_TAGSLASH
;
2303 case 2: # self::COLON_STATE_TAGSTART:
2306 $state = self
::COLON_STATE_CLOSETAG
;
2309 $state = self
::COLON_STATE_COMMENT
;
2312 # Illegal early close? This shouldn't happen D:
2313 $state = self
::COLON_STATE_TEXT
;
2316 $state = self
::COLON_STATE_TAG
;
2319 case 3: # self::COLON_STATE_CLOSETAG:
2324 wfDebug( __METHOD__
.": Invalid input; too many close tags\n" );
2325 wfProfileOut( __METHOD__
);
2328 $state = self
::COLON_STATE_TEXT
;
2331 case self
::COLON_STATE_TAGSLASH
:
2333 # Yes, a self-closed tag <blah/>
2334 $state = self
::COLON_STATE_TEXT
;
2336 # Probably we're jumping the gun, and this is an attribute
2337 $state = self
::COLON_STATE_TAG
;
2340 case 5: # self::COLON_STATE_COMMENT:
2342 $state = self
::COLON_STATE_COMMENTDASH
;
2345 case self
::COLON_STATE_COMMENTDASH
:
2347 $state = self
::COLON_STATE_COMMENTDASHDASH
;
2349 $state = self
::COLON_STATE_COMMENT
;
2352 case self
::COLON_STATE_COMMENTDASHDASH
:
2354 $state = self
::COLON_STATE_TEXT
;
2356 $state = self
::COLON_STATE_COMMENT
;
2360 throw new MWException( "State machine error in " . __METHOD__
);
2364 wfDebug( __METHOD__
.": Invalid input; not enough close tags (stack $stack, state $state)\n" );
2367 wfProfileOut( __METHOD__
);
2372 * Return value of a magic variable (like PAGENAME)
2376 function getVariableValue( $index, $frame=false ) {
2377 global $wgContLang, $wgSitename, $wgServer, $wgServerName;
2378 global $wgScriptPath, $wgStylePath;
2381 * Some of these require message or data lookups and can be
2382 * expensive to check many times.
2384 if ( wfRunHooks( 'ParserGetVariableValueVarCache', array( &$this, &$this->mVarCache
) ) ) {
2385 if ( isset( $this->mVarCache
[$index] ) ) {
2386 return $this->mVarCache
[$index];
2390 $ts = wfTimestamp( TS_UNIX
, $this->mOptions
->getTimestamp() );
2391 wfRunHooks( 'ParserGetVariableValueTs', array( &$this, &$ts ) );
2394 global $wgLocaltimezone;
2395 if ( isset( $wgLocaltimezone ) ) {
2396 $oldtz = date_default_timezone_get();
2397 date_default_timezone_set( $wgLocaltimezone );
2400 $localTimestamp = date( 'YmdHis', $ts );
2401 $localMonth = date( 'm', $ts );
2402 $localMonth1 = date( 'n', $ts );
2403 $localMonthName = date( 'n', $ts );
2404 $localDay = date( 'j', $ts );
2405 $localDay2 = date( 'd', $ts );
2406 $localDayOfWeek = date( 'w', $ts );
2407 $localWeek = date( 'W', $ts );
2408 $localYear = date( 'Y', $ts );
2409 $localHour = date( 'H', $ts );
2410 if ( isset( $wgLocaltimezone ) ) {
2411 date_default_timezone_set( $oldtz );
2415 case 'currentmonth':
2416 $value = $wgContLang->formatNum( gmdate( 'm', $ts ) );
2418 case 'currentmonth1':
2419 $value = $wgContLang->formatNum( gmdate( 'n', $ts ) );
2421 case 'currentmonthname':
2422 $value = $wgContLang->getMonthName( gmdate( 'n', $ts ) );
2424 case 'currentmonthnamegen':
2425 $value = $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) );
2427 case 'currentmonthabbrev':
2428 $value = $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) );
2431 $value = $wgContLang->formatNum( gmdate( 'j', $ts ) );
2434 $value = $wgContLang->formatNum( gmdate( 'd', $ts ) );
2437 $value = $wgContLang->formatNum( $localMonth );
2440 $value = $wgContLang->formatNum( $localMonth1 );
2442 case 'localmonthname':
2443 $value = $wgContLang->getMonthName( $localMonthName );
2445 case 'localmonthnamegen':
2446 $value = $wgContLang->getMonthNameGen( $localMonthName );
2448 case 'localmonthabbrev':
2449 $value = $wgContLang->getMonthAbbreviation( $localMonthName );
2452 $value = $wgContLang->formatNum( $localDay );
2455 $value = $wgContLang->formatNum( $localDay2 );
2458 $value = wfEscapeWikiText( $this->mTitle
->getText() );
2461 $value = $this->mTitle
->getPartialURL();
2463 case 'fullpagename':
2464 $value = wfEscapeWikiText( $this->mTitle
->getPrefixedText() );
2466 case 'fullpagenamee':
2467 $value = $this->mTitle
->getPrefixedURL();
2470 $value = wfEscapeWikiText( $this->mTitle
->getSubpageText() );
2472 case 'subpagenamee':
2473 $value = $this->mTitle
->getSubpageUrlForm();
2475 case 'basepagename':
2476 $value = wfEscapeWikiText( $this->mTitle
->getBaseText() );
2478 case 'basepagenamee':
2479 $value = wfUrlEncode( str_replace( ' ', '_', $this->mTitle
->getBaseText() ) );
2481 case 'talkpagename':
2482 if ( $this->mTitle
->canTalk() ) {
2483 $talkPage = $this->mTitle
->getTalkPage();
2484 $value = wfEscapeWikiText( $talkPage->getPrefixedText() );
2489 case 'talkpagenamee':
2490 if ( $this->mTitle
->canTalk() ) {
2491 $talkPage = $this->mTitle
->getTalkPage();
2492 $value = $talkPage->getPrefixedUrl();
2497 case 'subjectpagename':
2498 $subjPage = $this->mTitle
->getSubjectPage();
2499 $value = wfEscapeWikiText( $subjPage->getPrefixedText() );
2501 case 'subjectpagenamee':
2502 $subjPage = $this->mTitle
->getSubjectPage();
2503 $value = $subjPage->getPrefixedUrl();
2506 # Let the edit saving system know we should parse the page
2507 # *after* a revision ID has been assigned.
2508 $this->mOutput
->setFlag( 'vary-revision' );
2509 wfDebug( __METHOD__
. ": {{REVISIONID}} used, setting vary-revision...\n" );
2510 $value = $this->mRevisionId
;
2513 # Let the edit saving system know we should parse the page
2514 # *after* a revision ID has been assigned. This is for null edits.
2515 $this->mOutput
->setFlag( 'vary-revision' );
2516 wfDebug( __METHOD__
. ": {{REVISIONDAY}} used, setting vary-revision...\n" );
2517 $value = intval( substr( $this->getRevisionTimestamp(), 6, 2 ) );
2519 case 'revisionday2':
2520 # Let the edit saving system know we should parse the page
2521 # *after* a revision ID has been assigned. This is for null edits.
2522 $this->mOutput
->setFlag( 'vary-revision' );
2523 wfDebug( __METHOD__
. ": {{REVISIONDAY2}} used, setting vary-revision...\n" );
2524 $value = substr( $this->getRevisionTimestamp(), 6, 2 );
2526 case 'revisionmonth':
2527 # Let the edit saving system know we should parse the page
2528 # *after* a revision ID has been assigned. This is for null edits.
2529 $this->mOutput
->setFlag( 'vary-revision' );
2530 wfDebug( __METHOD__
. ": {{REVISIONMONTH}} used, setting vary-revision...\n" );
2531 $value = intval( substr( $this->getRevisionTimestamp(), 4, 2 ) );
2533 case 'revisionyear':
2534 # Let the edit saving system know we should parse the page
2535 # *after* a revision ID has been assigned. This is for null edits.
2536 $this->mOutput
->setFlag( 'vary-revision' );
2537 wfDebug( __METHOD__
. ": {{REVISIONYEAR}} used, setting vary-revision...\n" );
2538 $value = substr( $this->getRevisionTimestamp(), 0, 4 );
2540 case 'revisiontimestamp':
2541 # Let the edit saving system know we should parse the page
2542 # *after* a revision ID has been assigned. This is for null edits.
2543 $this->mOutput
->setFlag( 'vary-revision' );
2544 wfDebug( __METHOD__
. ": {{REVISIONTIMESTAMP}} used, setting vary-revision...\n" );
2545 $value = $this->getRevisionTimestamp();
2547 case 'revisionuser':
2548 # Let the edit saving system know we should parse the page
2549 # *after* a revision ID has been assigned. This is for null edits.
2550 $this->mOutput
->setFlag( 'vary-revision' );
2551 wfDebug( __METHOD__
. ": {{REVISIONUSER}} used, setting vary-revision...\n" );
2552 $value = $this->getRevisionUser();
2555 $value = str_replace( '_',' ',$wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2558 $value = wfUrlencode( $wgContLang->getNsText( $this->mTitle
->getNamespace() ) );
2561 $value = $this->mTitle
->canTalk() ?
str_replace( '_',' ',$this->mTitle
->getTalkNsText() ) : '';
2564 $value = $this->mTitle
->canTalk() ?
wfUrlencode( $this->mTitle
->getTalkNsText() ) : '';
2566 case 'subjectspace':
2567 $value = $this->mTitle
->getSubjectNsText();
2569 case 'subjectspacee':
2570 $value = ( wfUrlencode( $this->mTitle
->getSubjectNsText() ) );
2572 case 'currentdayname':
2573 $value = $wgContLang->getWeekdayName( gmdate( 'w', $ts ) +
1 );
2576 $value = $wgContLang->formatNum( gmdate( 'Y', $ts ), true );
2579 $value = $wgContLang->time( wfTimestamp( TS_MW
, $ts ), false, false );
2582 $value = $wgContLang->formatNum( gmdate( 'H', $ts ), true );
2585 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2586 # int to remove the padding
2587 $value = $wgContLang->formatNum( (int)gmdate( 'W', $ts ) );
2590 $value = $wgContLang->formatNum( gmdate( 'w', $ts ) );
2592 case 'localdayname':
2593 $value = $wgContLang->getWeekdayName( $localDayOfWeek +
1 );
2596 $value = $wgContLang->formatNum( $localYear, true );
2599 $value = $wgContLang->time( $localTimestamp, false, false );
2602 $value = $wgContLang->formatNum( $localHour, true );
2605 # @bug 4594 PHP5 has it zero padded, PHP4 does not, cast to
2606 # int to remove the padding
2607 $value = $wgContLang->formatNum( (int)$localWeek );
2610 $value = $wgContLang->formatNum( $localDayOfWeek );
2612 case 'numberofarticles':
2613 $value = $wgContLang->formatNum( SiteStats
::articles() );
2615 case 'numberoffiles':
2616 $value = $wgContLang->formatNum( SiteStats
::images() );
2618 case 'numberofusers':
2619 $value = $wgContLang->formatNum( SiteStats
::users() );
2621 case 'numberofactiveusers':
2622 $value = $wgContLang->formatNum( SiteStats
::activeUsers() );
2624 case 'numberofpages':
2625 $value = $wgContLang->formatNum( SiteStats
::pages() );
2627 case 'numberofadmins':
2628 $value = $wgContLang->formatNum( SiteStats
::numberingroup( 'sysop' ) );
2630 case 'numberofedits':
2631 $value = $wgContLang->formatNum( SiteStats
::edits() );
2633 case 'numberofviews':
2634 $value = $wgContLang->formatNum( SiteStats
::views() );
2636 case 'currenttimestamp':
2637 $value = wfTimestamp( TS_MW
, $ts );
2639 case 'localtimestamp':
2640 $value = $localTimestamp;
2642 case 'currentversion':
2643 $value = SpecialVersion
::getVersion();
2650 return $wgServerName;
2652 return $wgScriptPath;
2654 return $wgStylePath;
2655 case 'directionmark':
2656 return $wgContLang->getDirMark();
2657 case 'contentlanguage':
2658 global $wgContLanguageCode;
2659 return $wgContLanguageCode;
2662 if ( wfRunHooks( 'ParserGetVariableValueSwitch', array( &$this, &$this->mVarCache
, &$index, &$ret, &$frame ) ) ) {
2670 $this->mVarCache
[$index] = $value;
2676 * initialise the magic variables (like CURRENTMONTHNAME) and substitution modifiers
2680 function initialiseVariables() {
2681 wfProfileIn( __METHOD__
);
2682 $variableIDs = MagicWord
::getVariableIDs();
2683 $substIDs = MagicWord
::getSubstIDs();
2685 $this->mVariables
= new MagicWordArray( $variableIDs );
2686 $this->mSubstWords
= new MagicWordArray( $substIDs );
2687 wfProfileOut( __METHOD__
);
2691 * Preprocess some wikitext and return the document tree.
2692 * This is the ghost of replace_variables().
2694 * @param string $text The text to parse
2695 * @param integer flags Bitwise combination of:
2696 * self::PTD_FOR_INCLUSION Handle <noinclude>/<includeonly> as if the text is being
2697 * included. Default is to assume a direct page view.
2699 * The generated DOM tree must depend only on the input text and the flags.
2700 * The DOM tree must be the same in OT_HTML and OT_WIKI mode, to avoid a regression of bug 4899.
2702 * Any flag added to the $flags parameter here, or any other parameter liable to cause a
2703 * change in the DOM tree for a given text, must be passed through the section identifier
2704 * in the section edit link and thus back to extractSections().
2706 * The output of this function is currently only cached in process memory, but a persistent
2707 * cache may be implemented at a later date which takes further advantage of these strict
2708 * dependency requirements.
2712 function preprocessToDom( $text, $flags = 0 ) {
2713 $dom = $this->getPreprocessor()->preprocessToObj( $text, $flags );
2718 * Return a three-element array: leading whitespace, string contents, trailing whitespace
2720 public static function splitWhitespace( $s ) {
2721 $ltrimmed = ltrim( $s );
2722 $w1 = substr( $s, 0, strlen( $s ) - strlen( $ltrimmed ) );
2723 $trimmed = rtrim( $ltrimmed );
2724 $diff = strlen( $ltrimmed ) - strlen( $trimmed );
2726 $w2 = substr( $ltrimmed, -$diff );
2730 return array( $w1, $trimmed, $w2 );
2734 * Replace magic variables, templates, and template arguments
2735 * with the appropriate text. Templates are substituted recursively,
2736 * taking care to avoid infinite loops.
2738 * Note that the substitution depends on value of $mOutputType:
2739 * self::OT_WIKI: only {{subst:}} templates
2740 * self::OT_PREPROCESS: templates but not extension tags
2741 * self::OT_HTML: all templates and extension tags
2743 * @param string $tex The text to transform
2744 * @param PPFrame $frame Object describing the arguments passed to the template.
2745 * Arguments may also be provided as an associative array, as was the usual case before MW1.12.
2746 * Providing arguments this way may be useful for extensions wishing to perform variable replacement explicitly.
2747 * @param bool $argsOnly Only do argument (triple-brace) expansion, not double-brace expansion
2750 function replaceVariables( $text, $frame = false, $argsOnly = false ) {
2751 # Is there any text? Also, Prevent too big inclusions!
2752 if ( strlen( $text ) < 1 ||
strlen( $text ) > $this->mOptions
->getMaxIncludeSize() ) {
2755 wfProfileIn( __METHOD__
);
2757 if ( $frame === false ) {
2758 $frame = $this->getPreprocessor()->newFrame();
2759 } elseif ( !( $frame instanceof PPFrame
) ) {
2760 wfDebug( __METHOD__
." called using plain parameters instead of a PPFrame instance. Creating custom frame.\n" );
2761 $frame = $this->getPreprocessor()->newCustomFrame( $frame );
2764 $dom = $this->preprocessToDom( $text );
2765 $flags = $argsOnly ? PPFrame
::NO_TEMPLATES
: 0;
2766 $text = $frame->expand( $dom, $flags );
2768 wfProfileOut( __METHOD__
);
2772 # Clean up argument array - refactored in 1.9 so parserfunctions can use it, too.
2773 static function createAssocArgs( $args ) {
2774 $assocArgs = array();
2776 foreach ( $args as $arg ) {
2777 $eqpos = strpos( $arg, '=' );
2778 if ( $eqpos === false ) {
2779 $assocArgs[$index++
] = $arg;
2781 $name = trim( substr( $arg, 0, $eqpos ) );
2782 $value = trim( substr( $arg, $eqpos+
1 ) );
2783 if ( $value === false ) {
2786 if ( $name !== false ) {
2787 $assocArgs[$name] = $value;
2796 * Warn the user when a parser limitation is reached
2797 * Will warn at most once the user per limitation type
2799 * @param string $limitationType, should be one of:
2800 * 'expensive-parserfunction' (corresponding messages:
2801 * 'expensive-parserfunction-warning',
2802 * 'expensive-parserfunction-category')
2803 * 'post-expand-template-argument' (corresponding messages:
2804 * 'post-expand-template-argument-warning',
2805 * 'post-expand-template-argument-category')
2806 * 'post-expand-template-inclusion' (corresponding messages:
2807 * 'post-expand-template-inclusion-warning',
2808 * 'post-expand-template-inclusion-category')
2809 * @params int $current, $max When an explicit limit has been
2810 * exceeded, provide the values (optional)
2812 function limitationWarn( $limitationType, $current=null, $max=null) {
2813 # does no harm if $current and $max are present but are unnecessary for the message
2814 $warning = wfMsgExt( "$limitationType-warning", array( 'parsemag', 'escape' ), $current, $max );
2815 $this->mOutput
->addWarning( $warning );
2816 $this->addTrackingCategory( "$limitationType-category" );
2820 * Return the text of a template, after recursively
2821 * replacing any variables or templates within the template.
2823 * @param array $piece The parts of the template
2824 * $piece['title']: the title, i.e. the part before the |
2825 * $piece['parts']: the parameter array
2826 * $piece['lineStart']: whether the brace was at the start of a line
2827 * @param PPFrame The current frame, contains template arguments
2828 * @return string the text of the template
2831 function braceSubstitution( $piece, $frame ) {
2832 global $wgContLang, $wgNonincludableNamespaces;
2833 wfProfileIn( __METHOD__
);
2834 wfProfileIn( __METHOD__
.'-setup' );
2837 $found = false; # $text has been filled
2838 $nowiki = false; # wiki markup in $text should be escaped
2839 $isHTML = false; # $text is HTML, armour it against wikitext transformation
2840 $forceRawInterwiki = false; # Force interwiki transclusion to be done in raw mode not rendered
2841 $isChildObj = false; # $text is a DOM node needing expansion in a child frame
2842 $isLocalObj = false; # $text is a DOM node needing expansion in the current frame
2844 # Title object, where $text came from
2847 # $part1 is the bit before the first |, and must contain only title characters.
2848 # Various prefixes will be stripped from it later.
2849 $titleWithSpaces = $frame->expand( $piece['title'] );
2850 $part1 = trim( $titleWithSpaces );
2853 # Original title text preserved for various purposes
2854 $originalTitle = $part1;
2856 # $args is a list of argument nodes, starting from index 0, not including $part1
2857 $args = ( null == $piece['parts'] ) ?
array() : $piece['parts'];
2858 wfProfileOut( __METHOD__
.'-setup' );
2861 wfProfileIn( __METHOD__
.'-modifiers' );
2864 $substMatch = $this->mSubstWords
->matchStartAndRemove( $part1 );
2866 # Possibilities for substMatch: "subst", "safesubst" or FALSE
2867 # Decide whether to expand template or keep wikitext as-is.
2868 if ( $this->ot
['wiki'] ) {
2869 if ( $substMatch === false ) {
2870 $literal = true; # literal when in PST with no prefix
2872 $literal = false; # expand when in PST with subst: or safesubst:
2875 if ( $substMatch == 'subst' ) {
2876 $literal = true; # literal when not in PST with plain subst:
2878 $literal = false; # expand when not in PST with safesubst: or no prefix
2882 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
2889 if ( !$found && $args->getLength() == 0 ) {
2890 $id = $this->mVariables
->matchStartToEnd( $part1 );
2891 if ( $id !== false ) {
2892 $text = $this->getVariableValue( $id, $frame );
2893 if ( MagicWord
::getCacheTTL( $id ) > -1 ) {
2894 $this->mOutput
->mContainsOldMagic
= true;
2900 # MSG, MSGNW and RAW
2903 $mwMsgnw = MagicWord
::get( 'msgnw' );
2904 if ( $mwMsgnw->matchStartAndRemove( $part1 ) ) {
2907 # Remove obsolete MSG:
2908 $mwMsg = MagicWord
::get( 'msg' );
2909 $mwMsg->matchStartAndRemove( $part1 );
2913 $mwRaw = MagicWord
::get( 'raw' );
2914 if ( $mwRaw->matchStartAndRemove( $part1 ) ) {
2915 $forceRawInterwiki = true;
2918 wfProfileOut( __METHOD__
.'-modifiers' );
2922 wfProfileIn( __METHOD__
. '-pfunc' );
2924 $colonPos = strpos( $part1, ':' );
2925 if ( $colonPos !== false ) {
2926 # Case sensitive functions
2927 $function = substr( $part1, 0, $colonPos );
2928 if ( isset( $this->mFunctionSynonyms
[1][$function] ) ) {
2929 $function = $this->mFunctionSynonyms
[1][$function];
2931 # Case insensitive functions
2932 $function = $wgContLang->lc( $function );
2933 if ( isset( $this->mFunctionSynonyms
[0][$function] ) ) {
2934 $function = $this->mFunctionSynonyms
[0][$function];
2940 list( $callback, $flags ) = $this->mFunctionHooks
[$function];
2941 $initialArgs = array( &$this );
2942 $funcArgs = array( trim( substr( $part1, $colonPos +
1 ) ) );
2943 if ( $flags & SFH_OBJECT_ARGS
) {
2944 # Add a frame parameter, and pass the arguments as an array
2945 $allArgs = $initialArgs;
2946 $allArgs[] = $frame;
2947 for ( $i = 0; $i < $args->getLength(); $i++
) {
2948 $funcArgs[] = $args->item( $i );
2950 $allArgs[] = $funcArgs;
2952 # Convert arguments to plain text
2953 for ( $i = 0; $i < $args->getLength(); $i++
) {
2954 $funcArgs[] = trim( $frame->expand( $args->item( $i ) ) );
2956 $allArgs = array_merge( $initialArgs, $funcArgs );
2959 # Workaround for PHP bug 35229 and similar
2960 if ( !is_callable( $callback ) ) {
2961 wfProfileOut( __METHOD__
. '-pfunc' );
2962 wfProfileOut( __METHOD__
);
2963 throw new MWException( "Tag hook for $function is not callable\n" );
2965 $result = call_user_func_array( $callback, $allArgs );
2968 $preprocessFlags = 0;
2970 if ( is_array( $result ) ) {
2971 if ( isset( $result[0] ) ) {
2973 unset( $result[0] );
2976 # Extract flags into the local scope
2977 # This allows callers to set flags such as nowiki, found, etc.
2983 $text = $this->preprocessToDom( $text, $preprocessFlags );
2988 wfProfileOut( __METHOD__
. '-pfunc' );
2991 # Finish mangling title and then check for loops.
2992 # Set $title to a Title object and $titleText to the PDBK
2995 # Split the title into page and subpage
2997 $part1 = $this->maybeDoSubpageLink( $part1, $subpage );
2998 if ( $subpage !== '' ) {
2999 $ns = $this->mTitle
->getNamespace();
3001 $title = Title
::newFromText( $part1, $ns );
3003 $titleText = $title->getPrefixedText();
3004 # Check for language variants if the template is not found
3005 if ( $wgContLang->hasVariants() && $title->getArticleID() == 0 ) {
3006 $wgContLang->findVariantLink( $part1, $title, true );
3008 # Do recursion depth check
3009 $limit = $this->mOptions
->getMaxTemplateDepth();
3010 if ( $frame->depth
>= $limit ) {
3012 $text = '<span class="error">'
3013 . wfMsgForContent( 'parser-template-recursion-depth-warning', $limit )
3019 # Load from database
3020 if ( !$found && $title ) {
3021 wfProfileIn( __METHOD__
. '-loadtpl' );
3022 if ( !$title->isExternal() ) {
3023 if ( $title->getNamespace() == NS_SPECIAL
3024 && $this->mOptions
->getAllowSpecialInclusion()
3025 && $this->ot
['html'] )
3027 $text = SpecialPage
::capturePath( $title );
3028 if ( is_string( $text ) ) {
3031 $this->disableCache();
3033 } elseif ( $wgNonincludableNamespaces && in_array( $title->getNamespace(), $wgNonincludableNamespaces ) ) {
3034 $found = false; # access denied
3035 wfDebug( __METHOD__
.": template inclusion denied for " . $title->getPrefixedDBkey() );
3037 list( $text, $title ) = $this->getTemplateDom( $title );
3038 if ( $text !== false ) {
3044 # If the title is valid but undisplayable, make a link to it
3045 if ( !$found && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3046 $text = "[[:$titleText]]";
3049 } elseif ( $title->isTrans() ) {
3050 # Interwiki transclusion
3051 if ( $this->ot
['html'] && !$forceRawInterwiki ) {
3052 $text = $this->interwikiTransclude( $title, 'render' );
3055 $text = $this->interwikiTransclude( $title, 'raw' );
3056 # Preprocess it like a template
3057 $text = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3063 # Do infinite loop check
3064 # This has to be done after redirect resolution to avoid infinite loops via redirects
3065 if ( !$frame->loopCheck( $title ) ) {
3067 $text = '<span class="error">' . wfMsgForContent( 'parser-template-loop-warning', $titleText ) . '</span>';
3068 wfDebug( __METHOD__
.": template loop broken at '$titleText'\n" );
3070 wfProfileOut( __METHOD__
. '-loadtpl' );
3073 # If we haven't found text to substitute by now, we're done
3074 # Recover the source wikitext and return it
3076 $text = $frame->virtualBracketedImplode( '{{', '|', '}}', $titleWithSpaces, $args );
3077 wfProfileOut( __METHOD__
);
3078 return array( 'object' => $text );
3081 # Expand DOM-style return values in a child frame
3082 if ( $isChildObj ) {
3083 # Clean up argument array
3084 $newFrame = $frame->newChild( $args, $title );
3087 $text = $newFrame->expand( $text, PPFrame
::RECOVER_ORIG
);
3088 } elseif ( $titleText !== false && $newFrame->isEmpty() ) {
3089 # Expansion is eligible for the empty-frame cache
3090 if ( isset( $this->mTplExpandCache
[$titleText] ) ) {
3091 $text = $this->mTplExpandCache
[$titleText];
3093 $text = $newFrame->expand( $text );
3094 $this->mTplExpandCache
[$titleText] = $text;
3097 # Uncached expansion
3098 $text = $newFrame->expand( $text );
3101 if ( $isLocalObj && $nowiki ) {
3102 $text = $frame->expand( $text, PPFrame
::RECOVER_ORIG
);
3103 $isLocalObj = false;
3106 # Replace raw HTML by a placeholder
3107 # Add a blank line preceding, to prevent it from mucking up
3108 # immediately preceding headings
3110 $text = "\n\n" . $this->insertStripItem( $text );
3111 } elseif ( $nowiki && ( $this->ot
['html'] ||
$this->ot
['pre'] ) ) {
3112 # Escape nowiki-style return values
3113 $text = wfEscapeWikiText( $text );
3114 } elseif ( is_string( $text )
3115 && !$piece['lineStart']
3116 && preg_match( '/^(?:{\\||:|;|#|\*)/', $text ) )
3118 # Bug 529: if the template begins with a table or block-level
3119 # element, it should be treated as beginning a new line.
3120 # This behaviour is somewhat controversial.
3121 $text = "\n" . $text;
3124 if ( is_string( $text ) && !$this->incrementIncludeSize( 'post-expand', strlen( $text ) ) ) {
3125 # Error, oversize inclusion
3126 $text = "[[$originalTitle]]" .
3127 $this->insertStripItem( '<!-- WARNING: template omitted, post-expand include size too large -->' );
3128 $this->limitationWarn( 'post-expand-template-inclusion' );
3131 if ( $isLocalObj ) {
3132 $ret = array( 'object' => $text );
3134 $ret = array( 'text' => $text );
3137 wfProfileOut( __METHOD__
);
3142 * Get the semi-parsed DOM representation of a template with a given title,
3143 * and its redirect destination title. Cached.
3145 function getTemplateDom( $title ) {
3146 $cacheTitle = $title;
3147 $titleText = $title->getPrefixedDBkey();
3149 if ( isset( $this->mTplRedirCache
[$titleText] ) ) {
3150 list( $ns, $dbk ) = $this->mTplRedirCache
[$titleText];
3151 $title = Title
::makeTitle( $ns, $dbk );
3152 $titleText = $title->getPrefixedDBkey();
3154 if ( isset( $this->mTplDomCache
[$titleText] ) ) {
3155 return array( $this->mTplDomCache
[$titleText], $title );
3158 # Cache miss, go to the database
3159 list( $text, $title ) = $this->fetchTemplateAndTitle( $title );
3161 if ( $text === false ) {
3162 $this->mTplDomCache
[$titleText] = false;
3163 return array( false, $title );
3166 $dom = $this->preprocessToDom( $text, self
::PTD_FOR_INCLUSION
);
3167 $this->mTplDomCache
[ $titleText ] = $dom;
3169 if ( !$title->equals( $cacheTitle ) ) {
3170 $this->mTplRedirCache
[$cacheTitle->getPrefixedDBkey()] =
3171 array( $title->getNamespace(),$cdb = $title->getDBkey() );
3174 return array( $dom, $title );
3178 * Fetch the unparsed text of a template and register a reference to it.
3180 function fetchTemplateAndTitle( $title ) {
3181 $templateCb = $this->mOptions
->getTemplateCallback();
3182 $stuff = call_user_func( $templateCb, $title, $this );
3183 $text = $stuff['text'];
3184 $finalTitle = isset( $stuff['finalTitle'] ) ?
$stuff['finalTitle'] : $title;
3185 if ( isset( $stuff['deps'] ) ) {
3186 foreach ( $stuff['deps'] as $dep ) {
3187 $this->mOutput
->addTemplate( $dep['title'], $dep['page_id'], $dep['rev_id'] );
3190 return array( $text, $finalTitle );
3193 function fetchTemplate( $title ) {
3194 $rv = $this->fetchTemplateAndTitle( $title );
3199 * Static function to get a template
3200 * Can be overridden via ParserOptions::setTemplateCallback().
3202 static function statelessFetchTemplate( $title, $parser=false ) {
3203 $text = $skip = false;
3204 $finalTitle = $title;
3207 # Loop to fetch the article, with up to 1 redirect
3208 for ( $i = 0; $i < 2 && is_object( $title ); $i++
) {
3209 # Give extensions a chance to select the revision instead
3210 $id = false; # Assume current
3211 wfRunHooks( 'BeforeParserFetchTemplateAndtitle', array( $parser, &$title, &$skip, &$id ) );
3217 'page_id' => $title->getArticleID(),
3221 $rev = $id ? Revision
::newFromId( $id ) : Revision
::newFromTitle( $title );
3222 $rev_id = $rev ?
$rev->getId() : 0;
3223 # If there is no current revision, there is no page
3224 if ( $id === false && !$rev ) {
3225 $linkCache = LinkCache
::singleton();
3226 $linkCache->addBadLinkObj( $title );
3231 'page_id' => $title->getArticleID(),
3232 'rev_id' => $rev_id );
3235 $text = $rev->getText();
3236 } elseif ( $title->getNamespace() == NS_MEDIAWIKI
) {
3238 $message = $wgContLang->lcfirst( $title->getText() );
3239 $text = wfMsgForContentNoTrans( $message );
3240 if ( wfEmptyMsg( $message, $text ) ) {
3247 if ( $text === false ) {
3251 $finalTitle = $title;
3252 $title = Title
::newFromRedirect( $text );
3256 'finalTitle' => $finalTitle,
3261 * Transclude an interwiki link.
3263 function interwikiTransclude( $title, $action ) {
3264 global $wgEnableScaryTranscluding;
3266 if ( !$wgEnableScaryTranscluding ) {
3267 return wfMsg('scarytranscludedisabled');
3270 $url = $title->getFullUrl( "action=$action" );
3272 if ( strlen( $url ) > 255 ) {
3273 return wfMsg( 'scarytranscludetoolong' );
3275 return $this->fetchScaryTemplateMaybeFromCache( $url );
3278 function fetchScaryTemplateMaybeFromCache( $url ) {
3279 global $wgTranscludeCacheExpiry;
3280 $dbr = wfGetDB( DB_SLAVE
);
3281 $tsCond = $dbr->timestamp( time() - $wgTranscludeCacheExpiry );
3282 $obj = $dbr->selectRow( 'transcache', array('tc_time', 'tc_contents' ),
3283 array( 'tc_url' => $url, "tc_time >= " . $dbr->addQuotes( $tsCond ) ) );
3285 return $obj->tc_contents
;
3288 $text = Http
::get( $url );
3290 return wfMsg( 'scarytranscludefailed', $url );
3293 $dbw = wfGetDB( DB_MASTER
);
3294 $dbw->replace( 'transcache', array('tc_url'), array(
3296 'tc_time' => $dbw->timestamp( time() ),
3297 'tc_contents' => $text)
3304 * Triple brace replacement -- used for template arguments
3307 function argSubstitution( $piece, $frame ) {
3308 wfProfileIn( __METHOD__
);
3311 $parts = $piece['parts'];
3312 $nameWithSpaces = $frame->expand( $piece['title'] );
3313 $argName = trim( $nameWithSpaces );
3315 $text = $frame->getArgument( $argName );
3316 if ( $text === false && $parts->getLength() > 0
3320 ||
( $this->ot
['wiki'] && $frame->isTemplate() )
3323 # No match in frame, use the supplied default
3324 $object = $parts->item( 0 )->getChildren();
3326 if ( !$this->incrementIncludeSize( 'arg', strlen( $text ) ) ) {
3327 $error = '<!-- WARNING: argument omitted, expansion size too large -->';
3328 $this->limitationWarn( 'post-expand-template-argument' );
3331 if ( $text === false && $object === false ) {
3333 $object = $frame->virtualBracketedImplode( '{{{', '|', '}}}', $nameWithSpaces, $parts );
3335 if ( $error !== false ) {
3338 if ( $object !== false ) {
3339 $ret = array( 'object' => $object );
3341 $ret = array( 'text' => $text );
3344 wfProfileOut( __METHOD__
);
3349 * Return the text to be used for a given extension tag.
3350 * This is the ghost of strip().
3352 * @param array $params Associative array of parameters:
3353 * name PPNode for the tag name
3354 * attr PPNode for unparsed text where tag attributes are thought to be
3355 * attributes Optional associative array of parsed attributes
3356 * inner Contents of extension element
3357 * noClose Original text did not have a close tag
3358 * @param PPFrame $frame
3360 function extensionSubstitution( $params, $frame ) {
3361 global $wgRawHtml, $wgContLang;
3363 $name = $frame->expand( $params['name'] );
3364 $attrText = !isset( $params['attr'] ) ?
null : $frame->expand( $params['attr'] );
3365 $content = !isset( $params['inner'] ) ?
null : $frame->expand( $params['inner'] );
3366 $marker = "{$this->mUniqPrefix}-$name-" . sprintf( '%08X', $this->mMarkerIndex++
) . self
::MARKER_SUFFIX
;
3368 $isFunctionTag = isset( $this->mFunctionTagHooks
[strtolower($name)] ) &&
3369 ( $this->ot
['html'] ||
$this->ot
['pre'] );
3370 if ( $isFunctionTag ) {
3371 $markerType = 'none';
3373 $markerType = 'general';
3375 if ( $this->ot
['html'] ||
$isFunctionTag ) {
3376 $name = strtolower( $name );
3377 $attributes = Sanitizer
::decodeTagAttributes( $attrText );
3378 if ( isset( $params['attributes'] ) ) {
3379 $attributes = $attributes +
$params['attributes'];
3382 if ( isset( $this->mTagHooks
[$name] ) ) {
3383 # Workaround for PHP bug 35229 and similar
3384 if ( !is_callable( $this->mTagHooks
[$name] ) ) {
3385 throw new MWException( "Tag hook for $name is not callable\n" );
3387 $output = call_user_func_array( $this->mTagHooks
[$name],
3388 array( $content, $attributes, $this, $frame ) );
3389 } elseif ( isset( $this->mFunctionTagHooks
[$name] ) ) {
3390 list( $callback, $flags ) = $this->mFunctionTagHooks
[$name];
3391 if ( !is_callable( $callback ) ) {
3392 throw new MWException( "Tag hook for $name is not callable\n" );
3395 $output = call_user_func_array( $callback, array( &$this, $frame, $content, $attributes ) );
3397 $output = '<span class="error">Invalid tag extension name: ' .
3398 htmlspecialchars( $name ) . '</span>';
3401 if ( is_array( $output ) ) {
3402 # Extract flags to local scope (to override $markerType)
3404 $output = $flags[0];
3409 if ( is_null( $attrText ) ) {
3412 if ( isset( $params['attributes'] ) ) {
3413 foreach ( $params['attributes'] as $attrName => $attrValue ) {
3414 $attrText .= ' ' . htmlspecialchars( $attrName ) . '="' .
3415 htmlspecialchars( $attrValue ) . '"';
3418 if ( $content === null ) {
3419 $output = "<$name$attrText/>";
3421 $close = is_null( $params['close'] ) ?
'' : $frame->expand( $params['close'] );
3422 $output = "<$name$attrText>$content$close";
3426 if ( $markerType === 'none' ) {
3428 } elseif ( $markerType === 'nowiki' ) {
3429 $this->mStripState
->nowiki
->setPair( $marker, $output );
3430 } elseif ( $markerType === 'general' ) {
3431 $this->mStripState
->general
->setPair( $marker, $output );
3433 throw new MWException( __METHOD__
.': invalid marker type' );
3439 * Increment an include size counter
3441 * @param string $type The type of expansion
3442 * @param integer $size The size of the text
3443 * @return boolean False if this inclusion would take it over the maximum, true otherwise
3445 function incrementIncludeSize( $type, $size ) {
3446 if ( $this->mIncludeSizes
[$type] +
$size > $this->mOptions
->getMaxIncludeSize( $type ) ) {
3449 $this->mIncludeSizes
[$type] +
= $size;
3455 * Increment the expensive function count
3457 * @return boolean False if the limit has been exceeded
3459 function incrementExpensiveFunctionCount() {
3460 global $wgExpensiveParserFunctionLimit;
3461 $this->mExpensiveFunctionCount++
;
3462 if ( $this->mExpensiveFunctionCount
<= $wgExpensiveParserFunctionLimit ) {
3469 * Strip double-underscore items like __NOGALLERY__ and __NOTOC__
3470 * Fills $this->mDoubleUnderscores, returns the modified text
3472 function doDoubleUnderscore( $text ) {
3473 wfProfileIn( __METHOD__
);
3475 # The position of __TOC__ needs to be recorded
3476 $mw = MagicWord
::get( 'toc' );
3477 if ( $mw->match( $text ) ) {
3478 $this->mShowToc
= true;
3479 $this->mForceTocPosition
= true;
3481 # Set a placeholder. At the end we'll fill it in with the TOC.
3482 $text = $mw->replace( '<!--MWTOC-->', $text, 1 );
3484 # Only keep the first one.
3485 $text = $mw->replace( '', $text );
3488 # Now match and remove the rest of them
3489 $mwa = MagicWord
::getDoubleUnderscoreArray();
3490 $this->mDoubleUnderscores
= $mwa->matchAndRemove( $text );
3492 if ( isset( $this->mDoubleUnderscores
['nogallery'] ) ) {
3493 $this->mOutput
->mNoGallery
= true;
3495 if ( isset( $this->mDoubleUnderscores
['notoc'] ) && !$this->mForceTocPosition
) {
3496 $this->mShowToc
= false;
3498 if ( isset( $this->mDoubleUnderscores
['hiddencat'] ) && $this->mTitle
->getNamespace() == NS_CATEGORY
) {
3499 $this->mOutput
->setProperty( 'hiddencat', 'y' );
3500 $this->addTrackingCategory( 'hidden-category-category' );
3502 # (bug 8068) Allow control over whether robots index a page.
3504 # FIXME (bug 14899): __INDEX__ always overrides __NOINDEX__ here! This
3505 # is not desirable, the last one on the page should win.
3506 if ( isset( $this->mDoubleUnderscores
['noindex'] ) && $this->mTitle
->canUseNoindex() ) {
3507 $this->mOutput
->setIndexPolicy( 'noindex' );
3508 $this->addTrackingCategory( 'noindex-category' );
3510 if ( isset( $this->mDoubleUnderscores
['index'] ) && $this->mTitle
->canUseNoindex() ) {
3511 $this->mOutput
->setIndexPolicy( 'index' );
3512 $this->addTrackingCategory( 'index-category' );
3515 wfProfileOut( __METHOD__
);
3520 * Add a tracking category, getting the title from a system message,
3521 * or print a debug message if the title is invalid.
3522 * @param $msg String message key
3523 * @return Bool whether the addition was successful
3525 protected function addTrackingCategory( $msg ) {
3526 $cat = wfMsgForContent( $msg );
3528 # Allow tracking categories to be disabled by setting them to "-"
3529 if ( $cat === '-' ) {
3533 $containerCategory = Title
::makeTitleSafe( NS_CATEGORY
, $cat );
3534 if ( $containerCategory ) {
3535 $this->mOutput
->addCategory( $containerCategory->getDBkey(), $this->getDefaultSort() );
3538 wfDebug( __METHOD__
.": [[MediaWiki:$msg]] is not a valid title!\n" );
3544 * This function accomplishes several tasks:
3545 * 1) Auto-number headings if that option is enabled
3546 * 2) Add an [edit] link to sections for users who have enabled the option and can edit the page
3547 * 3) Add a Table of contents on the top for users who have enabled the option
3548 * 4) Auto-anchor headings
3550 * It loops through all headlines, collects the necessary data, then splits up the
3551 * string and re-inserts the newly formatted headlines.
3553 * @param string $text
3554 * @param string $origText Original, untouched wikitext
3555 * @param boolean $isMain
3558 function formatHeadings( $text, $origText, $isMain=true ) {
3559 global $wgMaxTocLevel, $wgContLang, $wgHtml5, $wgExperimentalHtmlIds;
3561 $doNumberHeadings = $this->mOptions
->getNumberHeadings();
3562 $showEditLink = $this->mOptions
->getEditSection();
3564 # Do not call quickUserCan unless necessary
3565 if ( $showEditLink && !$this->mTitle
->quickUserCan( 'edit' ) ) {
3569 # Inhibit editsection links if requested in the page
3570 if ( isset( $this->mDoubleUnderscores
['noeditsection'] ) ||
$this->mOptions
->getIsPrintable() ) {
3574 # Get all headlines for numbering them and adding funky stuff like [edit]
3575 # links - this is for later, but we need the number of headlines right now
3577 $numMatches = preg_match_all( '/<H(?P<level>[1-6])(?P<attrib>.*?'.'>)(?P<header>.*?)<\/H[1-6] *>/i', $text, $matches );
3579 # if there are fewer than 4 headlines in the article, do not show TOC
3580 # unless it's been explicitly enabled.
3581 $enoughToc = $this->mShowToc
&&
3582 ( ( $numMatches >= 4 ) ||
$this->mForceTocPosition
);
3584 # Allow user to stipulate that a page should have a "new section"
3585 # link added via __NEWSECTIONLINK__
3586 if ( isset( $this->mDoubleUnderscores
['newsectionlink'] ) ) {
3587 $this->mOutput
->setNewSection( true );
3590 # Allow user to remove the "new section"
3591 # link via __NONEWSECTIONLINK__
3592 if ( isset( $this->mDoubleUnderscores
['nonewsectionlink'] ) ) {
3593 $this->mOutput
->hideNewSection( true );
3596 # if the string __FORCETOC__ (not case-sensitive) occurs in the HTML,
3597 # override above conditions and always show TOC above first header
3598 if ( isset( $this->mDoubleUnderscores
['forcetoc'] ) ) {
3599 $this->mShowToc
= true;
3603 # We need this to perform operations on the HTML
3604 $sk = $this->mOptions
->getSkin();
3610 # Ugh .. the TOC should have neat indentation levels which can be
3611 # passed to the skin functions. These are determined here
3615 $sublevelCount = array();
3616 $levelCount = array();
3622 $markerRegex = "{$this->mUniqPrefix}-h-(\d+)-" . self
::MARKER_SUFFIX
;
3623 $baseTitleText = $this->mTitle
->getPrefixedDBkey();
3624 $oldType = $this->mOutputType
;
3625 $this->setOutputType( self
::OT_WIKI
);
3626 $frame = $this->getPreprocessor()->newFrame();
3627 $root = $this->preprocessToDom( $origText );
3628 $node = $root->getFirstChild();
3632 foreach ( $matches[3] as $headline ) {
3633 $isTemplate = false;
3635 $sectionIndex = false;
3637 $markerMatches = array();
3638 if ( preg_match("/^$markerRegex/", $headline, $markerMatches ) ) {
3639 $serial = $markerMatches[1];
3640 list( $titleText, $sectionIndex ) = $this->mHeadings
[$serial];
3641 $isTemplate = ( $titleText != $baseTitleText );
3642 $headline = preg_replace( "/^$markerRegex/", "", $headline );
3646 $prevlevel = $level;
3647 $prevtoclevel = $toclevel;
3649 $level = $matches[1][$headlineCount];
3651 if ( $level > $prevlevel ) {
3652 # Increase TOC level
3654 $sublevelCount[$toclevel] = 0;
3655 if ( $toclevel<$wgMaxTocLevel ) {
3656 $prevtoclevel = $toclevel;
3657 $toc .= $sk->tocIndent();
3660 } elseif ( $level < $prevlevel && $toclevel > 1 ) {
3661 # Decrease TOC level, find level to jump to
3663 for ( $i = $toclevel; $i > 0; $i-- ) {
3664 if ( $levelCount[$i] == $level ) {
3665 # Found last matching level
3668 } elseif ( $levelCount[$i] < $level ) {
3669 # Found first matching level below current level
3677 if ( $toclevel<$wgMaxTocLevel ) {
3678 if ( $prevtoclevel < $wgMaxTocLevel ) {
3679 # Unindent only if the previous toc level was shown :p
3680 $toc .= $sk->tocUnindent( $prevtoclevel - $toclevel );
3681 $prevtoclevel = $toclevel;
3683 $toc .= $sk->tocLineEnd();
3687 # No change in level, end TOC line
3688 if ( $toclevel<$wgMaxTocLevel ) {
3689 $toc .= $sk->tocLineEnd();
3693 $levelCount[$toclevel] = $level;
3695 # count number of headlines for each level
3696 @$sublevelCount[$toclevel]++
;
3698 for( $i = 1; $i <= $toclevel; $i++
) {
3699 if ( !empty( $sublevelCount[$i] ) ) {
3703 $numbering .= $wgContLang->formatNum( $sublevelCount[$i] );
3708 # The safe header is a version of the header text safe to use for links
3709 # Avoid insertion of weird stuff like <math> by expanding the relevant sections
3710 $safeHeadline = $this->mStripState
->unstripBoth( $headline );
3712 # Remove link placeholders by the link text.
3713 # <!--LINK number-->
3715 # link text with suffix
3716 $safeHeadline = $this->replaceLinkHoldersText( $safeHeadline );
3718 # Strip out HTML (other than plain <sup> and <sub>: bug 8393)
3719 $tocline = preg_replace(
3720 array( '#<(?!/?(sup|sub)).*?'.'>#', '#<(/?(sup|sub)).*?'.'>#' ),
3721 array( '', '<$1>' ),
3724 $tocline = trim( $tocline );
3726 # For the anchor, strip out HTML-y stuff period
3727 $safeHeadline = preg_replace( '/<.*?'.'>/', '', $safeHeadline );
3728 $safeHeadline = preg_replace( '/[ _]+/', ' ', $safeHeadline );
3729 $safeHeadline = trim( $safeHeadline );
3731 # Save headline for section edit hint before it's escaped
3732 $headlineHint = $safeHeadline;
3734 if ( $wgHtml5 && $wgExperimentalHtmlIds ) {
3735 # For reverse compatibility, provide an id that's
3736 # HTML4-compatible, like we used to.
3738 # It may be worth noting, academically, that it's possible for
3739 # the legacy anchor to conflict with a non-legacy headline
3740 # anchor on the page. In this case likely the "correct" thing
3741 # would be to either drop the legacy anchors or make sure
3742 # they're numbered first. However, this would require people
3743 # to type in section names like "abc_.D7.93.D7.90.D7.A4"
3744 # manually, so let's not bother worrying about it.
3745 $legacyHeadline = Sanitizer
::escapeId( $safeHeadline,
3746 array( 'noninitial', 'legacy' ) );
3747 $safeHeadline = Sanitizer
::escapeId( $safeHeadline );
3749 if ( $legacyHeadline == $safeHeadline ) {
3750 # No reason to have both (in fact, we can't)
3751 $legacyHeadline = false;
3754 $legacyHeadline = false;
3755 $safeHeadline = Sanitizer
::escapeId( $safeHeadline,
3759 # HTML names must be case-insensitively unique (bug 10721). FIXME:
3760 # Does this apply to Unicode characters? Because we aren't
3761 # handling those here.
3762 $arrayKey = strtolower( $safeHeadline );
3763 if ( $legacyHeadline === false ) {
3764 $legacyArrayKey = false;
3766 $legacyArrayKey = strtolower( $legacyHeadline );
3769 # count how many in assoc. array so we can track dupes in anchors
3770 if ( isset( $refers[$arrayKey] ) ) {
3771 $refers[$arrayKey]++
;
3773 $refers[$arrayKey] = 1;
3775 if ( isset( $refers[$legacyArrayKey] ) ) {
3776 $refers[$legacyArrayKey]++
;
3778 $refers[$legacyArrayKey] = 1;
3781 # Don't number the heading if it is the only one (looks silly)
3782 if ( $doNumberHeadings && count( $matches[3] ) > 1) {
3783 # the two are different if the line contains a link
3784 $headline = $numbering . ' ' . $headline;
3787 # Create the anchor for linking from the TOC to the section
3788 $anchor = $safeHeadline;
3789 $legacyAnchor = $legacyHeadline;
3790 if ( $refers[$arrayKey] > 1 ) {
3791 $anchor .= '_' . $refers[$arrayKey];
3793 if ( $legacyHeadline !== false && $refers[$legacyArrayKey] > 1 ) {
3794 $legacyAnchor .= '_' . $refers[$legacyArrayKey];
3796 if ( $enoughToc && ( !isset( $wgMaxTocLevel ) ||
$toclevel < $wgMaxTocLevel ) ) {
3797 $toc .= $sk->tocLine( $anchor, $tocline,
3798 $numbering, $toclevel, ( $isTemplate ?
false : $sectionIndex ) );
3801 # Add the section to the section tree
3802 # Find the DOM node for this header
3803 while ( $node && !$isTemplate ) {
3804 if ( $node->getName() === 'h' ) {
3805 $bits = $node->splitHeading();
3806 if ( $bits['i'] == $sectionIndex )
3809 $byteOffset +
= mb_strlen( $this->mStripState
->unstripBoth(
3810 $frame->expand( $node, PPFrame
::RECOVER_ORIG
) ) );
3811 $node = $node->getNextSibling();
3814 'toclevel' => $toclevel,
3817 'number' => $numbering,
3818 'index' => ( $isTemplate ?
'T-' : '' ) . $sectionIndex,
3819 'fromtitle' => $titleText,
3820 'byteoffset' => ( $isTemplate ?
null : $byteOffset ),
3821 'anchor' => $anchor,
3824 # give headline the correct <h#> tag
3825 if ( $showEditLink && $sectionIndex !== false ) {
3826 if ( $isTemplate ) {
3827 # Put a T flag in the section identifier, to indicate to extractSections()
3828 # that sections inside <includeonly> should be counted.
3829 $editlink = $sk->doEditSectionLink( Title
::newFromText( $titleText ), "T-$sectionIndex" );
3831 $editlink = $sk->doEditSectionLink( $this->mTitle
, $sectionIndex, $headlineHint );
3836 $head[$headlineCount] = $sk->makeHeadline( $level,
3837 $matches['attrib'][$headlineCount], $anchor, $headline,
3838 $editlink, $legacyAnchor );
3843 $this->setOutputType( $oldType );
3845 # Never ever show TOC if no headers
3846 if ( $numVisible < 1 ) {
3851 if ( $prevtoclevel > 0 && $prevtoclevel < $wgMaxTocLevel ) {
3852 $toc .= $sk->tocUnindent( $prevtoclevel - 1 );
3854 $toc = $sk->tocList( $toc );
3855 $this->mOutput
->setTOCHTML( $toc );
3859 $this->mOutput
->setSections( $tocraw );
3862 # split up and insert constructed headlines
3864 $blocks = preg_split( '/<H[1-6].*?' . '>.*?<\/H[1-6]>/i', $text );
3867 foreach ( $blocks as $block ) {
3868 if ( $showEditLink && $headlineCount > 0 && $i == 0 && $block !== "\n" ) {
3869 # This is the [edit] link that appears for the top block of text when
3870 # section editing is enabled
3872 # Disabled because it broke block formatting
3873 # For example, a bullet point in the top line
3874 # $full .= $sk->editSectionLink(0);
3877 if ( $enoughToc && !$i && $isMain && !$this->mForceTocPosition
) {
3878 # Top anchor now in skin
3882 if ( !empty( $head[$i] ) ) {
3887 if ( $this->mForceTocPosition
) {
3888 return str_replace( '<!--MWTOC-->', $toc, $full );
3895 * Merge $tree2 into $tree1 by replacing the section with index
3896 * $section in $tree1 and its descendants with the sections in $tree2.
3897 * Note that in the returned section tree, only the 'index' and
3898 * 'byteoffset' fields are guaranteed to be correct.
3899 * @param $tree1 array Section tree from ParserOutput::getSectons()
3900 * @param $tree2 array Section tree
3901 * @param $section int Section index
3902 * @param $title Title Title both section trees come from
3903 * @param $len2 int Length of the original wikitext for $tree2
3904 * @return array Merged section tree
3906 public static function mergeSectionTrees( $tree1, $tree2, $section, $title, $len2 ) {
3909 $targetLevel = false;
3913 $numbering = array( 0 );
3914 $titletext = $title->getPrefixedDBkey();
3915 foreach ( $tree1 as $s ) {
3916 if ( $targetLevel !== false ) {
3917 if ( $s['level'] <= $targetLevel ) {
3918 # We've skipped enough
3919 $targetLevel = false;
3924 if ( $s['index'] != $section ||
3925 $s['fromtitle'] != $titletext ) {
3926 self
::incrementNumbering( $numbering,
3927 $s['toclevel'], $lastLevel );
3929 # Rewrite index, byteoffset and number
3930 if ( $s['fromtitle'] == $titletext ) {
3931 $s['index'] = $nextIndex++
;
3933 $s['byteoffset'] +
= $len2;
3936 $s['number'] = implode( '.', array_map(
3937 array( $wgContLang, 'formatnum' ),
3939 $lastLevel = $s['toclevel'];
3943 # Insert sections from $tree2 here
3944 foreach ( $tree2 as $s2 ) {
3945 # Rewrite the fields in $s2
3946 # before inserting it
3947 $s2['toclevel'] +
= $s['toclevel'] - 1;
3948 $s2['level'] +
= $s['level'] - 1;
3949 $s2['index'] = $nextIndex++
;
3950 $s2['byteoffset'] +
= $s['byteoffset'];
3952 self
::incrementNumbering( $numbering,
3953 $s2['toclevel'], $lastLevel );
3954 $s2['number'] = implode( '.', array_map(
3955 array( $wgContLang, 'formatnum' ),
3957 $lastLevel = $s2['toclevel'];
3960 # Skip all descendants of $section in $tree1
3961 $targetLevel = $s['level'];
3969 * Increment a section number. Helper function for mergeSectionTrees()
3970 * @param $number array Array representing a section number
3971 * @param $level int Current TOC level (depth)
3972 * @param $lastLevel int Level of previous TOC entry
3974 private static function incrementNumbering( &$number, $level, $lastLevel ) {
3975 if ( $level > $lastLevel ) {
3976 $number[$level - 1] = 1;
3977 } elseif ( $level < $lastLevel ) {
3978 foreach ( $number as $key => $unused )
3979 if ( $key >= $level ) {
3980 unset( $number[$key] );
3982 $number[$level - 1]++
;
3984 $number[$level - 1]++
;
3989 * Transform wiki markup when saving a page by doing \r\n -> \n
3990 * conversion, substitting signatures, {{subst:}} templates, etc.
3992 * @param string $text the text to transform
3993 * @param Title &$title the Title object for the current article
3994 * @param User $user the User object describing the current user
3995 * @param ParserOptions $options parsing options
3996 * @param bool $clearState whether to clear the parser state first
3997 * @return string the altered wiki markup
4000 function preSaveTransform( $text, Title
$title, $user, $options, $clearState = true ) {
4001 $this->mOptions
= $options;
4002 $this->setTitle( $title );
4003 $this->setOutputType( self
::OT_WIKI
);
4005 if ( $clearState ) {
4006 $this->clearState();
4012 $text = str_replace( array_keys( $pairs ), array_values( $pairs ), $text );
4013 $text = $this->pstPass2( $text, $user );
4014 $text = $this->mStripState
->unstripBoth( $text );
4019 * Pre-save transform helper function
4022 function pstPass2( $text, $user ) {
4023 global $wgContLang, $wgLocaltimezone;
4025 # Note: This is the timestamp saved as hardcoded wikitext to
4026 # the database, we use $wgContLang here in order to give
4027 # everyone the same signature and use the default one rather
4028 # than the one selected in each user's preferences.
4029 # (see also bug 12815)
4030 $ts = $this->mOptions
->getTimestamp();
4031 if ( isset( $wgLocaltimezone ) ) {
4032 $tz = $wgLocaltimezone;
4034 $tz = date_default_timezone_get();
4037 $unixts = wfTimestamp( TS_UNIX
, $ts );
4038 $oldtz = date_default_timezone_get();
4039 date_default_timezone_set( $tz );
4040 $ts = date( 'YmdHis', $unixts );
4041 $tzMsg = date( 'T', $unixts ); # might vary on DST changeover!
4043 # Allow translation of timezones trough wiki. date() can return
4044 # whatever crap the system uses, localised or not, so we cannot
4045 # ship premade translations.
4046 $key = 'timezone-' . strtolower( trim( $tzMsg ) );
4047 $value = wfMsgForContent( $key );
4048 if ( !wfEmptyMsg( $key, $value ) ) {
4052 date_default_timezone_set( $oldtz );
4054 $d = $wgContLang->timeanddate( $ts, false, false ) . " ($tzMsg)";
4056 # Variable replacement
4057 # Because mOutputType is OT_WIKI, this will only process {{subst:xxx}} type tags
4058 $text = $this->replaceVariables( $text );
4061 $sigText = $this->getUserSig( $user );
4062 $text = strtr( $text, array(
4064 '~~~~' => "$sigText $d",
4068 # Context links: [[|name]] and [[name (context)|]]
4069 global $wgLegalTitleChars;
4070 $tc = "[$wgLegalTitleChars]";
4071 $nc = '[ _0-9A-Za-z\x80-\xff-]'; # Namespaces can use non-ascii!
4073 $p1 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\))\\|]]/"; # [[ns:page (context)|]]
4074 $p4 = "/\[\[(:?$nc+:|:|)($tc+?)(($tc+))\\|]]/"; # [[ns:page(context)|]]
4075 $p3 = "/\[\[(:?$nc+:|:|)($tc+?)( \\($tc+\\)|)(, $tc+|)\\|]]/"; # [[ns:page (context), context|]]
4076 $p2 = "/\[\[\\|($tc+)]]/"; # [[|page]]
4078 # try $p1 first, to turn "[[A, B (C)|]]" into "[[A, B (C)|A, B]]"
4079 $text = preg_replace( $p1, '[[\\1\\2\\3|\\2]]', $text );
4080 $text = preg_replace( $p4, '[[\\1\\2\\3|\\2]]', $text );
4081 $text = preg_replace( $p3, '[[\\1\\2\\3\\4|\\2]]', $text );
4083 $t = $this->mTitle
->getText();
4085 if ( preg_match( "/^($nc+:|)$tc+?( \\($tc+\\))$/", $t, $m ) ) {
4086 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4087 } elseif ( preg_match( "/^($nc+:|)$tc+?(, $tc+|)$/", $t, $m ) && "$m[1]$m[2]" != '' ) {
4088 $text = preg_replace( $p2, "[[$m[1]\\1$m[2]|\\1]]", $text );
4090 # if there's no context, don't bother duplicating the title
4091 $text = preg_replace( $p2, '[[\\1]]', $text );
4094 # Trim trailing whitespace
4095 $text = rtrim( $text );
4101 * Fetch the user's signature text, if any, and normalize to
4102 * validated, ready-to-insert wikitext.
4103 * If you have pre-fetched the nickname or the fancySig option, you can
4104 * specify them here to save a database query.
4109 function getUserSig( &$user, $nickname = false, $fancySig = null ) {
4110 global $wgMaxSigChars;
4112 $username = $user->getName();
4114 # If not given, retrieve from the user object.
4115 if ( $nickname === false )
4116 $nickname = $user->getOption( 'nickname' );
4118 if ( is_null( $fancySig ) ) {
4119 $fancySig = $user->getBoolOption( 'fancysig' );
4122 $nickname = $nickname == null ?
$username : $nickname;
4124 if ( mb_strlen( $nickname ) > $wgMaxSigChars ) {
4125 $nickname = $username;
4126 wfDebug( __METHOD__
. ": $username has overlong signature.\n" );
4127 } elseif ( $fancySig !== false ) {
4128 # Sig. might contain markup; validate this
4129 if ( $this->validateSig( $nickname ) !== false ) {
4130 # Validated; clean up (if needed) and return it
4131 return $this->cleanSig( $nickname, true );
4133 # Failed to validate; fall back to the default
4134 $nickname = $username;
4135 wfDebug( __METHOD__
.": $username has bad XML tags in signature.\n" );
4139 # Make sure nickname doesnt get a sig in a sig
4140 $nickname = $this->cleanSigInSig( $nickname );
4142 # If we're still here, make it a link to the user page
4143 $userText = wfEscapeWikiText( $username );
4144 $nickText = wfEscapeWikiText( $nickname );
4145 if ( $user->isAnon() ) {
4146 return wfMsgExt( 'signature-anon', array( 'content', 'parsemag' ), $userText, $nickText );
4148 return wfMsgExt( 'signature', array( 'content', 'parsemag' ), $userText, $nickText );
4153 * Check that the user's signature contains no bad XML
4155 * @param string $text
4156 * @return mixed An expanded string, or false if invalid.
4158 function validateSig( $text ) {
4159 return( Xml
::isWellFormedXmlFragment( $text ) ?
$text : false );
4163 * Clean up signature text
4165 * 1) Strip ~~~, ~~~~ and ~~~~~ out of signatures @see cleanSigInSig
4166 * 2) Substitute all transclusions
4168 * @param string $text
4169 * @param $parsing Whether we're cleaning (preferences save) or parsing
4170 * @return string Signature text
4172 function cleanSig( $text, $parsing = false ) {
4175 $this->clearState();
4176 $this->setTitle( $wgTitle );
4177 $this->mOptions
= new ParserOptions
;
4178 $this->setOutputType
= self
::OT_PREPROCESS
;
4181 # Option to disable this feature
4182 if ( !$this->mOptions
->getCleanSignatures() ) {
4186 # FIXME: regex doesn't respect extension tags or nowiki
4187 # => Move this logic to braceSubstitution()
4188 $substWord = MagicWord
::get( 'subst' );
4189 $substRegex = '/\{\{(?!(?:' . $substWord->getBaseRegex() . '))/x' . $substWord->getRegexCase();
4190 $substText = '{{' . $substWord->getSynonym( 0 );
4192 $text = preg_replace( $substRegex, $substText, $text );
4193 $text = $this->cleanSigInSig( $text );
4194 $dom = $this->preprocessToDom( $text );
4195 $frame = $this->getPreprocessor()->newFrame();
4196 $text = $frame->expand( $dom );
4199 $text = $this->mStripState
->unstripBoth( $text );
4206 * Strip ~~~, ~~~~ and ~~~~~ out of signatures
4207 * @param string $text
4208 * @return string Signature text with /~{3,5}/ removed
4210 function cleanSigInSig( $text ) {
4211 $text = preg_replace( '/~{3,5}/', '', $text );
4216 * Set up some variables which are usually set up in parse()
4217 * so that an external function can call some class members with confidence
4220 function startExternalParse( &$title, $options, $outputType, $clearState = true ) {
4221 $this->setTitle( $title );
4222 $this->mOptions
= $options;
4223 $this->setOutputType( $outputType );
4224 if ( $clearState ) {
4225 $this->clearState();
4230 * Wrapper for preprocess()
4232 * @param string $text the text to preprocess
4233 * @param ParserOptions $options options
4237 function transformMsg( $text, $options ) {
4239 static $executing = false;
4241 # Guard against infinite recursion
4247 wfProfileIn( __METHOD__
);
4248 $text = $this->preprocess( $text, $wgTitle, $options );
4251 wfProfileOut( __METHOD__
);
4256 * Create an HTML-style tag, e.g. <yourtag>special text</yourtag>
4257 * The callback should have the following form:
4258 * function myParserHook( $text, $params, $parser ) { ... }
4260 * Transform and return $text. Use $parser for any required context, e.g. use
4261 * $parser->getTitle() and $parser->getOptions() not $wgTitle or $wgOut->mParserOptions
4265 * @param mixed $tag The tag to use, e.g. 'hook' for <hook>
4266 * @param mixed $callback The callback function (and object) to use for the tag
4268 * @return The old value of the mTagHooks array associated with the hook
4270 function setHook( $tag, $callback ) {
4271 $tag = strtolower( $tag );
4272 $oldVal = isset( $this->mTagHooks
[$tag] ) ?
$this->mTagHooks
[$tag] : null;
4273 $this->mTagHooks
[$tag] = $callback;
4274 if ( !in_array( $tag, $this->mStripList
) ) {
4275 $this->mStripList
[] = $tag;
4281 function setTransparentTagHook( $tag, $callback ) {
4282 $tag = strtolower( $tag );
4283 $oldVal = isset( $this->mTransparentTagHooks
[$tag] ) ?
$this->mTransparentTagHooks
[$tag] : null;
4284 $this->mTransparentTagHooks
[$tag] = $callback;
4290 * Remove all tag hooks
4292 function clearTagHooks() {
4293 $this->mTagHooks
= array();
4294 $this->mStripList
= $this->mDefaultStripList
;
4298 * Create a function, e.g. {{sum:1|2|3}}
4299 * The callback function should have the form:
4300 * function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
4302 * Or with SFH_OBJECT_ARGS:
4303 * function myParserFunction( $parser, $frame, $args ) { ... }
4305 * The callback may either return the text result of the function, or an array with the text
4306 * in element 0, and a number of flags in the other elements. The names of the flags are
4307 * specified in the keys. Valid flags are:
4308 * found The text returned is valid, stop processing the template. This
4310 * nowiki Wiki markup in the return value should be escaped
4311 * isHTML The returned text is HTML, armour it against wikitext transformation
4315 * @param string $id The magic word ID
4316 * @param mixed $callback The callback function (and object) to use
4317 * @param integer $flags a combination of the following flags:
4318 * SFH_NO_HASH No leading hash, i.e. {{plural:...}} instead of {{#if:...}}
4320 * SFH_OBJECT_ARGS Pass the template arguments as PPNode objects instead of text. This
4321 * allows for conditional expansion of the parse tree, allowing you to eliminate dead
4322 * branches and thus speed up parsing. It is also possible to analyse the parse tree of
4323 * the arguments, and to control the way they are expanded.
4325 * The $frame parameter is a PPFrame. This can be used to produce expanded text from the
4326 * arguments, for instance:
4327 * $text = isset( $args[0] ) ? $frame->expand( $args[0] ) : '';
4329 * For technical reasons, $args[0] is pre-expanded and will be a string. This may change in
4330 * future versions. Please call $frame->expand() on it anyway so that your code keeps
4331 * working if/when this is changed.
4333 * If you want whitespace to be trimmed from $args, you need to do it yourself, post-
4336 * Please read the documentation in includes/parser/Preprocessor.php for more information
4337 * about the methods available in PPFrame and PPNode.
4339 * @return The old callback function for this name, if any
4341 function setFunctionHook( $id, $callback, $flags = 0 ) {
4344 $oldVal = isset( $this->mFunctionHooks
[$id] ) ?
$this->mFunctionHooks
[$id][0] : null;
4345 $this->mFunctionHooks
[$id] = array( $callback, $flags );
4347 # Add to function cache
4348 $mw = MagicWord
::get( $id );
4350 throw new MWException( __METHOD__
.'() expecting a magic word identifier.' );
4352 $synonyms = $mw->getSynonyms();
4353 $sensitive = intval( $mw->isCaseSensitive() );
4355 foreach ( $synonyms as $syn ) {
4357 if ( !$sensitive ) {
4358 $syn = $wgContLang->lc( $syn );
4361 if ( !( $flags & SFH_NO_HASH
) ) {
4364 # Remove trailing colon
4365 if ( substr( $syn, -1, 1 ) === ':' ) {
4366 $syn = substr( $syn, 0, -1 );
4368 $this->mFunctionSynonyms
[$sensitive][$syn] = $id;
4374 * Get all registered function hook identifiers
4378 function getFunctionHooks() {
4379 return array_keys( $this->mFunctionHooks
);
4383 * Create a tag function, e.g. <test>some stuff</test>.
4384 * Unlike tag hooks, tag functions are parsed at preprocessor level.
4385 * Unlike parser functions, their content is not preprocessed.
4387 function setFunctionTagHook( $tag, $callback, $flags ) {
4388 $tag = strtolower( $tag );
4389 $old = isset( $this->mFunctionTagHooks
[$tag] ) ?
4390 $this->mFunctionTagHooks
[$tag] : null;
4391 $this->mFunctionTagHooks
[$tag] = array( $callback, $flags );
4393 if ( !in_array( $tag, $this->mStripList
) ) {
4394 $this->mStripList
[] = $tag;
4401 * FIXME: update documentation. makeLinkObj() is deprecated.
4402 * Replace <!--LINK--> link placeholders with actual links, in the buffer
4403 * Placeholders created in Skin::makeLinkObj()
4404 * Returns an array of link CSS classes, indexed by PDBK.
4406 function replaceLinkHolders( &$text, $options = 0 ) {
4407 return $this->mLinkHolders
->replace( $text );
4411 * Replace <!--LINK--> link placeholders with plain text of links
4412 * (not HTML-formatted).
4413 * @param string $text
4416 function replaceLinkHoldersText( $text ) {
4417 return $this->mLinkHolders
->replaceText( $text );
4421 * Renders an image gallery from a text with one line per image.
4422 * text labels may be given by using |-style alternative text. E.g.
4423 * Image:one.jpg|The number "1"
4424 * Image:tree.jpg|A tree
4425 * given as text will return the HTML of a gallery with two images,
4426 * labeled 'The number "1"' and
4429 function renderImageGallery( $text, $params ) {
4430 $ig = new ImageGallery();
4431 $ig->setContextTitle( $this->mTitle
);
4432 $ig->setShowBytes( false );
4433 $ig->setShowFilename( false );
4434 $ig->setParser( $this );
4435 $ig->setHideBadImages();
4436 $ig->setAttributes( Sanitizer
::validateTagAttributes( $params, 'table' ) );
4437 $ig->useSkin( $this->mOptions
->getSkin() );
4438 $ig->mRevisionId
= $this->mRevisionId
;
4440 if ( isset( $params['showfilename'] ) ) {
4441 $ig->setShowFilename( true );
4443 $ig->setShowFilename( false );
4445 if ( isset( $params['caption'] ) ) {
4446 $caption = $params['caption'];
4447 $caption = htmlspecialchars( $caption );
4448 $caption = $this->replaceInternalLinks( $caption );
4449 $ig->setCaptionHtml( $caption );
4451 if ( isset( $params['perrow'] ) ) {
4452 $ig->setPerRow( $params['perrow'] );
4454 if ( isset( $params['widths'] ) ) {
4455 $ig->setWidths( $params['widths'] );
4457 if ( isset( $params['heights'] ) ) {
4458 $ig->setHeights( $params['heights'] );
4461 wfRunHooks( 'BeforeParserrenderImageGallery', array( &$this, &$ig ) );
4463 $lines = StringUtils
::explode( "\n", $text );
4464 foreach ( $lines as $line ) {
4465 # match lines like these:
4466 # Image:someimage.jpg|This is some image
4468 preg_match( "/^([^|]+)(\\|(.*))?$/", $line, $matches );
4470 if ( count( $matches ) == 0 ) {
4474 if ( strpos( $matches[0], '%' ) !== false ) {
4475 $matches[1] = urldecode( $matches[1] );
4477 $tp = Title
::newFromText( $matches[1] );
4479 if ( is_null( $nt ) ) {
4480 # Bogus title. Ignore these so we don't bomb out later.
4483 if ( isset( $matches[3] ) ) {
4484 $label = $matches[3];
4489 $html = $this->recursiveTagParse( trim( $label ) );
4491 $ig->add( $nt, $html );
4493 # Only add real images (bug #5586)
4494 if ( $nt->getNamespace() == NS_FILE
) {
4495 $this->mOutput
->addImage( $nt->getDBkey() );
4498 return $ig->toHTML();
4501 function getImageParams( $handler ) {
4503 $handlerClass = get_class( $handler );
4507 if ( !isset( $this->mImageParams
[$handlerClass] ) ) {
4508 # Initialise static lists
4509 static $internalParamNames = array(
4510 'horizAlign' => array( 'left', 'right', 'center', 'none' ),
4511 'vertAlign' => array( 'baseline', 'sub', 'super', 'top', 'text-top', 'middle',
4512 'bottom', 'text-bottom' ),
4513 'frame' => array( 'thumbnail', 'manualthumb', 'framed', 'frameless',
4514 'upright', 'border', 'link', 'alt' ),
4516 static $internalParamMap;
4517 if ( !$internalParamMap ) {
4518 $internalParamMap = array();
4519 foreach ( $internalParamNames as $type => $names ) {
4520 foreach ( $names as $name ) {
4521 $magicName = str_replace( '-', '_', "img_$name" );
4522 $internalParamMap[$magicName] = array( $type, $name );
4527 # Add handler params
4528 $paramMap = $internalParamMap;
4530 $handlerParamMap = $handler->getParamMap();
4531 foreach ( $handlerParamMap as $magic => $paramName ) {
4532 $paramMap[$magic] = array( 'handler', $paramName );
4535 $this->mImageParams
[$handlerClass] = $paramMap;
4536 $this->mImageParamsMagicArray
[$handlerClass] = new MagicWordArray( array_keys( $paramMap ) );
4538 return array( $this->mImageParams
[$handlerClass], $this->mImageParamsMagicArray
[$handlerClass] );
4542 * Parse image options text and use it to make an image
4543 * @param Title $title
4544 * @param string $options
4545 * @param LinkHolderArray $holders
4547 function makeImage( $title, $options, $holders = false ) {
4548 # Check if the options text is of the form "options|alt text"
4550 # * thumbnail make a thumbnail with enlarge-icon and caption, alignment depends on lang
4551 # * left no resizing, just left align. label is used for alt= only
4552 # * right same, but right aligned
4553 # * none same, but not aligned
4554 # * ___px scale to ___ pixels width, no aligning. e.g. use in taxobox
4555 # * center center the image
4556 # * frame Keep original image size, no magnify-button.
4557 # * framed Same as "frame"
4558 # * frameless like 'thumb' but without a frame. Keeps user preferences for width
4559 # * upright reduce width for upright images, rounded to full __0 px
4560 # * border draw a 1px border around the image
4561 # * alt Text for HTML alt attribute (defaults to empty)
4562 # * link Set the target of the image link. Can be external, interwiki, or local
4563 # vertical-align values (no % or length right now):
4573 $parts = StringUtils
::explode( "|", $options );
4574 $sk = $this->mOptions
->getSkin();
4576 # Give extensions a chance to select the file revision for us
4577 $skip = $time = $descQuery = false;
4578 wfRunHooks( 'BeforeParserMakeImageLinkObj', array( &$this, &$title, &$skip, &$time, &$descQuery ) );
4581 return $sk->link( $title );
4585 $imagename = $title->getDBkey();
4586 $file = wfFindFile( $title, array( 'time' => $time ) );
4588 $handler = $file ?
$file->getHandler() : false;
4590 list( $paramMap, $mwArray ) = $this->getImageParams( $handler );
4592 # Process the input parameters
4594 $params = array( 'frame' => array(), 'handler' => array(),
4595 'horizAlign' => array(), 'vertAlign' => array() );
4596 foreach ( $parts as $part ) {
4597 $part = trim( $part );
4598 list( $magicName, $value ) = $mwArray->matchVariableStartToEnd( $part );
4600 if ( isset( $paramMap[$magicName] ) ) {
4601 list( $type, $paramName ) = $paramMap[$magicName];
4603 # Special case; width and height come in one variable together
4604 if ( $type === 'handler' && $paramName === 'width' ) {
4606 # (bug 13500) In both cases (width/height and width only),
4607 # permit trailing "px" for backward compatibility.
4608 if ( preg_match( '/^([0-9]*)x([0-9]*)\s*(?:px)?\s*$/', $value, $m ) ) {
4609 $width = intval( $m[1] );
4610 $height = intval( $m[2] );
4611 if ( $handler->validateParam( 'width', $width ) ) {
4612 $params[$type]['width'] = $width;
4615 if ( $handler->validateParam( 'height', $height ) ) {
4616 $params[$type]['height'] = $height;
4619 } elseif ( preg_match( '/^[0-9]*\s*(?:px)?\s*$/', $value ) ) {
4620 $width = intval( $value );
4621 if ( $handler->validateParam( 'width', $width ) ) {
4622 $params[$type]['width'] = $width;
4625 } # else no validation -- bug 13436
4627 if ( $type === 'handler' ) {
4628 # Validate handler parameter
4629 $validated = $handler->validateParam( $paramName, $value );
4631 # Validate internal parameters
4632 switch( $paramName ) {
4635 # @todo Fixme: possibly check validity here for
4636 # manualthumb? downstream behavior seems odd with
4637 # missing manual thumbs.
4639 $value = $this->stripAltText( $value, $holders );
4642 $chars = self
::EXT_LINK_URL_CLASS
;
4643 $prots = $this->mUrlProtocols
;
4644 if ( $value === '' ) {
4645 $paramName = 'no-link';
4648 } elseif ( preg_match( "/^$prots/", $value ) ) {
4649 if ( preg_match( "/^($prots)$chars+$/", $value, $m ) ) {
4650 $paramName = 'link-url';
4651 $this->mOutput
->addExternalLink( $value );
4655 $linkTitle = Title
::newFromText( $value );
4657 $paramName = 'link-title';
4658 $value = $linkTitle;
4659 $this->mOutput
->addLink( $linkTitle );
4665 # Most other things appear to be empty or numeric...
4666 $validated = ( $value === false ||
is_numeric( trim( $value ) ) );
4671 $params[$type][$paramName] = $value;
4675 if ( !$validated ) {
4680 # Process alignment parameters
4681 if ( $params['horizAlign'] ) {
4682 $params['frame']['align'] = key( $params['horizAlign'] );
4684 if ( $params['vertAlign'] ) {
4685 $params['frame']['valign'] = key( $params['vertAlign'] );
4688 $params['frame']['caption'] = $caption;
4690 # Will the image be presented in a frame, with the caption below?
4691 $imageIsFramed = isset( $params['frame']['frame'] ) ||
4692 isset( $params['frame']['framed'] ) ||
4693 isset( $params['frame']['thumbnail'] ) ||
4694 isset( $params['frame']['manualthumb'] );
4696 # In the old days, [[Image:Foo|text...]] would set alt text. Later it
4697 # came to also set the caption, ordinary text after the image -- which
4698 # makes no sense, because that just repeats the text multiple times in
4699 # screen readers. It *also* came to set the title attribute.
4701 # Now that we have an alt attribute, we should not set the alt text to
4702 # equal the caption: that's worse than useless, it just repeats the
4703 # text. This is the framed/thumbnail case. If there's no caption, we
4704 # use the unnamed parameter for alt text as well, just for the time be-
4705 # ing, if the unnamed param is set and the alt param is not.
4707 # For the future, we need to figure out if we want to tweak this more,
4708 # e.g., introducing a title= parameter for the title; ignoring the un-
4709 # named parameter entirely for images without a caption; adding an ex-
4710 # plicit caption= parameter and preserving the old magic unnamed para-
4712 if ( $imageIsFramed ) { # Framed image
4713 if ( $caption === '' && !isset( $params['frame']['alt'] ) ) {
4714 # No caption or alt text, add the filename as the alt text so
4715 # that screen readers at least get some description of the image
4716 $params['frame']['alt'] = $title->getText();
4718 # Do not set $params['frame']['title'] because tooltips don't make sense
4720 } else { # Inline image
4721 if ( !isset( $params['frame']['alt'] ) ) {
4722 # No alt text, use the "caption" for the alt text
4723 if ( $caption !== '') {
4724 $params['frame']['alt'] = $this->stripAltText( $caption, $holders );
4726 # No caption, fall back to using the filename for the
4728 $params['frame']['alt'] = $title->getText();
4731 # Use the "caption" for the tooltip text
4732 $params['frame']['title'] = $this->stripAltText( $caption, $holders );
4735 wfRunHooks( 'ParserMakeImageParams', array( $title, $file, &$params ) );
4737 # Linker does the rest
4738 $ret = $sk->makeImageLink2( $title, $file, $params['frame'], $params['handler'], $time, $descQuery );
4740 # Give the handler a chance to modify the parser object
4742 $handler->parserTransformHook( $this, $file );
4748 protected function stripAltText( $caption, $holders ) {
4749 # Strip bad stuff out of the title (tooltip). We can't just use
4750 # replaceLinkHoldersText() here, because if this function is called
4751 # from replaceInternalLinks2(), mLinkHolders won't be up-to-date.
4753 $tooltip = $holders->replaceText( $caption );
4755 $tooltip = $this->replaceLinkHoldersText( $caption );
4758 # make sure there are no placeholders in thumbnail attributes
4759 # that are later expanded to html- so expand them now and
4761 $tooltip = $this->mStripState
->unstripBoth( $tooltip );
4762 $tooltip = Sanitizer
::stripAllTags( $tooltip );
4768 * Set a flag in the output object indicating that the content is dynamic and
4769 * shouldn't be cached.
4771 function disableCache() {
4772 wfDebug( "Parser output marked as uncacheable.\n" );
4773 $this->mOutput
->mCacheTime
= -1;
4777 * Callback from the Sanitizer for expanding items found in HTML attribute
4778 * values, so they can be safely tested and escaped.
4779 * @param string $text
4780 * @param PPFrame $frame
4784 function attributeStripCallback( &$text, $frame = false ) {
4785 $text = $this->replaceVariables( $text, $frame );
4786 $text = $this->mStripState
->unstripBoth( $text );
4795 function Title( $x = null ) { return wfSetVar( $this->mTitle
, $x ); }
4796 function Options( $x = null ) { return wfSetVar( $this->mOptions
, $x ); }
4797 function OutputType( $x = null ) { return wfSetVar( $this->mOutputType
, $x ); }
4803 function getTags() {
4804 return array_merge( array_keys( $this->mTransparentTagHooks
), array_keys( $this->mTagHooks
) );
4810 * Break wikitext input into sections, and either pull or replace
4811 * some particular section's text.
4813 * External callers should use the getSection and replaceSection methods.
4815 * @param string $text Page wikitext
4816 * @param string $section A section identifier string of the form:
4817 * <flag1> - <flag2> - ... - <section number>
4819 * Currently the only recognised flag is "T", which means the target section number
4820 * was derived during a template inclusion parse, in other words this is a template
4821 * section edit link. If no flags are given, it was an ordinary section edit link.
4822 * This flag is required to avoid a section numbering mismatch when a section is
4823 * enclosed by <includeonly> (bug 6563).
4825 * The section number 0 pulls the text before the first heading; other numbers will
4826 * pull the given section along with its lower-level subsections. If the section is
4827 * not found, $mode=get will return $newtext, and $mode=replace will return $text.
4829 * @param string $mode One of "get" or "replace"
4830 * @param string $newText Replacement text for section data.
4831 * @return string for "get", the extracted section text.
4832 * for "replace", the whole page with the section replaced.
4834 private function extractSections( $text, $section, $mode, $newText='' ) {
4836 $this->clearState();
4837 $this->setTitle( $wgTitle ); # not generally used but removes an ugly failure mode
4838 $this->mOptions
= new ParserOptions
;
4839 $this->setOutputType( self
::OT_PLAIN
);
4841 $frame = $this->getPreprocessor()->newFrame();
4843 # Process section extraction flags
4845 $sectionParts = explode( '-', $section );
4846 $sectionIndex = array_pop( $sectionParts );
4847 foreach ( $sectionParts as $part ) {
4848 if ( $part === 'T' ) {
4849 $flags |
= self
::PTD_FOR_INCLUSION
;
4852 # Preprocess the text
4853 $root = $this->preprocessToDom( $text, $flags );
4855 # <h> nodes indicate section breaks
4856 # They can only occur at the top level, so we can find them by iterating the root's children
4857 $node = $root->getFirstChild();
4859 # Find the target section
4860 if ( $sectionIndex == 0 ) {
4861 # Section zero doesn't nest, level=big
4862 $targetLevel = 1000;
4865 if ( $node->getName() === 'h' ) {
4866 $bits = $node->splitHeading();
4867 if ( $bits['i'] == $sectionIndex ) {
4868 $targetLevel = $bits['level'];
4872 if ( $mode === 'replace' ) {
4873 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4875 $node = $node->getNextSibling();
4881 if ( $mode === 'get' ) {
4888 # Find the end of the section, including nested sections
4890 if ( $node->getName() === 'h' ) {
4891 $bits = $node->splitHeading();
4892 $curLevel = $bits['level'];
4893 if ( $bits['i'] != $sectionIndex && $curLevel <= $targetLevel ) {
4897 if ( $mode === 'get' ) {
4898 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4900 $node = $node->getNextSibling();
4903 # Write out the remainder (in replace mode only)
4904 if ( $mode === 'replace' ) {
4905 # Output the replacement text
4906 # Add two newlines on -- trailing whitespace in $newText is conventionally
4907 # stripped by the editor, so we need both newlines to restore the paragraph gap
4908 # Only add trailing whitespace if there is newText
4909 if ( $newText != "" ) {
4910 $outText .= $newText . "\n\n";
4914 $outText .= $frame->expand( $node, PPFrame
::RECOVER_ORIG
);
4915 $node = $node->getNextSibling();
4919 if ( is_string( $outText ) ) {
4920 # Re-insert stripped tags
4921 $outText = rtrim( $this->mStripState
->unstripBoth( $outText ) );
4928 * This function returns the text of a section, specified by a number ($section).
4929 * A section is text under a heading like == Heading == or \<h1\>Heading\</h1\>, or
4930 * the first section before any such heading (section 0).
4932 * If a section contains subsections, these are also returned.
4934 * @param string $text text to look in
4935 * @param string $section section identifier
4936 * @param string $deftext default to return if section is not found
4937 * @return string text of the requested section
4939 public function getSection( $text, $section, $deftext='' ) {
4940 return $this->extractSections( $text, $section, "get", $deftext );
4943 public function replaceSection( $oldtext, $section, $text ) {
4944 return $this->extractSections( $oldtext, $section, "replace", $text );
4948 * Get the timestamp associated with the current revision, adjusted for
4949 * the default server-local timestamp
4951 function getRevisionTimestamp() {
4952 if ( is_null( $this->mRevisionTimestamp
) ) {
4953 wfProfileIn( __METHOD__
);
4955 $dbr = wfGetDB( DB_SLAVE
);
4956 $timestamp = $dbr->selectField( 'revision', 'rev_timestamp',
4957 array( 'rev_id' => $this->mRevisionId
), __METHOD__
);
4959 # Normalize timestamp to internal MW format for timezone processing.
4960 # This has the added side-effect of replacing a null value with
4961 # the current time, which gives us more sensible behavior for
4963 $timestamp = wfTimestamp( TS_MW
, $timestamp );
4965 # The cryptic '' timezone parameter tells to use the site-default
4966 # timezone offset instead of the user settings.
4968 # Since this value will be saved into the parser cache, served
4969 # to other users, and potentially even used inside links and such,
4970 # it needs to be consistent for all visitors.
4971 $this->mRevisionTimestamp
= $wgContLang->userAdjust( $timestamp, '' );
4973 wfProfileOut( __METHOD__
);
4975 return $this->mRevisionTimestamp
;
4979 * Get the name of the user that edited the last revision
4981 function getRevisionUser() {
4982 # if this template is subst: the revision id will be blank,
4983 # so just use the current user's name
4984 if ( $this->mRevisionId
) {
4985 $revision = Revision
::newFromId( $this->mRevisionId
);
4986 $revuser = $revision->getUserText();
4989 $revuser = $wgUser->getName();
4995 * Mutator for $mDefaultSort
4997 * @param $sort New value
4999 public function setDefaultSort( $sort ) {
5000 $this->mDefaultSort
= $sort;
5004 * Accessor for $mDefaultSort
5005 * Will use the title/prefixed title if none is set
5009 public function getDefaultSort() {
5010 global $wgCategoryPrefixedDefaultSortkey;
5011 if ( $this->mDefaultSort
!== false ) {
5012 return $this->mDefaultSort
;
5013 } elseif ( $this->mTitle
->getNamespace() == NS_CATEGORY ||
5014 !$wgCategoryPrefixedDefaultSortkey )
5016 return $this->mTitle
->getText();
5018 return $this->mTitle
->getPrefixedText();
5023 * Accessor for $mDefaultSort
5024 * Unlike getDefaultSort(), will return false if none is set
5026 * @return string or false
5028 public function getCustomDefaultSort() {
5029 return $this->mDefaultSort
;
5033 * Try to guess the section anchor name based on a wikitext fragment
5034 * presumably extracted from a heading, for example "Header" from
5037 public function guessSectionNameFromWikiText( $text ) {
5038 # Strip out wikitext links(they break the anchor)
5039 $text = $this->stripSectionName( $text );
5040 $headline = Sanitizer
::decodeCharReferences( $text );
5042 $headline = StringUtils
::delimiterReplace( '<', '>', '', $headline );
5043 $headline = trim( $headline );
5044 $sectionanchor = '#' . urlencode( str_replace( ' ', '_', $headline ) );
5045 $replacearray = array(
5050 array_keys( $replacearray ),
5051 array_values( $replacearray ),
5056 * Strips a text string of wikitext for use in a section anchor
5058 * Accepts a text string and then removes all wikitext from the
5059 * string and leaves only the resultant text (i.e. the result of
5060 * [[User:WikiSysop|Sysop]] would be "Sysop" and the result of
5061 * [[User:WikiSysop]] would be "User:WikiSysop") - this is intended
5062 * to create valid section anchors by mimicing the output of the
5063 * parser when headings are parsed.
5065 * @param $text string Text string to be stripped of wikitext
5066 * for use in a Section anchor
5067 * @return Filtered text string
5069 public function stripSectionName( $text ) {
5070 # Strip internal link markup
5071 $text = preg_replace( '/\[\[:?([^[|]+)\|([^[]+)\]\]/', '$2', $text );
5072 $text = preg_replace( '/\[\[:?([^[]+)\|?\]\]/', '$1', $text );
5074 # Strip external link markup (FIXME: Not Tolerant to blank link text
5075 # I.E. [http://www.mediawiki.org] will render as [1] or something depending
5076 # on how many empty links there are on the page - need to figure that out.
5077 $text = preg_replace( '/\[(?:' . wfUrlProtocols() . ')([^ ]+?) ([^[]+)\]/', '$2', $text );
5079 # Parse wikitext quotes (italics & bold)
5080 $text = $this->doQuotes( $text );
5083 $text = StringUtils
::delimiterReplace( '<', '>', '', $text );
5087 function srvus( $text ) {
5088 return $this->testSrvus( $text, $this->mOutputType
);
5092 * strip/replaceVariables/unstrip for preprocessor regression testing
5094 function testSrvus( $text, $title, $options, $outputType = self
::OT_HTML
) {
5095 $this->clearState();
5096 if ( !$title instanceof Title
) {
5097 $title = Title
::newFromText( $title );
5099 $this->mTitle
= $title;
5100 $this->mOptions
= $options;
5101 $this->setOutputType( $outputType );
5102 $text = $this->replaceVariables( $text );
5103 $text = $this->mStripState
->unstripBoth( $text );
5104 $text = Sanitizer
::removeHTMLtags( $text );
5108 function testPst( $text, $title, $options ) {
5110 if ( !$title instanceof Title
) {
5111 $title = Title
::newFromText( $title );
5113 return $this->preSaveTransform( $text, $title, $wgUser, $options );
5116 function testPreprocess( $text, $title, $options ) {
5117 if ( !$title instanceof Title
) {
5118 $title = Title
::newFromText( $title );
5120 return $this->testSrvus( $text, $title, $options, self
::OT_PREPROCESS
);
5123 function markerSkipCallback( $s, $callback ) {
5126 while ( $i < strlen( $s ) ) {
5127 $markerStart = strpos( $s, $this->mUniqPrefix
, $i );
5128 if ( $markerStart === false ) {
5129 $out .= call_user_func( $callback, substr( $s, $i ) );
5132 $out .= call_user_func( $callback, substr( $s, $i, $markerStart - $i ) );
5133 $markerEnd = strpos( $s, self
::MARKER_SUFFIX
, $markerStart );
5134 if ( $markerEnd === false ) {
5135 $out .= substr( $s, $markerStart );
5138 $markerEnd +
= strlen( self
::MARKER_SUFFIX
);
5139 $out .= substr( $s, $markerStart, $markerEnd - $markerStart );
5147 function serialiseHalfParsedText( $text ) {
5149 $data['text'] = $text;
5151 # First, find all strip markers, and store their
5153 $stripState = new StripState
;
5155 while ( ( $start_pos = strpos( $text, $this->mUniqPrefix
, $pos ) )
5156 && ( $end_pos = strpos( $text, self
::MARKER_SUFFIX
, $pos ) ) )
5158 $end_pos +
= strlen( self
::MARKER_SUFFIX
);
5159 $marker = substr( $text, $start_pos, $end_pos-$start_pos );
5161 if ( !empty( $this->mStripState
->general
->data
[$marker] ) ) {
5162 $replaceArray = $stripState->general
;
5163 $stripText = $this->mStripState
->general
->data
[$marker];
5164 } elseif ( !empty( $this->mStripState
->nowiki
->data
[$marker] ) ) {
5165 $replaceArray = $stripState->nowiki
;
5166 $stripText = $this->mStripState
->nowiki
->data
[$marker];
5168 throw new MWException( "Hanging strip marker: '$marker'." );
5171 $replaceArray->setPair( $marker, $stripText );
5174 $data['stripstate'] = $stripState;
5176 # Now, find all of our links, and store THEIR
5177 # data in an array! :)
5178 $links = array( 'internal' => array(), 'interwiki' => array() );
5182 while ( ( $start_pos = strpos( $text, '<!--LINK ', $pos ) ) ) {
5183 list( $ns, $trail ) = explode( ':', substr( $text, $start_pos +
strlen( '<!--LINK ' ) ), 2 );
5186 if ( empty( $links['internal'][$ns] ) ) {
5187 $links['internal'][$ns] = array();
5190 $key = trim( substr( $trail, 0, strpos( $trail, '-->' ) ) );
5191 $links['internal'][$ns][] = $this->mLinkHolders
->internals
[$ns][$key];
5192 $pos = $start_pos +
strlen( "<!--LINK $ns:$key-->" );
5198 while ( ( $start_pos = strpos( $text, '<!--IWLINK ', $pos ) ) ) {
5199 $data = substr( $text, $start_pos );
5200 $key = trim( substr( $data, 0, strpos( $data, '-->' ) ) );
5201 $links['interwiki'][] = $this->mLinkHolders
->interwiki
[$key];
5202 $pos = $start_pos +
strlen( "<!--IWLINK $key-->" );
5205 $data['linkholder'] = $links;
5212 * @param $data Array
5213 * @param $intPrefix String unique identifying prefix
5216 function unserialiseHalfParsedText( $data, $intPrefix = null ) {
5217 if ( !$intPrefix ) {
5218 $intPrefix = $this->getRandomString();
5221 # First, extract the strip state.
5222 $stripState = $data['stripstate'];
5223 $this->mStripState
->general
->merge( $stripState->general
);
5224 $this->mStripState
->nowiki
->merge( $stripState->nowiki
);
5226 # Now, extract the text, and renumber links
5227 $text = $data['text'];
5228 $links = $data['linkholder'];
5231 foreach ( $links['internal'] as $ns => $nsLinks ) {
5232 foreach ( $nsLinks as $key => $entry ) {
5233 $newKey = $intPrefix . '-' . $key;
5234 $this->mLinkHolders
->internals
[$ns][$newKey] = $entry;
5236 $text = str_replace( "<!--LINK $ns:$key-->", "<!--LINK $ns:$newKey-->", $text );
5241 foreach ( $links['interwiki'] as $key => $entry ) {
5242 $newKey = "$intPrefix-$key";
5243 $this->mLinkHolders
->interwikis
[$newKey] = $entry;
5245 $text = str_replace( "<!--IWLINK $key-->", "<!--IWLINK $newKey-->", $text );
5248 # Should be good to go.
5254 * @todo document, briefly.
5258 var $general, $nowiki;
5260 function __construct() {
5261 $this->general
= new ReplacementArray
;
5262 $this->nowiki
= new ReplacementArray
;
5265 function unstripGeneral( $text ) {
5266 wfProfileIn( __METHOD__
);
5269 $text = $this->general
->replace( $text );
5270 } while ( $text !== $oldText );
5271 wfProfileOut( __METHOD__
);
5275 function unstripNoWiki( $text ) {
5276 wfProfileIn( __METHOD__
);
5279 $text = $this->nowiki
->replace( $text );
5280 } while ( $text !== $oldText );
5281 wfProfileOut( __METHOD__
);
5285 function unstripBoth( $text ) {
5286 wfProfileIn( __METHOD__
);
5289 $text = $this->general
->replace( $text );
5290 $text = $this->nowiki
->replace( $text );
5291 } while ( $text !== $oldText );
5292 wfProfileOut( __METHOD__
);
5298 * @todo document, briefly.
5301 class OnlyIncludeReplacer
{
5304 function replace( $matches ) {
5305 if ( substr( $matches[1], -1 ) === "\n" ) {
5306 $this->output
.= substr( $matches[1], 0, -1 );
5308 $this->output
.= $matches[1];